O2Client

Struct O2Client 

Source
pub struct O2Client {
    pub api: O2Api,
    pub config: NetworkConfig,
    markets_cache: Option<MarketsResponse>,
    markets_cache_at: Option<Instant>,
    metadata_policy: MetadataPolicy,
    ws: Mutex<Option<O2WebSocket>>,
}
Expand description

The high-level O2 Exchange client.

Fields§

§api: O2Api§config: NetworkConfig§markets_cache: Option<MarketsResponse>§markets_cache_at: Option<Instant>§metadata_policy: MetadataPolicy§ws: Mutex<Option<O2WebSocket>>

Implementations§

Source§

impl O2Client

Source

fn should_whitelist_account(&self) -> bool

Source

fn parse_account_nonce( raw_nonce: Option<u64>, _context: &str, ) -> Result<u64, O2Error>

Source

async fn retry_whitelist_account(&self, trade_account_id: &str) -> bool

Source

async fn retry_mint_to_contract(&self, trade_account_id: &str) -> bool

Source

async fn should_faucet_account(&mut self, trade_account_id: &str) -> bool

Source

pub fn new(network: Network) -> Self

Create a new O2Client for the given network.

Source

pub fn with_config(config: NetworkConfig) -> Self

Create a new O2Client with a custom configuration.

Source

pub fn set_metadata_policy(&mut self, policy: MetadataPolicy)

Configure how market metadata should be refreshed.

Source

pub fn generate_wallet(&self) -> Result<Wallet, O2Error>

Generate a new Fuel-native wallet.

Source

pub fn generate_evm_wallet(&self) -> Result<EvmWallet, O2Error>

Generate a new EVM-compatible wallet.

Source

pub fn load_wallet(&self, private_key_hex: &str) -> Result<Wallet, O2Error>

Load a Fuel-native wallet from a private key hex string.

Source

pub fn load_evm_wallet( &self, private_key_hex: &str, ) -> Result<EvmWallet, O2Error>

Load an EVM wallet from a private key hex string.

Source

pub async fn fetch_markets(&mut self) -> Result<&MarketsResponse, O2Error>

Fetch and cache markets.

Source

async fn ensure_markets(&mut self) -> Result<&MarketsResponse, O2Error>

Get cached markets, fetching if needed.

Source

fn should_refresh_markets(&self) -> bool

Source

pub async fn get_markets(&mut self) -> Result<Vec<Market>, O2Error>

Get all markets.

Source

pub async fn get_market<M>(&mut self, symbol: M) -> Result<Market, O2Error>

Get a market by symbol pair (e.g., “FUEL/USDC”).

Source

pub async fn get_market_by_id( &mut self, market_id: &MarketId, ) -> Result<Market, O2Error>

Get a market by hex market ID.

Source

async fn get_chain_id(&mut self) -> Result<u64, O2Error>

Get the chain_id from cached markets.

Source

pub async fn setup_account<W: SignableWallet>( &mut self, wallet: &W, ) -> Result<AccountResponse, O2Error>

Idempotent account setup: creates account, funds via faucet, whitelists. Safe to call on every bot startup. Works with both Wallet and EvmWallet.

Source

pub async fn top_up_from_faucet<W: SignableWallet>( &self, owner: &W, ) -> Result<FaucetResponse, O2Error>

Mint test assets from faucet directly to the owner’s trading account contract.

Useful for explicit testnet/devnet top-ups after account setup.

Source

pub async fn create_session<W: SignableWallet, S: AsRef<str>>( &mut self, owner: &W, market_names: &[S], ttl: Duration, ) -> Result<Session, O2Error>

Create a trading session with a relative TTL.

Works with both Wallet (Fuel-native) and EvmWallet.

Source

pub async fn create_session_until<W: SignableWallet, S: AsRef<str>>( &mut self, owner: &W, market_names: &[S], expiry_unix_secs: u64, ) -> Result<Session, O2Error>

Create a trading session that expires at an absolute UNIX timestamp.

Works with both Wallet (Fuel-native) and EvmWallet.

Source

pub async fn actions_for<M>( &mut self, market_name: M, ) -> Result<MarketActionsBuilder, O2Error>

Create a single-market action builder with normalized market context.

Source

fn check_session_expiry(session: &Session) -> Result<(), O2Error>

Check if a session has expired and return an error if so.

Source

pub async fn create_order<M, P, Q>( &mut self, session: &mut Session, market_name: M, side: Side, price: P, quantity: Q, order_type: OrderType, settle_first: bool, collect_orders: bool, ) -> Result<SessionActionsResponse, O2Error>

Place a new order.

price and quantity accept flexible inputs:

If settle_first is true, a SettleBalance action is prepended.

Source

pub async fn cancel_order<M>( &mut self, session: &mut Session, order_id: &OrderId, market_name: M, ) -> Result<SessionActionsResponse, O2Error>

Cancel an order by order_id.

Source

pub async fn cancel_all_orders<M>( &mut self, session: &mut Session, market_name: M, ) -> Result<Vec<SessionActionsResponse>, O2Error>

Cancel all open orders for a market.

Source

fn build_cancel_actions<'a, I>(order_ids: I) -> Vec<Action>
where I: IntoIterator<Item = &'a OrderId>,

Source

pub async fn batch_actions<M>( &mut self, session: &mut Session, market_name: M, actions: Vec<Action>, collect_orders: bool, ) -> Result<SessionActionsResponse, O2Error>

Submit a batch of typed actions for a single market.

Handles price/quantity scaling, encoding, signing, and nonce management.

Source

