Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 107 additions & 14 deletions src/AccountStateStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
EnginePositionSide,
EngineSimplePosition,
} from './lib/types/position.js';
import { AbstractAssetBalance } from './lib/types/wallet.js';
import { getUnrealisedPNL } from './util/math.js';


Expand All @@ -23,8 +24,8 @@ export class AccountStateStore<
> {
private isPendingPersistPositionMetadata = false;

// symbol:leverageValue
private accountLeverageState: Record<string, number> = {};
// symbol:buyLeverageValue,sellLeverageValue
private accountLeverageState: Record<string, { buy: number, sell: number }> = {};

// per symbol, per side, cache a copy of the position state
private accountPositionState: Record<
Expand All @@ -43,25 +44,32 @@ export class AccountStateStore<
// Store all active orders, keyed by "endineOrder.exchangeOrderId"
private accountOrders: Map<string, EngineOrder> = new Map();

// Store asset balances by asset symbol
private accountAssetBalances: Map<string, AbstractAssetBalance> = new Map();

private accountOtherState = {
balance: 0,
previousBalance: 0,
hedgedPositions: 0,
};

dumpLogState(): void {
console.log(
`Position dump: `,
JSON.stringify(
dumpLogState(): string | void {
try {
// Using string concatenation instead of console.log
const stateString = JSON.stringify(
{
accountLeverageState: this.accountLeverageState,
acconutPositionState: this.accountPositionState,
accountOtherState: this.accountOtherState,
},
null,
2,
),
);
);
// Handle in a way that doesn't require console
return stateString;
} catch (error) {
// Silently handle errors
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were you seeing exceptions here? Why not log the error?

}
}

/**
Expand Down Expand Up @@ -96,10 +104,13 @@ export class AccountStateStore<
public getSessionSummary(startingBalance: number) {
const balanceNow = this.getWalletBalance();

const positions = this.getAllPositions().map((pos) => ({
...pos,
leverage: this.getSymbolLeverage(pos.symbol),
}));
const positions = this.getAllPositions().map((pos) => {
const leverageData = this.getSymbolLeverage(pos.symbol);
return {
...pos,
leverage: pos.positionSide === 'LONG' ? leverageData?.buy : leverageData?.sell,
};
});

let activePositionUpnlSum = 0;
let quoteMarginLockedSum = 0;
Expand Down Expand Up @@ -243,13 +254,25 @@ export class AccountStateStore<
return true;
}
setSymbolLeverage(symbol: string, leverage: number): void {
this.accountLeverageState[symbol] = leverage;
this.accountLeverageState[symbol] = { buy: leverage, sell: leverage };
}
Comment on lines 256 to 258
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good that you kept the symbol leverage setter without a side - less friction for upgrading to this


getSymbolLeverage(symbol: string): number | undefined {
setSymbolSideLeverage(symbol: string, side: 'buy' | 'sell', leverage: number): void {
if (!this.accountLeverageState[symbol]) {
this.accountLeverageState[symbol] = { buy: leverage, sell: leverage };
} else {
this.accountLeverageState[symbol][side] = leverage;
}
}

getSymbolLeverage(symbol: string): { buy: number, sell: number } | undefined {
return this.accountLeverageState[symbol];
}

getSymbolSideLeverage(symbol: string, side: 'buy' | 'sell'): number | undefined {
return this.accountLeverageState[symbol]?.[side];
}

getSymbolLeverageCache() {
return this.accountLeverageState;
}
Expand Down Expand Up @@ -495,4 +518,74 @@ export class AccountStateStore<
return ascending ? comparison : -comparison;
});
}

/**
* Get all stored asset balances
*/
getAllAssetBalances(): AbstractAssetBalance[] {
return Array.from(this.accountAssetBalances.values());
}

/**
* Get balance for a specific asset
*/
getAssetBalance(asset: string): AbstractAssetBalance | undefined {
return this.accountAssetBalances.get(asset);
}

/**
* Update or add an asset balance
*/
upsertAssetBalance(assetBalance: AbstractAssetBalance): void {
this.accountAssetBalances.set(assetBalance.asset, assetBalance);
}

/**
* Update or add multiple asset balances at once
*/
upsertAssetBalances(assetBalances: AbstractAssetBalance[]): void {
for (const balance of assetBalances) {
this.upsertAssetBalance(balance);
}
}

/**
* Remove an asset balance
*/
deleteAssetBalance(asset: string): boolean {
return this.accountAssetBalances.delete(asset);
}

/**
* Clear all asset balances
*/
clearAssetBalances(): void {
this.accountAssetBalances.clear();
}

/**
* Get total free balance value across all assets
* This assumes the 'free' property is already in the same denomination
*/
getTotalFreeBalance(): number {
let total = 0;
for (const balance of this.accountAssetBalances.values()) {
total += parseFloat(balance.free) || 0;
}
return total;
}

/**
* Get asset balances filtered by a predicate
*/
filterAssetBalances(predicate: (balance: AbstractAssetBalance) => boolean): AbstractAssetBalance[] {
return this.getAllAssetBalances().filter(predicate);
}

/**
* Get a list of all asset symbols
*/
getAssetSymbols(): string[] {
return Array.from(this.accountAssetBalances.keys());
}
}
51 changes: 51 additions & 0 deletions src/lib/misc/mappings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { AbstractAssetBalance, BybitCoinData, BybitWalletData } from "lib/types/wallet";

/**
* Maps BybitWalletData to AbstractWalletData
* @param bybitWalletData The Bybit wallet data to map
* @returns AbstractWalletData
*/
export function mapBybitWalletToAbstract(bybitWalletData: BybitWalletData): AbstractWalletData {
return {
accountType: bybitWalletData.accountType,
updateTime: Date.now(),
balances: bybitWalletData.coin.map((coin: any) => mapBybitCoinToAbstractAsset(coin)),
accountIMRate: bybitWalletData.accountIMRate,
accountMMRate: bybitWalletData.accountMMRate,
totalEquity: bybitWalletData.totalEquity,
totalWalletBalance: bybitWalletData.totalWalletBalance,
totalMarginBalance: bybitWalletData.totalMarginBalance,
totalAvailableBalance: bybitWalletData.totalAvailableBalance,
totalPerpUPL: bybitWalletData.totalPerpUPL,
totalInitialMargin: bybitWalletData.totalInitialMargin,
totalMaintenanceMargin: bybitWalletData.totalMaintenanceMargin,
accountLTV: bybitWalletData.accountLTV
};
}

/**
* Maps BybitCoinData to AbstractAssetBalance
* @param bybitCoinData The Bybit coin data to map
* @returns AbstractAssetBalance
*/
export function mapBybitCoinToAbstractAsset(bybitCoinData: BybitCoinData): AbstractAssetBalance {
return {
asset: bybitCoinData.coin,
free: bybitCoinData.walletBalance,
locked: bybitCoinData.locked || "0",
walletBalance: bybitCoinData.walletBalance,
unrealisedPnl: bybitCoinData.unrealisedPnl,
cumRealisedPnl: bybitCoinData.cumRealisedPnl,
availableToWithdraw: bybitCoinData.availableToWithdraw,
availableToBorrow: bybitCoinData.availableToBorrow,
borrowAmount: bybitCoinData.borrowAmount,
accruedInterest: bybitCoinData.accruedInterest,
totalOrderIM: bybitCoinData.totalOrderIM,
totalPositionIM: bybitCoinData.totalPositionIM,
totalPositionMM: bybitCoinData.totalPositionMM,
bonus: bybitCoinData.bonus,
collateralSwitch: bybitCoinData.collateralSwitch,
marginCollateral: bybitCoinData.marginCollateral,
spotHedgingQty: bybitCoinData.spotHedgingQty
};
}
67 changes: 67 additions & 0 deletions src/lib/types/wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
export interface BybitCoinData {
coin: string;
equity: string;
usdValue: string;
walletBalance: string;
availableToWithdraw: string;
availableToBorrow: string;
borrowAmount: string;
accruedInterest: string;
totalOrderIM: string;
totalPositionIM: string;
totalPositionMM: string;
unrealisedPnl: string;
cumRealisedPnl: string;
bonus: string;
collateralSwitch: boolean;
marginCollateral: boolean;
locked: string;
spotHedgingQty: string;
}

export interface BybitWalletData {
accountIMRate: string;
accountMMRate: string;
totalEquity: string;
totalWalletBalance: string;
totalMarginBalance: string;
totalAvailableBalance: string;
totalPerpUPL: string;
totalInitialMargin: string;
totalMaintenanceMargin: string;
coin: BybitCoinData[];
accountLTV: string;
accountType: string;
}

export interface AbstractAssetBalance {
// Common properties
asset: string; // Asset symbol (e.g., "BTC", "ETH")
free: string; // Available balance for trading
locked: string; // Balance locked in open orders

// Optional properties that may be available in some exchanges
borrowed?: string; // Amount borrowed (margin trading)
interest?: string; // Interest on borrowed amount
netAsset?: string; // Net asset value (free + locked - borrowed)
unrealizedPnl?: string; // Unrealized profit/loss
marginBalance?: string; // Margin balance
initialMargin?: string; // Initial margin
maintenanceMargin?: string; // Maintenance margin
positionInitialMargin?: string; // Position initial margin
openOrderInitialMargin?: string; // Open order initial margin
walletBalance?: string; // Total wallet balance
unrealisedPnl?: string; // Alternative spelling for unrealizedPnl
cumRealisedPnl?: string; // Cumulative realized profit/loss
availableToWithdraw?: string; // Available for withdrawal
availableToBorrow?: string; // Available for borrowing
borrowAmount?: string; // Current borrow amount
accruedInterest?: string; // Accrued interest
totalOrderIM?: string; // Total order initial margin
totalPositionIM?: string; // Total position initial margin
totalPositionMM?: string; // Total position maintenance margin
bonus?: string; // Bonus amount
collateralSwitch?: boolean; // Whether asset can be used as collateral
marginCollateral?: boolean; // Whether asset is used as margin collateral
spotHedgingQty?: string; // Spot hedging quantity
}