import { API, OrderSide, OrderType } from '@orderly.network/types'; import { Decimal } from '@orderly.network/utils'; declare global { interface Window { __ORDERLY_VERSION__?: { [key: string]: string; }; } } declare const _default: "5.1.2"; /** * Calculates the notional value of a single position. * @param qty The quantity of the position. * @param mark_price The price of the position. * @returns The notional value of the position. */ declare function notional(qty: number, mark_price: number): number; /** * @formulaId totalNotional * @name Total Notional * @formula Total Notional = sum ( abs(position_qty_i * mark_price_i) ) * @description * ## Term Definitions * * - **Total Notional**: Sum of current position notional values * - **position_qty_i**: Single symbol position quantity * - **mark_price_i**: Single symbol mark price * * ## Example * * **Total Notional** = 10112.43 * * **abs(BTC position notional)** = 5197.2 * * **abs(ETH position notional)** = 4915.23 * * @param positions The array of positions. * @returns The total notional value of all positions. */ declare function totalNotional(positions: API.Position[]): number; /** @deprecated Use inline type or the new input type instead */ type UnrealPnLInputs = { markPrice: number; openPrice: number; qty: number; }; /** * @formulaId unrealizedPnL * @description Calculates the unrealized profit or loss of a single position. * This formula applies to both cross margin and isolated margin positions. * @formula Unrealized PnL = position_qty * (mark_price - entry_price) * @param inputs The inputs for calculating the unrealized profit or loss. * @returns The unrealized profit or loss of the position (in USDC). */ declare function unrealizedPnL(inputs: { /** symbol mark price */ markPrice: number; /** symbol open price (entry price) */ openPrice: number; /** symbol quantity (position quantity, positive for long, negative for short) */ qty: number; }): number; /** * @formulaId unrealizedPnLROI * @name Position unrealized ROI * @formula Position unrealized ROI = Position unrealized PNL / ( IMR_i * abs(position_qty_i * entry_price_i) ) * 100%, IMR_i = Max(1 / Symbol Leverage i, Base IMR i, IMR Factor i * Abs(Position Notional i)^(4/5)) * @description * ## Term Definitions * * - **Position unrealized ROI**: Single symbol unrealized return on investment * - **Position unrealized PNL**: Single symbol unrealized profit and loss * - **IMR_i**: Single symbol initial margin rate * - **Symbol Leverage_i**: Current leverage for symbol i under current margin mode * - **Base IMR_i**: Single symbol base initial margin rate * - **IMR Factor_i**: Single symbol IMR calculation factor, from v1/client/info * - **Position Notional_i**: Single symbol position notional sum * - **position_qty_i**: Single symbol position quantity * - **entry_price_i**: Single symbol entry price (avg. open price) * * ## Example * * **Position unrealized ROI** = Position unrealized PNL / (IMR_i * abs(position_qty_i * entry_price_i)) * 100% = 216.69 / (0.1 * abs(-3 * 1710.64)) * 100% = 42.22% * * **ETH IMR_i** = Max(1/10, 0.1, 0.0000003754 * abs(-4915.23)^(4/5)) = Max(0.1, 0.1, 0.000337077174) = 0.1 * * - Symbol Leverage_i = 10 * - ETH Base IMR_i = 0.1 * - ETH IMR Factor_i = 0.0000003754 * - ETH position_qty_i = -3 * - ETH entry_price_i = 1710.64 * - ETH mark_price_i = 1638.41 * - ETH Position Notional = -3 * 1638.41 = -4915.23 * - ETH Position unrealized PNL = 216.69 * * @param inputs The inputs for calculating the ROI. * @returns The ROI of the position's unrealized profit or loss. */ declare function unrealizedPnLROI(inputs: { positionQty: number; openPrice: number; IMR: number; unrealizedPnL: number; }): number; /** * @formulaId totalUnrealizedPnl * @name Total Unrealized PNL * @formula Total Unrealized PNL = sum ( unrealized_pnl_i ), unrealized_pnl_i = position_qty_i * ( mark_price_i - entry_price _i ) * @description * ## Term Definitions * * - **Total Unrealized PNL**: Sum of all current unrealized profit and loss for user's positions * - **unrealized_pnl_i**: Current unrealized profit and loss for a single symbol * - **position_qty_i**: Single symbol position quantity * - **mark_price_i**: Single symbol mark price * - **entry_price_i**: Single symbol entry price (avg. open price) * * ## Example * * ``` * BTC-PERP unrealized_pnl_i = 0.2 * (25986.2 - 26067) = -16.16 * ETH-PERP unrealized_pnl_i = -3 * (1638.41 - 1710.64) = 216.69 * * Total Unrealized PNL = -16.16 + 216.69 = 200.53 * ``` * @param positions The array of positions. * @returns The total unrealized profit or loss of all positions. */ declare function totalUnrealizedPnL(positions: API.Position[]): number; /** * @formulaId liqPrice * @name Position Liquidation Price * @description * * ## Define: * * ### (1) calculate_liq_price function * * ``` * calculate_liq_price( mark_price, position_qty, mmr ) * ``` * * If `position_qty >= 0` AND if `abs(position_qty) * mmr - position_qty >= 0`: * * Return `mark_price` * * Else: * * Return `max( mark_price + [ total_collateral_value - abs(position_qty) * mark_price * mmr - mm_for_other_symbols ] / [ abs(position_qty) * mmr - position_qty ], 0 )` * * Where `total_collateral_value` and `mm_for_other_symbols` are constants. * * - **total_collateral_value** * - **mm_for_other_symbols** = `sum_i ( abs(position_qty_i) * mark_price_i * mmr_i )` for i != current symbol * * ### (2) compare_collateral_w_mm function * * ``` * compare_collateral_w_mm( price ) = collateral >= mm * ``` * * Where: * - **collateral** = `total_collateral_value - position_qty_i * mark_price + position_qty_i * price` * - **mm** = `abs(position_qty_i) * price * Max(Base MMR i, (Base MMR i / Base IMR i) * IMR Factor i * Abs(position_qty_i * price)^(4/5)) + mm_for_other_symbols` * * ## Given: * * Position liquidation price for symbol i with: * - current mark price = `mark_price_i` * - current position qty = `position_qty_i` * - current mmr = `mmr_i = Max(Base MMR i, (Base MMR i / Base IMR i) * IMR Factor i * Abs(Position Notional i)^(4/5))` * - symbol base mmr = `base_mmr_i` * * ## For LONG position * * ``` * liq_price_left = calculate_liq_price( mark_price_i, position_qty_i, base_mmr_i ) * liq_price_right = calculate_liq_price( mark_price_i, position_qty_i, mmr_i ) * * ITERATE 30 times: * if liq_price_left >= liq_price_right: * return liq_price_right * * mid = ( liq_price_left + liq_price_right ) / 2 * * if compare_collateral_w_mm( mid ): * liq_price_right = mid * else: * liq_price_left = mid * * if (liq_price_right - liq_price_left) / (liq_price_left + liq_price_right) * 2 <= 0.0001: * break * * return liq_price_right * ``` * * ## For SHORT position * * ``` * liq_price_right = calculate_liq_price( mark_price_i, position_qty_i, mmr_i ) * liq_price_left = calculate_liq_price( mark_price_i, position_qty_i, * Max(Base MMR i, (Base MMR i / Base IMR i) * IMR Factor i * Abs(position_qty_i * liq_price_right)^(4/5)) * ) * * ITERATE 30 times: * if liq_price_left >= liq_price_right: * return liq_price_left * * mid = ( liq_price_left + liq_price_right ) / 2 * * if compare_collateral_w_mm( mid ): * liq_price_left = mid * else: * liq_price_right = mid * * if (liq_price_right - liq_price_left) / (liq_price_left + liq_price_right) * 2 <= 0.0001: * break * * return liq_price_left * ``` * * @returns The liquidation price of the position. */ declare function liqPrice(inputs: { markPrice: number; symbol: string; totalCollateral: number; positionQty: number; positions: Pick[]; MMR: number; baseMMR: number; baseIMR: number; IMRFactor: number; costPosition: number; }): number | null; /** * @formulaId maintenanceMargin * @name Position maintenance margin * @formula Position maintenance margin = abs (position_qty_i * mark_price_i * MMR_i ) * @description * ## Term Definitions * * - **Position maintenance margin**: Single symbol maintenance margin * - **MMR_i**: Single symbol maintenance margin rate * - **Base MMR_i**: Single symbol base maintenance margin rate * - **Base IMR_i**: Single symbol base initial margin rate * - **IMR Factor_i**: Single symbol IMR calculation factor, from v1/client/info * - **Position Notional_i**: Single symbol position notional sum * - **position_qty_i**: Single symbol position quantity * - **mark_price_i**: Single symbol mark price * * ## MMR Formula * * MMR_i = Max(Base MMR_i, (Base MMR_i / Base IMR_i) * IMR Factor_i * Abs(Position Notional_i)^(4/5)) * * ## Example * * **BTC Position maintenance margin** = abs(position_qty_i * mark_price_i * MMR_i) = abs(0.2 * 25986.2 * 0.05) = 259.86 * * **BTC MMR_i** = Max(0.05, (0.05 / 0.1) * 0.0000002512 * 5197.2^(4/5)) = Max(0.05, 0.000117924809) = 0.05 * * - BTC Base MMR_i = 0.05 * - BTC Base IMR_i = 0.1 * - BTC IMR Factor_i = 0.0000002512 * - Abs(BTC Position Notional_i) = 5197.2 * - position_qty_i = 0.2 * - mark_price_i = 25986.2 * * @param inputs The inputs for calculating the maintenance margin. * @returns The maintenance margin of the position. */ declare function maintenanceMargin(inputs: { positionQty: number; markPrice: number; MMR: number; }): number; /** @deprecated Use inline type or the new input type instead */ type LiqPriceInputs = { markPrice: number; totalCollateral: number; positionQty: number; positions: Pick[]; MMR: number; }; /** * @formulaId unsettlementPnl * @name Position Unrealized PNL * @formula Position Unrealized PNL = position_qty_i * (mark_price_i - entry_price_i) * @description * ## Term Definitions * * - **Position Unrealized PNL**: Single symbol unrealized profit and loss * - **position_qty_i**: Single symbol position quantity * - **mark_price_i**: Single symbol mark price * - **entry_price_i**: Single symbol entry price (avg. open price) * * ## Example * * **ETH Position Unrealized PNL** = position_qty_i * (mark_price_i - entry_price_i) = -3 * (1638.41 - 1710.64) = 216.69 * * - ETH position_qty_i = -3 * - ETH mark_price_i = 1638.41 * - ETH entry_price_i = 1710.64 * * @param inputs The inputs for calculating the unrealized profit or loss. * @returns The unrealized profit or loss of each position. */ declare function unsettlementPnL(inputs: { positionQty: number; markPrice: number; costPosition: number; sumUnitaryFunding: number; lastSumUnitaryFunding: number; }): number; /** * @formulaId totalUnsettlementPnL * @name Total Unsettlement PNL * @formula Unsettlement PNL = position_qty_i * mark_price_i - cost_position_i - position_qty_i * (sum_unitary_funding_i - last_sum_unitary_funding_i) * @description * ## Term Definitions * * - **total unsettlement PNL**: Sum of user account's unsettled PNL * - **mark_price_i**: Single symbol mark price * - **position_qty_i**: Single symbol position quantity * - **cost_position_i**: Single symbol notional snapshot from last settlement, `/v1/position` * - **sum_unitary_funding_i**: Single symbol current cumulative unit funding fee, `/v1/public/funding_rate` * - **last_sum_unitary_funding_i**: Single symbol cumulative unit funding fee from last settlement, `/v1/position` * * ## Example * * **BTC-PERP Unsettlement PNL** = 0.2 * 25986.2 - 5197.2 - 0.2 * (-1585.92 + 1583.92) = 0.44 * * **ETH-PERP Unsettlement PNL** = -3 * 1638.41 + 4902.45 + 3 * (-52.728 + 50.728) = -18.78 * * **Total Unsettlement PNL** = 0.44 - 18.78 = -18.34 * * @param positions The array of positions. * @returns The total unrealized profit or loss of all positions. */ declare function totalUnsettlementPnL(positions: (API.Position & { sum_unitary_funding: number; })[]): number; /** * @formulaId MMR * @name Position Maintenance Margin Rate * @formula MMR_i = Max(Base MMR_i, (Base MMR_i / Base IMR_i) * IMR Factor_i * Abs(Position Notional_i)^(4/5)) * @description * ## Term Definitions * * - **MMR_i**: Single symbol maintenance margin rate * - **Base MMR_i**: Single symbol base maintenance margin rate * - **Base IMR_i**: Single symbol base initial margin rate * - **IMR Factor_i**: Single symbol IMR calculation factor, from v1/client/info * - **Position Notional_i**: Single symbol position notional sum * - **position_qty_i**: Single symbol position quantity * - **mark_price_i**: Single symbol mark price * * ## Example * * **BTC MMR_i** = Max(0.05, (0.05 / 0.1) * 0.0000002512 * 5197.2^(4/5)) = Max(0.05, 0.000117924809) = 0.05 * * - BTC Base MMR_i = 0.05 * - BTC Base IMR_i = 0.1 * - BTC IMR Factor_i = 0.0000002512 * - Abs(BTC Position Notional_i) = 5197.2 * - position_qty_i = 0.2 * - mark_price_i = 25986.2 * * @param inputs The inputs for calculating the MMR. * @returns The MMR of the position. */ declare function MMR$1(inputs: { baseMMR: number; baseIMR: number; IMRFactor: number; positionNotional: number; IMR_factor_power: number; }): number; /** * Calculates the profit or loss for take profit. * @returns The profit or loss for take profit. */ declare function estPnLForTP(inputs: { positionQty: number; entryPrice: number; price: number; }): number; /** * Calculates the estimated price for take profit. * This is the inverse of estPnLForTP: given PnL, calculates the price. * Formula: price = PnL / positionQty + entryPrice */ declare function estPriceForTP(inputs: { positionQty: number; entryPrice: number; pnl: number; }): number; /** * Calculates the estimated offset for take profit. */ declare function estOffsetForTP(inputs: { price: number; entryPrice: number; }): number; /** * Calculates the estimated price from offset for take profit. */ declare function estPriceFromOffsetForTP(inputs: { offset: number; entryPrice: number; }): number; /** * Calculates the PnL for stop loss. */ declare function estPnLForSL(inputs: { positionQty: number; entryPrice: number; }): number; /** * @formulaId maxPositionNotional * @description calculate the max position notional * @formula max_notional = ( (1/ (leverage * imr_factor) ) ^ (1/0.8) */ declare function maxPositionNotional(inputs: { /** symbol leverage */ leverage: number; IMRFactor: number; }): number; /** * symbol_leverage_max = 1 / ( imr_factor * notional ^ 0.8 ) */ declare function maxPositionLeverage(inputs: { IMRFactor: number; notional: number; }): number; /** * @formulaId liquidationPriceIsolated * @name Liquidation Price for Isolated Margin Position * @formula liquidation_price = (isolated_position_margin' - cost_position' - funding_adjustment) / (abs(position_qty') * MMR' - position_qty') * funding_adjustment = position_qty' * (sum_unitary_funding - last_sum_unitary_funding) * position_qty' = position_qty + order_side * order_qty * MMR' = max(base_MMR, (base_MMR / base_IMR) * IMR_factor * abs(position_qty' * reference_price)^(4/5)) * @description * * ## Definition * * **liquidation_price**: Price at which the isolated margin position will be liquidated * * **isolated_position_margin'**: Isolated position margin after order execution (if applicable) * * **cost_position'**: Position cost after order execution (if applicable) * * **funding_adjustment**: Adjustment for funding fees * * **position_qty'**: Position quantity after order execution * * **MMR'**: Maintenance margin rate after order execution * * ## Scenarios * * ### 1. No Order (order_qty = 0) * - `isolated_position_margin' = isolated_position_margin` * - `cost_position' = cost_position` * * ### 2. Open/Add Position (position_qty = 0 or order_side = sign(position_qty)) * - `isolated_position_margin' = isolated_position_margin + order_qty * reference_price * (1 / leverage + iso_taker_fee_buffer)` * - `cost_position' = cost_position + order_side * order_qty * reference_price` * * ### 3. Close/Reduce Position (order_side ≠ sign(position_qty) and sign(position_qty') = sign(position_qty)) * - `isolated_position_margin' = isolated_position_margin * position_qty' / position_qty` * - `cost_position' = cost_position + order_side * order_qty * reference_price` * * ### 4. Flip Position (order_side ≠ sign(position_qty) and sign(position_qty') ≠ sign(position_qty)) * - `isolated_position_margin' = abs(position_qty') * reference_price * (1 / leverage + iso_taker_fee_buffer)` * - `cost_position' = position_qty' * reference_price` * * ## Example * * ``` * isolated_position_margin = 2000 * cost_position = 100000 * position_qty = 2 (long) * sum_unitary_funding = 0.001 * last_sum_unitary_funding = 0.0008 * base_MMR = 0.025 * base_IMR = 0.04 * IMR_factor = 0.0000001 * reference_price = 50000 * liquidation_price = (2000 - 100000 - 0.0004) / (2 * 0.025 - 2) ≈ 50256.41 * ``` * * @param inputs Input parameters for calculating liquidation price * @returns Liquidation price (in USDC) or null if invalid */ declare function liquidationPriceIsolated(inputs: { /** * @description Current isolated position margin */ isolatedPositionMargin: number; /** * @description Current position cost */ costPosition: number; /** * @description Current position quantity (positive for long, negative for short) */ positionQty: number; /** * @description Current cumulative unitary funding */ sumUnitaryFunding: number; /** * @description Last cumulative unitary funding (at last settlement) */ lastSumUnitaryFunding: number; /** * @description Base maintenance margin rate */ baseMMR: number; /** * @description Base initial margin rate */ baseIMR: number; /** * @description IMR calculation factor */ IMRFactor: number; /** * @description Reference price (mark price for current position, or order price for estimated liquidation) */ referencePrice?: number; /** * @description Order side (BUY = +1, SELL = -1) for calculating estimated liquidation after order execution */ orderSide?: "BUY" | "SELL"; /** * @description Order quantity for calculating estimated liquidation after order execution */ orderQty?: number; /** * @description Leverage for the position */ leverage: number; /** * @description Fee buffer reserved in isolated margin estimates (default: 0.0006) */ isoTakerFeeBuffer?: number; }): number | null; type index$1_LiqPriceInputs = LiqPriceInputs; type index$1_UnrealPnLInputs = UnrealPnLInputs; declare const index$1_estOffsetForTP: typeof estOffsetForTP; declare const index$1_estPnLForSL: typeof estPnLForSL; declare const index$1_estPnLForTP: typeof estPnLForTP; declare const index$1_estPriceForTP: typeof estPriceForTP; declare const index$1_estPriceFromOffsetForTP: typeof estPriceFromOffsetForTP; declare const index$1_liqPrice: typeof liqPrice; declare const index$1_liquidationPriceIsolated: typeof liquidationPriceIsolated; declare const index$1_maintenanceMargin: typeof maintenanceMargin; declare const index$1_maxPositionLeverage: typeof maxPositionLeverage; declare const index$1_maxPositionNotional: typeof maxPositionNotional; declare const index$1_notional: typeof notional; declare const index$1_totalNotional: typeof totalNotional; declare const index$1_totalUnrealizedPnL: typeof totalUnrealizedPnL; declare const index$1_totalUnsettlementPnL: typeof totalUnsettlementPnL; declare const index$1_unrealizedPnL: typeof unrealizedPnL; declare const index$1_unrealizedPnLROI: typeof unrealizedPnLROI; declare const index$1_unsettlementPnL: typeof unsettlementPnL; declare namespace index$1 { export { type index$1_LiqPriceInputs as LiqPriceInputs, MMR$1 as MMR, type index$1_UnrealPnLInputs as UnrealPnLInputs, index$1_estOffsetForTP as estOffsetForTP, index$1_estPnLForSL as estPnLForSL, index$1_estPnLForTP as estPnLForTP, index$1_estPriceForTP as estPriceForTP, index$1_estPriceFromOffsetForTP as estPriceFromOffsetForTP, index$1_liqPrice as liqPrice, index$1_liquidationPriceIsolated as liquidationPriceIsolated, index$1_maintenanceMargin as maintenanceMargin, index$1_maxPositionLeverage as maxPositionLeverage, index$1_maxPositionNotional as maxPositionNotional, index$1_notional as notional, index$1_totalNotional as totalNotional, index$1_totalUnrealizedPnL as totalUnrealizedPnL, index$1_totalUnsettlementPnL as totalUnsettlementPnL, index$1_unrealizedPnL as unrealizedPnL, index$1_unrealizedPnLROI as unrealizedPnLROI, index$1_unsettlementPnL as unsettlementPnL }; } type TotalValueInputs = { totalUnsettlementPnL: number; USDCHolding: number; nonUSDCHolding: { holding: number; indexPrice: number; }[]; }; /** * @formulaId totalValue * @name Total Value * @formula Total Value = total_holding + total_isolated_position_margin + total_unsettled_PNL, total_holding = usdc balance.holding + SUM(non-usdc balance.holding * mark price) * @description * * ## Definition * * **Total Value** = User's total asset value (denominated in USDC), including assets that cannot be used as collateral * * **Total holding** = Sum of all holding quantities in the user's account * * **usdc balance.holding** = USDC holding quantity * * **non-usdc balance.holding * mark price** = Value of non-USDC asset holdings (denominated in USDC) * * **total_isolated_position_margin** = Sum of all isolated margin position margins * * **holding**: Asset quantity held by the user, from `/v1/client/holding` or v2 Websocket API | Balance * * **mark price**: Current price of the asset, from v2 Websocket API | Balance * * **total unsettlement PNL** = Sum of user's account unsettled PNL (including both cross and isolated margin positions) * * ## Example * * ``` * total_holding = 2000 + 1000 * 1.001 = 3001 * total_isolated_position_margin = 500 * total_unsettled_PNL = -18.34 * Total Value = 3001 + 500 - 18.34 = 3482.66 * ``` */ declare function totalValue(inputs: { /** * @description Total unsettled PNL of user account (including both cross and isolated margin positions) */ totalUnsettlementPnL: number; /** * @description USDC holding quantity */ USDCHolding: number; /** * @description Non-USDC holdings with their index prices */ nonUSDCHolding: { holding: number; indexPrice: number; }[]; /** * @description Total isolated position margin (sum of all isolated margin positions). Pass 0 if no isolated margin positions exist. * @default 0 */ totalIsolatedPositionMargin?: number; }): Decimal; type FreeCollateralInputs = { totalCollateral: Decimal; totalInitialMarginWithOrders: number; }; /** * @formulaId freeCollateral * @name Free Collateral * @formula Free Collateral = Total_collateral_value - total_initial_margin_with_orders * Total_collateral_value = (usdc balance.holding + usdc balance.pending_short_qty - usdc balance.isolated_order_frozen) + SUM(non-usdc balance.holding * mark price * discount) + total_cross_unsettled_PNL * total_initial_margin_with_orders = sum ( cross_position_notional_with_orders_i * cross_IMR_i (with_orders)) * IMR_i (with_orders) = Max(1 / Symbol Leverage i, Base IMR i, IMR Factor i * Abs(Position Notional i + Order Notional i)^(4/5)) * position_notional_with_orders_i = abs( mark_price_i * position_qty_with_orders_i) * position_qty_with_orders_i = max[ abs(position_qty_i + sum_position_qty_buy_orders_i), abs(position_qty_i - sum_position_qty_sell_orders_i)] * @description * * ## Definition * * **Free collateral**: Total value of available margin in the user's account (denominated in USDC). For isolated margin mode, this only considers cross margin positions and orders. * * **Total_collateral_value**: Total value of collateral assets in the user's account (denominated in USDC). For isolated margin mode, includes cross margin unsettled PNL but excludes isolated order frozen amounts. * Use `totalCollateral` function with optional parameters (`usdcBalancePendingShortQty`, `usdcBalanceIsolatedOrderFrozen`, `totalCrossUnsettledPnL`) to calculate this value. * * **total_initial_margin_with_orders**: Total initial margin used by cross margin positions and orders (isolated margin positions are excluded). * Use `totalInitialMarginWithQty` function with `orders` parameter to calculate this value. The function automatically filters to cross margin only. * * **usdc balance.pending_short_qty**: USDC balance frozen for pending short orders * * **usdc balance.isolated_order_frozen**: USDC balance frozen for isolated margin orders * * **total_cross_unsettled_PNL**: Total unsettled PNL from cross margin positions only * * **initial_margin_i with order**: Initial margin for symbol i (considering both positions and orders) * * **IMR_i (with_orders)**: Initial margin rate for a single symbol (considering both position and order notional) * * **Symbol Leverage i**: Leverage for symbol i under current margin mode (cross/isolated). Use `position.leverage` when position exists; otherwise resolve by symbol + mode leverage source. * * **Base IMR i**: Base initial margin rate for a single symbol, from `/v1/public/info` * * **IMR Factor i**: IMR calculation factor for a single symbol, from `v1/client/info` * * **Position Notional i**: Sum of position notional for a single symbol * * **Order Notional i**: Sum of order notional for a single symbol * * **position_notional_with_orders_i**: Sum of position and order notional for a single symbol * * **mark_price_i**: Mark price for a single symbol * * **position_qty_with_orders_i**: Sum of position and order quantity for a single symbol * * **position_qty_i**: Position quantity for a single symbol * * **sum_position_qty_buy_orders_i**: Sum of long order quantity for a single symbol [algo orders should be ignored] * * **sum_position_qty_sell_orders_i**: Sum of short order quantity for a single symbol [algo orders should be ignored] * * ## Example * * ``` * Total_collateral_value = (2000 + 100 - 200) + 1 * 2000 * 0.9 + 50 = 2050 * total_initial_margin_with_orders = 1500 * Free Collateral = 2050 - 1500 = 550 * ``` */ declare function freeCollateral(inputs: { /** * @description Total collateral value */ totalCollateral: Decimal; /** * @description Total initial margin with orders (for cross margin positions only) */ totalInitialMarginWithOrders: number; }): Decimal; type FreeCollateralUSDCOnlyInputs = { /** * Free collateral (total_collateral_value - total_initial_margin_with_orders). * @see freeCollateral */ freeCollateral: Decimal; /** * Non-USDC token holdings; same structure as in totalCollateral. * Each item contributes (capped_holding × index_price × discount) to the sum to subtract. */ nonUSDCHolding: { holding: number; indexPrice: number; collateralCap: number; collateralRatio: Decimal; }[]; }; /** * @formulaId freeCollateralUSDCOnly * @name Free Collateral (USDC Only) * @formula Free Collateral USDC Only = max(0, free_collateral - SUM(non_usdc_token.holding × mark_price × discount)) * @description * * ## Definition * * **Free Collateral (USDC Only)**: Part of free collateral that is backed only by USDC (and unsettled PNL), i.e. excluding the value of non-USDC collateral. * * **free_collateral**: From freeCollateral (total_collateral_value - total_initial_margin_with_orders). * * **non_usdc_token.holding × mark_price × discount**: Same as in totalCollateral — value of each non-USDC asset (capped by collateralCap), using indexPrice as mark price and collateralRatio as discount. * * ## Example * * ``` * free_collateral = 550 * SUM(non_usdc.holding × mark_price × discount) = 1 * 2000 * 0.9 = 1800 * Free Collateral USDC Only = max(0, 550 - 1800) = 0 * ``` */ declare function freeCollateralUSDCOnly(inputs: FreeCollateralUSDCOnlyInputs): Decimal; /** * @formulaId totalCollateral * @name Total Collateral * @formula Total collateral = usdc balance.holding + SUM(non-usdc balance.holding * mark price * discount) + total unsettlement PNL * @description * * ## Definition * * **discount**: Collateral substitution rate * * **Total collateral**: Total value of collateral assets in the user's account (denominated in USDC) * * **usdc balance.holding**: USDC holding quantity * * **non-usdc balance.holding * mark price**: Value of non-USDC asset holdings (denominated in USDC) * * **holding**: Asset quantity held by the user, from `/v1/client/holding` or v2 Websocket API | Balance * * **mark price**: Current price of the asset, from v2 Websocket API | Balance * * **total unsettlement PNL**: Sum of user's account unsettled PNL * * ## Example * * ``` * Total collateral = 2000 + 1000 * 1.001 * 0 - 18.34 = 1981.66 * total unsettlement PNL = -18.34 * ``` */ declare function totalCollateral(inputs: { USDCHolding: number; nonUSDCHolding: { holding: number; indexPrice: number; collateralCap: number; collateralRatio: Decimal; }[]; /** * Sum of user's account unsettled PNL */ unsettlementPnL: number; /** * @description USDC balance frozen for pending short orders (for freeCollateral calculation) * @default 0 */ usdcBalancePendingShortQty?: number; /** * @description USDC balance frozen for isolated margin orders (for freeCollateral calculation) * @default 0 */ usdcBalanceIsolatedOrderFrozen?: number; /** * @description Total cross margin unsettled PNL (for freeCollateral calculation). If provided, this will be used instead of unsettlementPnL. */ totalCrossUnsettledPnL?: number; }): Decimal; /** * Sum of notional value for a symbol's position and orders. */ declare function positionNotionalWithOrder_by_symbol(inputs: { markPrice: number; positionQtyWithOrders: number; }): Decimal; /** * Sum of position quantity and orders quantity for a symbol. */ declare function positionQtyWithOrders_by_symbol(inputs: { positionQty: number; buyOrdersQty: number; sellOrdersQty: number; }): number; /** * @formulaId imr * @description * Initial margin rate for a symbol. * Max(1 / Symbol Leverage i, Base IMR i, IMR Factor i * Abs(Position Notional i + Order Notional i)^(4/5)) */ declare function IMR(inputs: { /** * effective symbol leverage (resolved by symbol + margin mode) */ maxLeverage: number; baseIMR: number; IMR_Factor: number; positionNotional: number; ordersNotional: number; IMR_factor_power?: number; }): number; declare function buyOrdersFilter_by_symbol(orders: API.Order[], symbol: string): API.Order[]; declare function sellOrdersFilter_by_symbol(orders: API.Order[], symbol: string): API.Order[]; /** * Get the quantity of a specified symbol from the list of positions. */ declare function getQtyFromPositions(positions: API.Position[], symbol: string): number; /** * Get the quantity of long and short orders for a specified symbol from the list of orders. */ declare function getQtyFromOrdersBySide(orders: API.Order[], symbol: string, side: OrderSide): number; declare function getPositonsAndOrdersNotionalBySymbol(inputs: { positions: API.Position[]; orders: API.Order[]; symbol: string; markPrice: number; }): number; /** * Calculate total initial margin with orders for cross margin positions. * Formula: total_initial_margin_with_orders = sum(cross_position_notional_with_orders_i * cross_IMR_i) * * @param positions - All positions (will be filtered to cross margin only) * @param orders - All orders (will be filtered to cross margin only) * @param markPrices - Mark prices by symbol * @param symbolInfo - Symbol info accessor * @param IMR_Factors - IMR factors by symbol * @param maxLeverageBySymbol - Symbol leverage map (symbol + margin mode) */ declare function totalInitialMarginWithQty(inputs: { positions: API.Position[]; orders: API.Order[]; markPrices: { [key: string]: number; }; symbolInfo: any; IMR_Factors: { [key: string]: number; }; maxLeverageBySymbol?: Record; }): number; /** * Group orders by symbol, as a symbol can have multiple orders. */ declare function groupOrdersBySymbol(orders: API.Order[]): { [key: string]: API.Order[]; }; /** * Extracts all unique symbols from positions and orders. * @param positions - An array of position objects. * @param orders - An array of order objects. * @returns An array of unique symbols. */ declare function extractSymbols(positions: Pick[], orders: Pick[]): string[]; /** * Total margin used by other symbols (except the current symbol). */ declare function otherIMs(inputs: { positions: API.Position[]; markPrices: { [key: string]: number; }; symbolInfo: any; IMR_Factors: { [key: string]: number; }; }): number; type ResultOptions = { dp: number; }; type MaxQtyInputs = { symbol: string; /** * @description Maximum quantity limit for opening a single position, /v1/public/info.base_max */ baseMaxQty: number; /** * Total collateral of the user (denominated in USDC), can be calculated from totalCollateral. * @see totalCollateral */ totalCollateral: number; maxLeverage: number; baseIMR: number; /** * @see otherIMs */ otherIMs: number; markPrice: number; positionQty: number; buyOrdersQty: number; sellOrdersQty: number; IMR_Factor: number; takerFeeRate: number; }; /** * @formulaId maxQty * @name Max Order QTY * @description * ## Max Long Quantity Formula * * ``` * max long qty = MIN ( * base max, * (((Total_collateral_value - Other_IMs) / (Max(1 / Symbol Leverage i, Base IMR i) + 2 * futures_take_fee_rate * 0.0001) / mark_price_i) * 0.995 - position_qty_this_symbol - sum_buy_order_qty_this_symbol), * ((((Total_collateral_value - Other_IMs) / IMR Factor i)^(1/1.8)) / mark_price_i - position_qty_this_symbol - sum_buy_order_qty_this_symbol) / (1 + 2 * futures_take_fee_rate * 0.0001) * 0.995 * ) * ``` * * ## Max Short Quantity Formula * * ``` * max short qty = MIN ( * base max, * (((Total_collateral_value - Other_IMs) / (Max(1 / Symbol Leverage i, Base IMR i) + 2 * futures_take_fee_rate * 0.0001) / mark_price_i) * 0.995 + position_qty_this_symbol - sum_sell_order_qty_this_symbol), * ((((Total_collateral_value - Other_IMs) / IMR Factor i)^(1/1.8)) / mark_price_i + position_qty_this_symbol - sum_sell_order_qty_this_symbol) / (1 + 2 * futures_take_fee_rate * 0.0001) * 0.995 * ) * ``` * * ## Reduce Only Mode * * When reduce only is enabled: * - If `position_qty_i > 0`: max long qty = 0, max short qty = abs(position_qty_i) * - If `position_qty_i < 0`: max long qty = abs(position_qty_i), max short qty = 0 * - If `position_qty_i = 0`: max long qty = 0, max short qty = 0 * * ## Variable Definitions * * | Variable | Description | API Reference | * |----------|-------------|---------------| * | `max long qty` | Maximum long quantity for current symbol | | * | `max short qty` | Maximum short quantity for current symbol | | * | `base_max` | Maximum quantity limit for opening a single position | `/v1/public/info.base_max` | * | `Total_collateral_value` | Total value of collateral assets in user account (USDC denominated) | | * | `Other_IMs` | Initial margin occupied by all other symbols excluding current symbol | | * | `IMR_i (with_orders)` | Initial margin rate for a single symbol (considering both position/orders notional) | | * | `Symbol Leverage i` | Leverage for symbol i under current margin mode | `position.leverage` or symbol+mode leverage source | * | `Base IMR i` | Base initial margin rate for a single symbol | `/v1/public/info` | * | `IMR Factor i` | IMR calculation factor for a single symbol | `v1/client/info` | * | `Position Notional i` | Sum of position notional for a single symbol | | * | `Order Notional i` | Sum of order notional for a single symbol | | * | `position_notional_with_orders_i` | Sum of position/orders notional for a single symbol | | * | `mark_price_i` | Mark price for a single symbol | | * | `position_qty_with_orders_i` | Sum of position/orders quantity for a single symbol | | * | `position_qty_i` | Position quantity for a single symbol | | * | `sum_position_qty_buy_orders_i` | Sum of long order quantity for a single symbol [algo orders ignored] | | * | `sum_position_qty_sell_orders_i` | Sum of short order quantity for a single symbol [algo orders ignored] | | * | `futures_take_fee_rate` | User's futures taker fee rate | `GET /v1/client/info` | * * ## Calculation Details * * ``` * Other_IMs = sum(position_notional_with_orders_i * IMR_i (with_orders)) // excluding current symbol * * IMR_i (with_orders) = Max(1 / Symbol Leverage i, Base IMR i, IMR Factor i * Abs(Position Notional i + Order Notional i)^(4/5)) * * position_notional_with_orders_i = abs(mark_price_i * position_qty_with_orders_i) * * position_qty_with_orders_i = max[abs(position_qty_i + sum_position_qty_buy_orders_i), abs(position_qty_i - sum_position_qty_sell_orders_i)] * ``` * * ## Example Calculation * * **Given:** * - `futures_take_fee_rate = 8` * - `BTC base max = 20` * - `Total_collateral_value = 1981.66` * - `Other_IMs = ETH Initial Margin = 4915.23 * 0.1 = 491.523` * - `BTC mark_price_i = 25986.2` * - `BTC position_qty_this_symbol = 0.2` * - `sum_buy_order_qty_this_symbol = 0.3` * - `sum_sell_order_qty_this_symbol = -0.5` * * **Max Long Quantity:** * ``` * max long qty = MIN( * 20 BTC, * ((1981.66 - 491.523) / (0.1 + 2 * 8 * 0.0001) / 25986.2 * 0.995 - 0.2 - 0.3) = 0.0615815026 BTC, * ((((1981.66 - 491.523) / 0.0000002512)^(1/1.8)) / 25986.2 - 0.2 - 0.3) / (1 + 2 * 8 * 0.0001) * 0.995 = 9.78216039 BTC * ) = 0.0615815026 BTC * ``` * * **Max Short Quantity:** * ``` * max short qty = MIN( * 20 BTC, * ((1981.66 - 491.523) / (0.1 + 2 * 8 * 0.0001) / 25986.2 * 0.995 + 0.2 - 0.5) = 0.261581503 BTC, * ((((1981.66 - 491.523) / 0.0000002512)^(1/1.8)) / 25986.2 + 0.2 - 0.5) / (1 + 2 * 8 * 0.0001) * 0.995 = 9.98084249726 BTC * ) = 0.261581503 BTC * ``` * * ## Additional Examples * * **Base max qty calculation:** * ``` * Base max qty = (1981.66 - 491.523) / (0.1 + 2 * 8 * 0.0001) / 25986.2 * 0.995 = 0.561581503 BTC * ``` * * **Different position scenarios:** * * 1. **Short position -0.3 BTC:** * - max long qty = 0.561581503 - (-0.3) = 0.861581503 * - max short qty = 0.561581503 + (-0.3) = 0.261581503 * * 2. **Short position -0.3 BTC + sell orders 0.1:** * - max long qty = 0.561581503 - (-0.3) = 0.861581503 * - max short qty = 0.561581503 + (-0.3) - 0.1 = 0.161581503 * * 3. **Long position 0.3 BTC + buy orders 0.2 + sell orders 0.1:** * - max long qty = 0.561581503 - 0.3 - 0.2 = 0.061581503 * - max short qty = 0.561581503 + 0.3 - 0.1 = 0.761581503 * * ## Special Case: Insufficient Collateral * * When `totalCollatValue <= newTotalIM`: * * ``` * newOrderSize_iter = ITERATE() return max(0, newOrderSize_iter * 99.5% + others) * ``` * * **ITERATE() Algorithm:** * ``` * ITERATE() { * iteratorLeverage = min(1 / Symbol Leverage i, Base IMR i) * iteratorStep = 2 * * // First iteration (30 times) * for (i = 0; i < 30; i++) { * iteratorLeverage = max(0, iteratorLeverage - iteratorStep) * newOrderSize1 = (adjustedCollateral - othersIM) * iteratorLeverage / markPrice * calculate afterTradeIM * if (adjustedCollateral >= afterTradeIM) break * } * * leftLeverage = iteratorLeverage * rightLeverage = min(symbolLeverage_i, leftLeverage + iteratorStep) * * // Binary search (30 times) * for (i = 0; i < 30; i++) { * midLeverage = (leftLeverage + rightLeverage) / 2 * newOrderSize2 = (adjustedCollateral - othersIM) * midLeverage / markPrice * calculate afterTradeIM * precision = (adjustedCollateral - afterTradeIM) / adjustedCollateral * * if (adjustedCollateral > afterTradeIM) { * leftLeverage = midLeverage * if (0 <= precision <= 0.5%) break * } else { * rightLeverage = midLeverage * } * } * * return newOrderSize2 * } * ``` */ declare function maxQty(side: OrderSide, inputs: MaxQtyInputs, options?: ResultOptions): number; declare function maxQtyByLong(inputs: Omit, options?: ResultOptions): number; declare function maxQtyByShort(inputs: Omit, options?: ResultOptions): number; /** * @formulaId maxQtyIsolated * @name Maximum Tradeable Quantity for Isolated Margin * @formula max_notional = min((1 / leverage / imr_factor)^(5/4), symbol_max_notional) * @description * * ## Definition * * **maxQtyIsolated**: Maximum tradeable quantity for isolated margin positions * * This function calculates the maximum quantity that can be traded for an isolated margin position, * considering available balance, leverage, position limits, and pending orders. * * ## Business Rules * * ### For BUY Orders: * - If `reduce_only == False` and `position_qty >= 0` (long or no position): Use simplified formula * - If `reduce_only == False` and `position_qty < 0` (short position): Use binary search iteration * - If `reduce_only == True`: Return `MAX(0, -position_qty)` (can only reduce short position) * * ### For SELL Orders: * - If `reduce_only == False` and `position_qty <= 0` (short or no position): Use simplified formula * - If `reduce_only == False` and `position_qty > 0` (long position): Use binary search iteration * - If `reduce_only == True`: Return `MAX(0, position_qty)` (can only reduce long position) * * ### Binary Search Algorithm: * - Used for reverse position scenarios (e.g., buying when holding short position) * - Maximum 30 iterations * - Searches for maximum quantity that satisfies: `iso_order_frozen <= available_balance` and `open_notional <= max_notional` * * ## Example * * ``` * order_side = BUY * reduce_only = False * position_qty = 5 (long) * available_balance = 1000 USDC * leverage = 25 * mark_price = 100000 USDC * current_order_reference_price = 99900 USDC * max_notional = 10059467.44 USDC * pending_long_notional = 299200 USDC * max_qty = MIN(1000 / (1 / 25 + 0.0006) / 99900 * 0.995, (10059467.44 - 100000 * 5 - 299200) / 99900) = 0.245 BTC * ``` * * @param inputs Input parameters for calculating maximum tradeable quantity * @returns Maximum tradeable quantity */ declare function isolatedMarginRate(inputs: { leverage: number; isoTakerFeeBuffer?: number; }): Decimal; declare function maxQtyForIsolatedMargin(inputs: { /** * @description Trading symbol */ symbol: string; /** * @description Order side (BUY or SELL) */ orderSide: OrderSide; /** * @description Current order reference price */ currentOrderReferencePrice: number; /** * @description Available balance (USDC) */ availableBalance: number; /** * @description Leverage for the trading pair */ leverage: number; /** * @description Base initial margin rate */ baseIMR: number; /** * @description IMR calculation factor */ IMR_Factor: number; /** * @description Mark price */ markPrice: number; /** * @description Current position quantity (positive for long, negative for short) */ positionQty: number; /** * @description Pending long orders (excluding current order) */ pendingLongOrders: Array<{ referencePrice: number; quantity: number; }>; /** * @description Pending sell orders (excluding current order) */ pendingSellOrders: Array<{ referencePrice: number; quantity: number; }>; /** * @description Already frozen margin for long orders */ isoOrderFrozenLong: number; /** * @description Already frozen margin for short orders */ isoOrderFrozenShort: number; /** * @description Maximum notional value for the symbol */ symbolMaxNotional: number; /** * @description Precision threshold for binary search (default: 1) */ epsilon?: number; /** * @description Fee buffer reserved in isolated frozen margin (default: 0.0006) */ isoTakerFeeBuffer?: number; }): number; /** * total margin ratio */ declare function totalMarginRatio(inputs: { totalCollateral: number; markPrices: { [key: string]: number; }; positions: API.Position[]; }, dp?: number): number; /** * @formulaId totalUnrealizedROI * @name Total Unrealized ROI * @formula Total Unrealized ROI = Total Unrealized PNL / ( Total Value - Total Unrealized PNL ) * 100% * @description * * ## Definition * * **Total Unrealized PNL** = Sum of unrealized profit and loss for all current positions of the user * * **Total Value** = User's total asset value (denominated in USDC), including assets that cannot be used as collateral * * ## Example * * ``` * Total Unrealized ROI = 200.53 / ( 2982.66 - 200.53 ) * 100% = 7.21% * Total Unrealized PNL = 200.53 * Total Value = 2982.66 * ``` */ declare function totalUnrealizedROI(inputs: { totalUnrealizedPnL: number; totalValue: number; }): number; /** * current account leverage */ declare function currentLeverage(totalMarginRatio: number): number; declare function availableBalance(inputs: { USDCHolding: number; unsettlementPnL: number; }): number; /** * @formulaId availableBalanceForIsolatedMargin * @name Available Balance for Isolated Margin * @formula availableBalanceForIsolatedMargin = max(0, min(USDC_balance, free_collateral - max(total_cross_unsettled_pnl, 0))) * @description * * ## Definition * * max(0, min(USDC_balance, free_collateral - max(total_cross_unsettled_pnl, 0))), where * * **USDC_balance** = User's USDC balance * * **free_collateral** = Available collateral in the user's account (for cross margin trading) * * **total_cross_unsettled_pnl** = sum( unsettled_PNL_i ) across all cross margin positions */ declare function availableBalanceForIsolatedMargin(inputs: { USDCHolding: number; totalCrossUnsettledPnL: number; freeCollateral: number; }): number; /** * @formulaId mmr * @name Total Maintenance Margin Ratio * @formula Total Maintenance Margin Ratio = sum(Position maintenance margin) / total_position_notional * 100%, total_position_notional = sum(abs(position_qty_i * mark_price_i)) * @description * * ## Definition * * **Total Maintenance Margin Ratio** = User's account maintenance margin ratio * * **sum(Position maintenance margin)** = Total maintenance margin of all user positions (denominated in USDC) * * **total_position_notional** = Sum of notional value of current positions * * **position_qty_i** = Position quantity for a single symbol * * **mark_price_i** = Mark price for a single symbol * * ## Example * * ``` * Total Margin Ratio = 505.61 / 10112.43 * 100% = 4.99988628% * total_position_notional = 10112.43 * abs(BTC position notional) = 5197.2 * abs(ETH position notional) = 4915.23 * sum(Position maintenance margin) = 505.61 * BTC position MM = 259.86 * ETH position MM = 245.75 * ``` * * @param inputs AccountMMRInputs * @returns number|null */ declare function MMR(inputs: { positionsMMR: number; /** * Notional sum of all positions, * positions.totalNotional() */ positionsNotional: number; }): number | null; declare const collateralRatio: (params: { baseWeight: number; discountFactor: number | null; collateralQty: number; collateralCap: number; indexPrice: number; }) => Decimal; /** collateral_value_i = min(collateral_qty_i , collateral_cap_i) * weight_i * index_price_i */ declare const collateralContribution: (params: { collateralQty: number; collateralCap: number; collateralRatio: number; indexPrice: number; }) => number; declare const LTV: (params: { usdcBalance: number; upnl: number; assets: Array<{ qty: number; indexPrice: number; weight: number; }>; }) => number; /** * max(0, min(USDC_balance, free_collateral - max(upnl, 0))) */ declare const maxWithdrawalUSDC: (inputs: { USDCBalance: number; freeCollateral: Decimal; upnl: number; }) => number; /** * * Other collateral: min(collateral_qty_i, free_collateral / (index_price_i × weight_i) * Other collateral with negative USDC: min(collateral_qty_i, free_collateral / (index_price_i × (1 + buffer) × weight_i) * buffer: 0.2% */ declare const maxWithdrawalOtherCollateral: (inputs: { USDCBalance: number; collateralQty: number; freeCollateral: Decimal; indexPrice: number; weight: Decimal; }) => Decimal; declare const calcMinimumReceived: (inputs: { amount: number; slippage: number; }) => number; /** * @formulaId maxAdd * @name Maximum Margin Addition for Isolated Position * @formula max_add = max(0, min(USDC_balance, free_collateral - max(total_cross_unsettled_pnl, 0))) * @description * * ## Definition * * **max_add**: Maximum amount of margin that can be added to an isolated margin position * * **USDC_balance**: User's USDC balance * * **free_collateral**: Available collateral in the user's account (for cross margin trading) * * **total_cross_unsettled_pnl**: Total unsettled PNL from cross margin positions only * * ## Business Rules * * - Maximum add amount cannot exceed available USDC balance * - Maximum add amount cannot exceed free collateral minus cross margin unrealized profit * - Cross margin unrealized profit reduces available funds for adding isolated margin * * ## Example * * ``` * USDC_balance = 500 * free_collateral = 300 * total_cross_unsettled_pnl = 100 (profit) * max_add = max(0, min(500, 300 - max(100, 0))) = max(0, min(500, 200)) = 200 * ``` * * @param inputs Input parameters for calculating maximum margin addition * @returns Maximum margin that can be added (in USDC) */ declare function maxAdd(inputs: { /** * @description USDC balance */ USDCHolding: number; /** * @description Free collateral (available for cross margin trading) */ freeCollateral: number; /** * @description Total cross margin unsettled PNL */ totalCrossUnsettledPnL: number; }): number; /** * @formulaId maxReduce * @name Maximum Margin Reduction for Isolated Position * @formula max_reduce = max(0, isolated_position_margin - position_notional * imr + min(0, position_unsettled_pnl)) * @description * * ## Definition * * **max_reduce**: Maximum amount of margin that can be reduced from an isolated margin position * * **isolated_position_margin**: Current margin allocated to the isolated position * * **position_notional**: Notional value of the isolated position * * **imr**: Initial margin rate for the isolated position * * **position_unsettled_pnl**: Unrealized PNL of the isolated position * * ## Business Rules * * - Maximum reduce amount cannot exceed current isolated position margin * - Unrealized losses increase the maximum reducible amount * - Position notional and IMR determine the minimum required margin * * ## Example * * ``` * isolated_position_margin = 1000 * position_notional = 5000 * imr = 0.02 * position_unsettled_pnl = -100 (loss) * max_reduce = max(0, 1000 - 5000 * 0.02 + min(0, -100)) = max(0, 1000 - 100 - 100) = 800 * ``` * * @param inputs Input parameters for calculating maximum margin reduction * @returns Maximum margin that can be reduced (in USDC) */ declare function maxReduce(inputs: { /** * @description Current margin allocated to the isolated position */ isolatedPositionMargin: number; /** * @description Notional value of the isolated position */ positionNotional: number; /** * @description Initial margin rate for the isolated position */ imr: number; /** * @description Unrealized PNL of the isolated position */ positionUnsettledPnL: number; }): number; type index_FreeCollateralInputs = FreeCollateralInputs; type index_FreeCollateralUSDCOnlyInputs = FreeCollateralUSDCOnlyInputs; declare const index_IMR: typeof IMR; declare const index_LTV: typeof LTV; declare const index_MMR: typeof MMR; type index_MaxQtyInputs = MaxQtyInputs; type index_ResultOptions = ResultOptions; type index_TotalValueInputs = TotalValueInputs; declare const index_availableBalance: typeof availableBalance; declare const index_availableBalanceForIsolatedMargin: typeof availableBalanceForIsolatedMargin; declare const index_buyOrdersFilter_by_symbol: typeof buyOrdersFilter_by_symbol; declare const index_calcMinimumReceived: typeof calcMinimumReceived; declare const index_collateralContribution: typeof collateralContribution; declare const index_collateralRatio: typeof collateralRatio; declare const index_currentLeverage: typeof currentLeverage; declare const index_extractSymbols: typeof extractSymbols; declare const index_freeCollateral: typeof freeCollateral; declare const index_freeCollateralUSDCOnly: typeof freeCollateralUSDCOnly; declare const index_getPositonsAndOrdersNotionalBySymbol: typeof getPositonsAndOrdersNotionalBySymbol; declare const index_getQtyFromOrdersBySide: typeof getQtyFromOrdersBySide; declare const index_getQtyFromPositions: typeof getQtyFromPositions; declare const index_groupOrdersBySymbol: typeof groupOrdersBySymbol; declare const index_isolatedMarginRate: typeof isolatedMarginRate; declare const index_maxAdd: typeof maxAdd; declare const index_maxQty: typeof maxQty; declare const index_maxQtyByLong: typeof maxQtyByLong; declare const index_maxQtyByShort: typeof maxQtyByShort; declare const index_maxQtyForIsolatedMargin: typeof maxQtyForIsolatedMargin; declare const index_maxReduce: typeof maxReduce; declare const index_maxWithdrawalOtherCollateral: typeof maxWithdrawalOtherCollateral; declare const index_maxWithdrawalUSDC: typeof maxWithdrawalUSDC; declare const index_otherIMs: typeof otherIMs; declare const index_positionNotionalWithOrder_by_symbol: typeof positionNotionalWithOrder_by_symbol; declare const index_positionQtyWithOrders_by_symbol: typeof positionQtyWithOrders_by_symbol; declare const index_sellOrdersFilter_by_symbol: typeof sellOrdersFilter_by_symbol; declare const index_totalCollateral: typeof totalCollateral; declare const index_totalInitialMarginWithQty: typeof totalInitialMarginWithQty; declare const index_totalMarginRatio: typeof totalMarginRatio; declare const index_totalUnrealizedROI: typeof totalUnrealizedROI; declare const index_totalValue: typeof totalValue; declare namespace index { export { type index_FreeCollateralInputs as FreeCollateralInputs, type index_FreeCollateralUSDCOnlyInputs as FreeCollateralUSDCOnlyInputs, index_IMR as IMR, index_LTV as LTV, index_MMR as MMR, type index_MaxQtyInputs as MaxQtyInputs, type index_ResultOptions as ResultOptions, type index_TotalValueInputs as TotalValueInputs, index_availableBalance as availableBalance, index_availableBalanceForIsolatedMargin as availableBalanceForIsolatedMargin, index_buyOrdersFilter_by_symbol as buyOrdersFilter_by_symbol, index_calcMinimumReceived as calcMinimumReceived, index_collateralContribution as collateralContribution, index_collateralRatio as collateralRatio, index_currentLeverage as currentLeverage, index_extractSymbols as extractSymbols, index_freeCollateral as freeCollateral, index_freeCollateralUSDCOnly as freeCollateralUSDCOnly, index_getPositonsAndOrdersNotionalBySymbol as getPositonsAndOrdersNotionalBySymbol, index_getQtyFromOrdersBySide as getQtyFromOrdersBySide, index_getQtyFromPositions as getQtyFromPositions, index_groupOrdersBySymbol as groupOrdersBySymbol, index_isolatedMarginRate as isolatedMarginRate, index_maxAdd as maxAdd, index_maxQty as maxQty, index_maxQtyByLong as maxQtyByLong, index_maxQtyByShort as maxQtyByShort, index_maxQtyForIsolatedMargin as maxQtyForIsolatedMargin, index_maxReduce as maxReduce, index_maxWithdrawalOtherCollateral as maxWithdrawalOtherCollateral, index_maxWithdrawalUSDC as maxWithdrawalUSDC, index_otherIMs as otherIMs, index_positionNotionalWithOrder_by_symbol as positionNotionalWithOrder_by_symbol, index_positionQtyWithOrders_by_symbol as positionQtyWithOrders_by_symbol, index_sellOrdersFilter_by_symbol as sellOrdersFilter_by_symbol, index_totalCollateral as totalCollateral, index_totalInitialMarginWithQty as totalInitialMarginWithQty, index_totalMarginRatio as totalMarginRatio, index_totalUnrealizedROI as totalUnrealizedROI, index_totalValue as totalValue }; } /** @deprecated Use inline type or the new input type instead */ type EstimatedLiquidationPriceInputs = { totalCollateral: number; markPrice: number; baseMMR: number; baseIMR: number; IMR_Factor: number; orderFee: number; positions: Pick[]; newOrder: { symbol: string; qty: number; price: number; }; }; /** @deprecated Use inline type or the new input type instead */ type EstimatedLeverageInputs = { totalCollateral: number; positions: Pick[]; newOrder: { symbol: string; qty: number; price: number; }; }; /** * Maximum price when placing an order */ declare function maxPrice(markprice: number, range: number): number; /** * Minimum price when placing an order */ declare function minPrice(markprice: number, range: number): number; /** * Scope price when placing an order * @returns number */ declare function scopePrice(price: number, scope: number, side: "BUY" | "SELL"): number; /** * Calculate the order fee */ declare function orderFee(inputs: { /** * Order quantity */ qty: number; price: number; futuresTakeFeeRate: number; }): number; /** * Calculate reference price for a **new order** based on business rules. * * The reference price is used by risk / margin formulas as the effective * execution price when the user is preparing a new order. * * Business rules (simplified): * * - LIMIT * - BUY: `reference = limit_price` * - SELL: `reference = max(limit_price, Bid1)` * - If `limit_price` is not provided: same as MARKET * * - MARKET * - BUY: `reference = Ask1` * - SELL: `reference = Bid1` * * - STOP MARKET * - If `stop_price` provided: `reference = stop_price` * - Else: same as MARKET * * - STOP LIMIT * - If `limit_price` provided: `reference = limit_price` * - Else: same as MARKET * * - TRAILING STOP * - If `trigger_price` provided: `reference = trigger_price` * - Else: same as MARKET * * - BBO (LIMIT with ASK / BID as `orderTypeExt`) * - BUY + ASK => `reference = Ask1` * - SELL + BID => `reference = Bid1` * - BUY + BID => `reference = Bid1` * - SELL + ASK => `reference = Ask1` * * @param order Lightweight description of the new order * @param askPrice Ask1 price from orderbook * @param bidPrice Bid1 price from orderbook * @returns Reference price or null if it cannot be determined */ declare function getOrderReferencePrice(order: { /** * @description Order type (e.g. LIMIT, MARKET, STOP_LIMIT, STOP_MARKET, TRAILING_STOP, ASK, BID) */ orderType: OrderType; /** * @description Extended order type for BBO orders (ASK / BID as LIMIT extensions) */ orderTypeExt?: OrderType; /** * @description Order side (BUY or SELL) */ side: OrderSide; /** * @description User input LIMIT price (for LIMIT / STOP_LIMIT orders) */ limitPrice?: number; /** * @description Trigger price (for STOP_MARKET / STOP_LIMIT / TRAILING_STOP orders) */ triggerPrice?: number; }, askPrice: number, bidPrice: number): number | null; /** * @formulaId estLiqPriceIsolated * @name Est. Position liq. Price (Isolated Margin) * @description * Estimate the liquidation price for an isolated-margin position after placing a new order. * * The underlying formula is: * * \[ * liquidation\_price = * \frac{ * isolated\_position\_margin' - cost\_position' - funding\_adjustment * }{ * |position\_qty'| \cdot MMR' - position\_qty' * } * \] * * Where: * - `position_qty' = positionQty + orderSide * orderQty` * - `funding_adjustment = position_qty' * (sumUnitaryFunding - lastSumUnitaryFunding)` * - `MMR' = max(baseMMR, (baseMMR / baseIMR) * IMR_Factor * abs(position_qty' * reference_price)^(4/5))` * * Notes: * - This function only considers a **single isolated position** (no cross-margin collateral or other symbols). * - `newOrder.qty > 0` is treated as a BUY, `newOrder.qty < 0` as a SELL. * * @param inputs Estimation inputs for isolated-margin liquidation price * @returns Estimated liquidation price (in quote currency), or 0 when invalid / no position */ declare function estLiqPriceIsolated(inputs: { /** * @description Current isolated margin of the position */ isolatedPositionMargin: number; /** * @description Current position cost (qty * average entry price) */ costPosition: number; /** * @description Current position quantity (positive for long, negative for short) */ positionQty: number; /** * @description Current cumulative unitary funding */ sumUnitaryFunding: number; /** * @description Last cumulative unitary funding at the last settlement */ lastSumUnitaryFunding: number; /** * @description Current mark price of the symbol */ markPrice: number; /** * @description Base maintenance margin rate */ baseMMR: number; /** * @description Base initial margin rate */ baseIMR: number; /** * @description IMR calculation factor */ IMR_Factor: number; /** * @description Leverage for this isolated position */ leverage: number; /** * @description Fee buffer reserved in isolated margin estimates (default: 0.0006) */ isoTakerFeeBuffer?: number; /** * @description New order information used for estimation */ newOrder: { /** * @description Symbol of the order (kept for interface consistency) */ symbol: string; /** * @description Order quantity (positive for BUY, negative for SELL) */ qty: number; /** * @description Order price (reference price when opening / adding / flipping) */ price: number; }; }): number; /** * @formulaId estLiqPrice * @name Est. Position liq. Price * @description * * ## When user has positions: * * ``` * Est. liq. Position Price = max(mark_price_i + (total_collateral_value - new_total_MM - order_fee) / (abs(position_qty_i + new_order_qty_i) * new_MMRi - (position_qty_i + new_order_qty_i)), 0) * ``` * * ## When user has no positions: * * ``` * Est. liq. Position Price = max(order_price_i + (total_collateral_value - new_total_MM - order_fee) / (abs(position_qty_i + new_order_qty_i) * new_MMRi - (position_qty_i + new_order_qty_i)), 0) * ``` * * ## Formula Components: * * - `order_fee = new_order_qty_i * order_price_i * futures_take_fee_rate` * - `new_total_MM = sum(abs(position_qty_i * mark_price_i + new_order_qty_i * order_price_i)) * MMRi)` * - `new_MMRi = Max(Base_MMR_i, (Base_MMR_i / Base_IMR_i) * IMR_Factor_i * Abs(position_qty_i * mark_price_i + new_order_qty_i * limit_price_i)^(4/5))` * * ## Order Price Determination: * * ### Market Order: * - **Long order**: `order_price_i = ask0` * - **Short order**: `order_price_i = bid0` * * ### Limit Order: * * #### Long order: * - If `limit_price >= ask0`: `order_price_i = ask0` * - If `limit_price < ask0`: `order_price_i = limit_price` * * #### Short order: * - If `limit_price <= bid0`: `order_price_i = bid0` * - If `limit_price > bid0`: `order_price_i = limit_price` * * ## Parameter Definitions: * * | Parameter | Description | * |-----------|-------------| * | `Est. Position liq. Price` | Estimated liquidation price for the position | * | `position_qty_i` | Position quantity for a single symbol | * | `mark_price_i` | Mark price for a single symbol | * | `total_collateral_value` | Total asset value of user's account margin (USDC denominated) | * | `new_order_qty_i` | Symbol quantity when user prepares to open position (positive for long, negative for short) | * | `new_total_MM` | Sum of current position maintenance margin (including prepared order maintenance margin) | * | `new_MMR_i` | Maintenance margin rate for a single symbol (including prepared order notional consideration) | * | `Base_MMR_i` | Base maintenance margin rate for a single symbol | * | `Base_IMR_i` | Base initial margin rate for a single symbol | * | `IMR_Factor_i` | IMR calculation factor for a single symbol, from v1/client/info | * | `Position_Notional_i` | Sum of position notional for a single symbol | * | `order_fee` | Estimated order fee when user prepares to open position | * | `futures_take_fee_rate` | User's futures take fee rate, from GET /v1/client/info | * | `order_price_i` | Estimated execution price when user prepares to open position | * | `limit_price` | Price entered by user when preparing to open position | * | `ask0` | Minimum ask price from orderbook | * | `bid0` | Maximum bid price from orderbook | * * ## Examples: * * ### Market Order Example: * Long BTC qty = 0.1, mark price = 25986.2, ask0 = 26000, BTC position_qty_i = 0.2, ETH position_qty_i = -3 * futures_take_fee_rate = 0.06% * * **Result**: BTC Est. Position liq. Price = 21268.7316 * * ### Limit Order Example 1: * Long BTC qty = 0.1, mark price = 25986.2, ask0 = 26000, limit price = 25000, BTC position_qty_i = 0.2, ETH position_qty_i = -3 * * **Result**: BTC Est. Position liq. Price = 21250.9772 * * ### Limit Order Example 2: * Short BTC qty = -0.1, mark price = 25986.2, bid0 = 25900, limit price = 25000, BTC position_qty_i = 0.2, ETH position_qty_i = -3 * * **Result**: BTC Est. Position liq. Price = 9102.17368 * * ### No Position Example: * Long BTC qty = 0.1, mark price = 25986.2, ask0 = 26000, limit price = 25000 * * **Result**: BTC Est. Position liq. Price = 5472 * * @param inputs * @returns */ declare function estLiqPrice(inputs: { totalCollateral: number; markPrice: number; baseMMR: number; baseIMR: number; IMR_Factor: number; orderFee: number; positions: { position_qty: number; mark_price: number; symbol: string; mmr: number; }[]; newOrder: { symbol: string; qty: number; price: number; }; }): number; /** * Estimated leverage * @param inputs EstimtedLeverageInputs * @returns number */ declare function estLeverage(inputs: { totalCollateral: number; positions: Pick[]; newOrder: { symbol: string; qty: number; price: number; }; }): number | null; declare function tpslROI(inputs: { side: OrderSide; type: "tp" | "sl"; closePrice: number; orderPrice: number; leverage: number; }): number; type order_EstimatedLeverageInputs = EstimatedLeverageInputs; type order_EstimatedLiquidationPriceInputs = EstimatedLiquidationPriceInputs; declare const order_estLeverage: typeof estLeverage; declare const order_estLiqPrice: typeof estLiqPrice; declare const order_estLiqPriceIsolated: typeof estLiqPriceIsolated; declare const order_getOrderReferencePrice: typeof getOrderReferencePrice; declare const order_maxPrice: typeof maxPrice; declare const order_minPrice: typeof minPrice; declare const order_orderFee: typeof orderFee; declare const order_scopePrice: typeof scopePrice; declare const order_tpslROI: typeof tpslROI; declare namespace order { export { type order_EstimatedLeverageInputs as EstimatedLeverageInputs, type order_EstimatedLiquidationPriceInputs as EstimatedLiquidationPriceInputs, order_estLeverage as estLeverage, order_estLiqPrice as estLiqPrice, order_estLiqPriceIsolated as estLiqPriceIsolated, order_getOrderReferencePrice as getOrderReferencePrice, order_maxPrice as maxPrice, order_minPrice as minPrice, order_orderFee as orderFee, order_scopePrice as scopePrice, order_tpslROI as tpslROI }; } export { index as account, order, order as orderUtils, index$1 as positions, _default as version };