pub async fn batch_actions_multi<M>( &mut self, session: &mut Session, market_actions: &[(M, Vec<Action>)], collect_orders: bool, ) -> Result<SessionActionsResponse, O2Error>

Submit a batch of typed actions across one or more markets.

Source

pub async fn settle_balance<M>( &mut self, session: &mut Session, market_name: M, ) -> Result<SessionActionsResponse, O2Error>

Settle balance for a market.

Source

pub async fn get_depth<M>( &mut self, market_name: M, precision: u64, limit: Option<usize>, ) -> Result<DepthSnapshot, O2Error>

Get order book depth.

§Arguments
  • market_name - Market pair string (e.g. "ETH/USDC") or market ID.
  • precision - Price grouping level, from 1 (most precise) to 18 (most grouped). At level 1, prices are at or near their exact values. Higher levels round prices into larger buckets — useful for a visual depth chart but too coarse for trading. Same scale as stream_depth.
  • limit - Maximum number of price levels per side.
§Errors

Returns O2Error::InvalidRequest if precision is outside 1–18.

Source

pub async fn get_trades<M>( &mut self, market_name: M, count: u32, start_timestamp: Option<u64>, start_trade_id: Option<&TradeId>, ) -> Result<TradesResponse, O2Error>

Get recent trades for a market.

Use start_timestamp + start_trade_id for cursor pagination (both must be provided together or omitted).

Source

pub async fn get_account_trades<M>( &mut self, market_name: M, account: impl IntoValidId<TradeAccountId>, count: u32, start_timestamp: Option<u64>, start_trade_id: Option<&TradeId>, ) -> Result<TradesResponse, O2Error>

Get trades for a specific account on a market.

Use start_timestamp + start_trade_id for cursor pagination (both must be provided together or omitted).

Source

pub async fn get_bars<M>( &mut self, market_name: M, resolution: &str, from_ts: u64, to_ts: u64, ) -> Result<Vec<Bar>, O2Error>

Get OHLCV bars.

from_ts and to_ts are in milliseconds (not seconds).

Source

pub async fn get_ticker<M>( &mut self, market_name: M, ) -> Result<MarketTicker, O2Error>

Get market ticker.

Source

pub async fn get_balances( &mut self, trade_account_id: impl IntoValidId<TradeAccountId>, ) -> Result<HashMap<String, BalanceResponse>, O2Error>

Get balances for a trading account, keyed by asset symbol.

Source

pub async fn get_orders<M>( &mut self, market_name: M, trade_account_id: impl IntoValidId<TradeAccountId>, is_open: Option<bool>, count: u32, start_timestamp: Option<u64>, start_order_id: Option<&OrderId>, ) -> Result<OrdersResponse, O2Error>

Get orders for a trading account in a market.

Use start_timestamp + start_order_id for cursor pagination (both must be provided together or omitted).

Source

pub async fn get_order<M>( &mut self, market_name: M, order_id: impl IntoValidId<OrderId>, ) -> Result<Order, O2Error>

Get a single order.

Source

pub async fn get_nonce( &self, trade_account_id: impl IntoValidId<TradeAccountId>, ) -> Result<u64, O2Error>

Get the current nonce for a trading account.

Source

pub async fn refresh_nonce(&self, session: &mut Session) -> Result<u64, O2Error>

Refresh the nonce on a session from the API.

Source

pub async fn withdraw<W: SignableWallet>( &mut self, owner: &W, session: &Session, asset_id: &AssetId, amount: &str, to: Option<&str>, ) -> Result<WithdrawResponse, O2Error>

Withdraw assets from the trading account to the owner wallet. Works with both Wallet (Fuel-native) and EvmWallet.

Source

async fn ensure_ws( ws_slot: &mut Option<O2WebSocket>, ws_url: &str, ) -> Result<(), O2Error>

Ensure the shared WebSocket is connected, creating or replacing as needed.

Source

pub async fn stream_depth( &self, market_id: impl IntoValidId<MarketId>, precision: u64, ) -> Result<TypedStream<DepthUpdate>, O2Error>

Stream depth updates over a shared WebSocket connection.

§Arguments
  • market_id - The market ID (hex string).
  • precision - Price grouping level, from "1" (most precise) to "18" (most grouped). Default "1". At level 1, prices are at or near their exact values. Higher levels round prices into larger buckets. Same scale as get_depth.
§Errors

Returns O2Error::InvalidRequest if precision is outside 1–18.

Source

pub async fn stream_orders( &self, identities: &[Identity], ) -> Result<TypedStream<OrderUpdate>, O2Error>

Stream order updates over a shared WebSocket connection.

Source

pub async fn stream_trades( &self, market_id: impl IntoValidId<MarketId>, ) -> Result<TypedStream<TradeUpdate>, O2Error>

Stream trade updates over a shared WebSocket connection.

Source

pub async fn stream_balances( &self, identities: &[Identity], ) -> Result<TypedStream<BalanceUpdate>, O2Error>

Stream balance updates over a shared WebSocket connection.

Source

pub async fn stream_nonce( &self, identities: &[Identity], ) -> Result<TypedStream<NonceUpdate>, O2Error>

Stream nonce updates over a shared WebSocket connection.

Source

pub async fn subscribe_ws_lifecycle( &self, ) -> Result<Receiver<WsLifecycleEvent>, O2Error>

Subscribe to shared WebSocket lifecycle events (reconnect/disconnect).

Source

pub async fn disconnect_ws(&self) -> Result<(), O2Error>

Disconnect the shared WebSocket connection and release resources.

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.

§

impl<T> Instrument for T

§

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

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

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.

§

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

§

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
§

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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