-
Notifications
You must be signed in to change notification settings - Fork 6
feat(): added direction for leverage and wallet storage #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
UjmaIT
wants to merge
1
commit into
sieblyio:master
Choose a base branch
from
UjmaIT:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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'; | ||
|
|
||
|
|
||
|
|
@@ -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< | ||
|
|
@@ -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 | ||
| } | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -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; | ||
|
|
@@ -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
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
| } | ||
|
|
@@ -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()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?