Skip to main content

OrderManager

Struct OrderManager 

Source
pub struct OrderManager { /* private fields */ }

Implementations§

Source§

impl OrderManager

Source

pub fn new( rest_client: Arc<BinanceRestClient>, symbol: &str, market: MarketKind, order_amount_usdt: f64, risk_config: &RiskConfig, ) -> Self

Create a new order manager bound to a single symbol/market context.

The instance keeps in-memory position, cached balances, and an embedded RiskModule that enforces pre-trade checks and global rate budget.

§Caution

This manager is stateful (last_price, balances, active orders). Reuse the same instance for a symbol stream instead of recreating per tick.

Source

pub fn position(&self) -> &Position

Return current in-memory position snapshot.

Values reflect fills processed by this process. They are not a full exchange reconciliation snapshot.

Source

pub fn market_kind(&self) -> MarketKind

Source

pub fn balances(&self) -> &HashMap<String, f64>

Return latest cached free balances.

Cache is updated by refresh_balances. Missing assets should be treated as zero balance.

Source

pub fn update_unrealized_pnl(&mut self, current_price: f64)

Update last price and recompute unrealized PnL.

§Usage

Call on every market data tick before submit_order, so risk checks use a valid last_price.

Source

pub fn last_price(&self) -> Option<f64>

Source

pub fn open_order_count(&self) -> usize

Source

pub fn reserved_cash_usdt(&self) -> f64

Source

pub fn rate_budget_snapshot(&self) -> RateBudgetSnapshot

Return current global rate-budget snapshot from the risk module.

Intended for UI display and observability.

Source

pub fn orders_rate_budget_snapshot(&self) -> RateBudgetSnapshot

Source

pub fn account_rate_budget_snapshot(&self) -> RateBudgetSnapshot

Source

pub fn market_data_rate_budget_snapshot(&self) -> RateBudgetSnapshot

Source

pub fn would_exceed_symbol_exposure_limit( &self, side: OrderSide, qty: f64, ) -> bool

Return whether a hypothetical fill would exceed symbol exposure limit.

This is intended for validation and tests; it does not mutate state.

Source

pub async fn refresh_balances(&mut self) -> Result<HashMap<String, f64>>

Fetch account balances from Binance and update internal state.

Returns the map asset -> free for assets with non-zero total (spot) or non-trivial wallet balance (futures).

§Usage

Refresh before order submission cycles to reduce false “insufficient balance” rejections from stale cache.

§Caution

Network/API failures return Err(_) and leave previous cache untouched.

Source

pub async fn refresh_order_history( &mut self, limit: usize, ) -> Result<OrderHistorySnapshot>

Fetch order history from exchange and format rows for UI display.

This method combines order and trade endpoints, persists snapshots to local sqlite, and emits a best-effort history view even if one endpoint fails.

§Caution

trade_data_complete = false means derived PnL may be partial.

Source

pub async fn submit_order( &mut self, signal: Signal, source_tag: &str, ) -> Result<Option<OrderUpdate>>

Build an order intent, run risk checks, and submit to broker when approved.

§Behavior
  • Signal::Hold returns Ok(None).
  • For buy/sell signals, this method:
    1. Builds OrderIntent.
    2. Calls RiskModule::evaluate_intent.
    3. Reserves one global rate token via reserve_rate_budget.
    4. Submits market order to spot/futures broker endpoint.
  • Rejections are returned as Ok(Some(OrderUpdate::Rejected { .. })) with structured reason_code.
§Usage

Recommended sequence:

  1. update_unrealized_pnl(last_price)
  2. refresh_balances() (periodic or before trading loop)
  3. submit_order(signal, source_tag)
§Caution
  • Spot sell requires base-asset balance (e.g. ETH for ETHUSDT).
  • If balances are stale, you may see “No position to sell” or "Insufficient <asset>" even though exchange state changed recently.
  • This method returns transport/runtime errors as Err(_); business rejections are encoded in OrderUpdate::Rejected.
Source

pub async fn place_protective_stop_for_open_position( &mut self, source_tag: &str, stop_price: f64, ) -> Result<Option<String>>

Attempt to place a protective stop for the currently open position.

Futures: submits STOP_MARKET reduce-only order. Spot: currently returns Ok(None) (spot stop order path is not yet wired).

Source

pub async fn ensure_protective_stop( &mut self, source_tag: &str, fallback_stop_price: f64, ) -> Result<bool>

Ensure a protective stop exists for open position.

Returns:

  • Ok(true) when flat (no protection needed) or placement succeeded
  • Ok(false) when protection was needed but could not be placed
Source

pub async fn emergency_close_position( &mut self, source_tag: &str, reason_code: &str, ) -> Result<Option<OrderUpdate>>

Emergency close helper for runtime/system-triggered liquidation paths.

If position is already flat, returns Ok(None) without broker call.

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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