Functions
get_leverage
Calculate the current leverage ratio for a user account.
client- Reference to the DriftClientuser- The user account to calculate leverage for
- Positive value indicates normal leverage
- Negative value indicates user has negative equity
get_spot_asset_value
Calculate the net spot asset value for a user.
client- Reference to the DriftClientuser- The user account
calculate_perp_liability_value
Calculate the liability value of a perp position.
base_asset_amount- Position size (BASE_PRECISION)price- Current price (PRICE_PRECISION)is_prediction_market- Whether this is a prediction market
- For regular markets:
abs(base_asset_amount * price) - For prediction markets: Accounts for the bounded nature of prediction market prices
UserMargin Trait
TheUserMargin trait extends DriftClient with margin calculation helpers.
max_trade_size
Calculate the maximum trade size a user can take in a given market and direction.
user- The user account pubkeymarket- The market to tradetrade_side- Long or Short
- Accounts for existing positions on the opposite side
- Reduce-only trades can use the liability value of opposite positions
- Currently only implemented for perp markets
calculate_perp_buying_power
Calculate the buying power for a specific perp market.
user- The user accountmarket- The perp marketoracle_price- Current oracle price (PRICE_PRECISION)collateral_buffer- Buffer to subtract from free collateral
- Takes into account the user’s margin mode (standard or high leverage)
- Uses the worse of market margin ratio or user’s custom margin ratio
- Accounts for LP positions via collateral buffer
calculate_margin_info
Calculate detailed margin information for a user.
user- The user account
MarginCalculation struct containing:
margin_requirement- Required margintotal_collateral- Total collateral valuetotal_perp_liability_value- Perp position liabilitytotal_spot_liability_value- Spot position liabilitytotal_spot_asset_value- Spot asset value