Skip to main content

MarginLedger

Struct MarginLedger 

Source
pub struct MarginLedger { /* private fields */ }
Expand description

Manages all isolated margin positions and free USDC balance.

This is the single source of truth for simulated account state, replacing the scattered tracking in PaperExchange and FillSimulator.

Implementations§

Source§

impl MarginLedger

Source

pub fn new(starting_balance: Decimal, fee_rate: Decimal) -> Self

Create a new ledger with starting USDC balance.

Source

pub fn free_usdc(&self) -> Decimal

Free USDC available for new margin reservations.

Source

pub fn set_free_usdc(&mut self, amount: Decimal)

Set free USDC directly (for compatibility with FillSimulator spot logic).

Source

pub fn adjust_free_usdc(&mut self, delta: Decimal)

Adjust free_usdc by delta (positive = add, negative = subtract).

Source

pub fn fee_rate(&self) -> Decimal

Fee rate used for margin calculations.

Source

pub fn set_fee_rate(&mut self, fee_rate: Decimal)

Set fee rate.

Source

pub fn position(&self, instrument: &InstrumentId) -> Option<&IsolatedPosition>

Get position for an instrument (if any).

Source

pub fn position_mut( &mut self, instrument: &InstrumentId, ) -> Option<&mut IsolatedPosition>

Get mutable position for an instrument.

Source

pub fn leverage_for(&self, instrument: &InstrumentId) -> Decimal

Get leverage for an instrument.

Source

pub fn total_reserved_margin(&self) -> Decimal

Total reserved margin across all positions.

Source

pub fn total_unrealized_pnl( &self, marks: &HashMap<InstrumentId, Decimal>, ) -> Decimal

Total unrealized PnL across all positions at given mark prices.

Source

pub fn equity(&self, marks: &HashMap<InstrumentId, Decimal>) -> Decimal

Account equity = free_usdc + total_reserved_margin + total_unrealized_pnl

Source

pub fn position_qty(&self, instrument: &InstrumentId) -> Decimal

Position quantity for an instrument (signed: +long, -short).

Source

pub fn set_leverage( &mut self, instrument: &InstrumentId, leverage: Decimal, max_leverage: Decimal, )

Set leverage for an instrument. leverage is the user’s chosen leverage (e.g. 10x). max_leverage is the exchange maximum for this asset (determines MMR).

Source

pub fn set_default_leverage(&mut self, leverage: Decimal)

Set default leverage for instruments without explicit settings.

Source

pub fn check_margin_for_perp_order( &self, instrument: &InstrumentId, side: OrderSide, price: Decimal, qty: Decimal, reduce_only: bool, ) -> Result<(), String>

Check if there’s sufficient margin for a PERP order.

  • Reducing orders always pass (they release margin).
  • New/increasing orders need: notional / leverage + 2x fee buffer.
  • Spot orders are not handled here (use FillSimulator’s check_balance).
Source

pub fn apply_perp_fill( &mut self, instrument: &InstrumentId, side: OrderSide, fill_price: Decimal, fill_qty: Decimal, fee_amount: Decimal, ) -> Decimal

Apply a PERP fill to the margin ledger.

Handles all scenarios:

  • Opening new position: reserve margin, set entry price
  • Increasing existing position: reserve additional margin, update avg entry
  • Reducing existing position: release margin proportionally, realize PnL
  • Flipping position: close old + open new in opposite direction

Returns the realized PnL from this fill (zero for new positions).

Source

pub fn check_liquidations( &self, marks: &HashMap<InstrumentId, Decimal>, ) -> Vec<InstrumentId>

Check all positions for liquidation at current mark prices. Returns list of instruments that should be liquidated.

Source

pub fn liquidate(&mut self, instrument: &InstrumentId, mark_price: Decimal)

Force-liquidate a position at the given mark price. Closes the entire position, realizes the loss, releases remaining margin.

Source

pub fn position_snapshots( &self, marks: &HashMap<InstrumentId, Decimal>, ) -> Vec<PositionSnapshot>

Generate position snapshots for poll_account_state(). Returns non-flat positions in the format expected by AccountState.

Trait Implementations§

Source§

impl Debug for MarginLedger

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more