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
impl O2Client
fn should_whitelist_account(&self) -> bool
fn parse_account_nonce( raw_nonce: Option<u64>, _context: &str, ) -> Result<u64, O2Error>
async fn retry_whitelist_account(&self, trade_account_id: &str) -> bool
async fn retry_mint_to_contract(&self, trade_account_id: &str) -> bool
async fn should_faucet_account(&mut self, trade_account_id: &str) -> bool
Sourcepub fn with_config(config: NetworkConfig) -> Self
pub fn with_config(config: NetworkConfig) -> Self
Create a new O2Client with a custom configuration.
Sourcepub fn set_metadata_policy(&mut self, policy: MetadataPolicy)
pub fn set_metadata_policy(&mut self, policy: MetadataPolicy)
Configure how market metadata should be refreshed.
Sourcepub fn generate_wallet(&self) -> Result<Wallet, O2Error>
pub fn generate_wallet(&self) -> Result<Wallet, O2Error>
Generate a new Fuel-native wallet.
Sourcepub fn generate_evm_wallet(&self) -> Result<EvmWallet, O2Error>
pub fn generate_evm_wallet(&self) -> Result<EvmWallet, O2Error>
Generate a new EVM-compatible wallet.
Sourcepub fn load_wallet(&self, private_key_hex: &str) -> Result<Wallet, O2Error>
pub fn load_wallet(&self, private_key_hex: &str) -> Result<Wallet, O2Error>
Load a Fuel-native wallet from a private key hex string.
Sourcepub fn load_evm_wallet(
&self,
private_key_hex: &str,
) -> Result<EvmWallet, O2Error>
pub fn load_evm_wallet( &self, private_key_hex: &str, ) -> Result<EvmWallet, O2Error>
Load an EVM wallet from a private key hex string.
Sourcepub async fn fetch_markets(&mut self) -> Result<&MarketsResponse, O2Error>
pub async fn fetch_markets(&mut self) -> Result<&MarketsResponse, O2Error>
Fetch and cache markets.
Sourceasync fn ensure_markets(&mut self) -> Result<&MarketsResponse, O2Error>
async fn ensure_markets(&mut self) -> Result<&MarketsResponse, O2Error>
Get cached markets, fetching if needed.
fn should_refresh_markets(&self) -> bool
Sourcepub async fn get_market<M>(&mut self, symbol: M) -> Result<Market, O2Error>where
M: IntoMarketSymbol,
pub async fn get_market<M>(&mut self, symbol: M) -> Result<Market, O2Error>where
M: IntoMarketSymbol,
Get a market by symbol pair (e.g., “FUEL/USDC”).
Sourcepub async fn get_market_by_id(
&mut self,
market_id: &MarketId,
) -> Result<Market, O2Error>
pub async fn get_market_by_id( &mut self, market_id: &MarketId, ) -> Result<Market, O2Error>
Get a market by hex market ID.
Sourceasync fn get_chain_id(&mut self) -> Result<u64, O2Error>
async fn get_chain_id(&mut self) -> Result<u64, O2Error>
Get the chain_id from cached markets.
Sourcepub async fn setup_account<W: SignableWallet>(
&mut self,
wallet: &W,
) -> Result<AccountResponse, O2Error>
pub async fn setup_account<W: SignableWallet>( &mut self, wallet: &W, ) -> Result<AccountResponse, O2Error>
Sourcepub async fn top_up_from_faucet<W: SignableWallet>(
&self,
owner: &W,
) -> Result<FaucetResponse, O2Error>
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.
Sourcepub async fn create_session<W: SignableWallet, S: AsRef<str>>(
&mut self,
owner: &W,
market_names: &[S],
ttl: Duration,
) -> Result<Session, O2Error>
pub async fn create_session<W: SignableWallet, S: AsRef<str>>( &mut self, owner: &W, market_names: &[S], ttl: Duration, ) -> Result<Session, O2Error>
Sourcepub async fn create_session_until<W: SignableWallet, S: AsRef<str>>(
&mut self,
owner: &W,
market_names: &[S],
expiry_unix_secs: u64,
) -> Result<Session, O2Error>
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>
Sourcepub async fn actions_for<M>(
&mut self,
market_name: M,
) -> Result<MarketActionsBuilder, O2Error>where
M: IntoMarketSymbol,
pub async fn actions_for<M>(
&mut self,
market_name: M,
) -> Result<MarketActionsBuilder, O2Error>where
M: IntoMarketSymbol,
Create a single-market action builder with normalized market context.
Sourcefn check_session_expiry(session: &Session) -> Result<(), O2Error>
fn check_session_expiry(session: &Session) -> Result<(), O2Error>
Check if a session has expired and return an error if so.
Sourcepub 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>where
M: IntoMarketSymbol,
P: TryInto<OrderPriceInput, Error = O2Error>,
Q: TryInto<OrderQuantityInput, Error = O2Error>,
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>where
M: IntoMarketSymbol,
P: TryInto<OrderPriceInput, Error = O2Error>,
Q: TryInto<OrderQuantityInput, Error = O2Error>,
Place a new order.
price and quantity accept flexible inputs:
- typed market-bound wrappers:
Price,Quantity - raw decimals:
crate::UnsignedDecimal - decimal strings:
&str/String
If settle_first is true, a SettleBalance action is prepended.
Sourcepub async fn cancel_order<M>(
&mut self,
session: &mut Session,
order_id: &OrderId,
market_name: M,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
pub async fn cancel_order<M>(
&mut self,
session: &mut Session,
order_id: &OrderId,
market_name: M,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
Cancel an order by order_id.
Sourcepub async fn cancel_all_orders<M>(
&mut self,
session: &mut Session,
market_name: M,
) -> Result<Vec<SessionActionsResponse>, O2Error>where
M: IntoMarketSymbol,
pub async fn cancel_all_orders<M>(
&mut self,
session: &mut Session,
market_name: M,
) -> Result<Vec<SessionActionsResponse>, O2Error>where
M: IntoMarketSymbol,
Cancel all open orders for a market.
fn build_cancel_actions<'a, I>(order_ids: I) -> Vec<Action>where
I: IntoIterator<Item = &'a OrderId>,
Sourcepub async fn batch_actions<M>(
&mut self,
session: &mut Session,
market_name: M,
actions: Vec<Action>,
collect_orders: bool,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
pub async fn batch_actions<M>(
&mut self,
session: &mut Session,
market_name: M,
actions: Vec<Action>,
collect_orders: bool,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
Submit a batch of typed actions for a single market.
Handles price/quantity scaling, encoding, signing, and nonce management.
Sourcepub async fn batch_actions_multi<M>(
&mut self,
session: &mut Session,
market_actions: &[(M, Vec<Action>)],
collect_orders: bool,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol + Clone,
pub async fn batch_actions_multi<M>(
&mut self,
session: &mut Session,
market_actions: &[(M, Vec<Action>)],
collect_orders: bool,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol + Clone,
Submit a batch of typed actions across one or more markets.
Sourcepub async fn settle_balance<M>(
&mut self,
session: &mut Session,
market_name: M,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
pub async fn settle_balance<M>(
&mut self,
session: &mut Session,
market_name: M,
) -> Result<SessionActionsResponse, O2Error>where
M: IntoMarketSymbol,
Settle balance for a market.
Sourcepub async fn get_depth<M>(
&mut self,
market_name: M,
precision: u64,
limit: Option<usize>,
) -> Result<DepthSnapshot, O2Error>where
M: IntoMarketSymbol,
pub async fn get_depth<M>(
&mut self,
market_name: M,
precision: u64,
limit: Option<usize>,
) -> Result<DepthSnapshot, O2Error>where
M: IntoMarketSymbol,
Get order book depth.
§Arguments
market_name- Market pair string (e.g."ETH/USDC") or market ID.precision- Price grouping level, from1(most precise) to18(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 asstream_depth.limit- Maximum number of price levels per side.
§Errors
Returns O2Error::InvalidRequest if precision is outside 1–18.
Sourcepub async fn get_trades<M>(
&mut self,
market_name: M,
count: u32,
start_timestamp: Option<u64>,
start_trade_id: Option<&TradeId>,
) -> Result<TradesResponse, O2Error>where
M: IntoMarketSymbol,
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>where
M: IntoMarketSymbol,
Get recent trades for a market.
Use start_timestamp + start_trade_id for cursor pagination
(both must be provided together or omitted).
Sourcepub 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>where
M: IntoMarketSymbol,
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>where
M: IntoMarketSymbol,
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).
Sourcepub async fn get_bars<M>(
&mut self,
market_name: M,
resolution: &str,
from_ts: u64,
to_ts: u64,
) -> Result<Vec<Bar>, O2Error>where
M: IntoMarketSymbol,
pub async fn get_bars<M>(
&mut self,
market_name: M,
resolution: &str,
from_ts: u64,
to_ts: u64,
) -> Result<Vec<Bar>, O2Error>where
M: IntoMarketSymbol,
Get OHLCV bars.
from_ts and to_ts are in milliseconds (not seconds).
Sourcepub async fn get_ticker<M>(
&mut self,
market_name: M,
) -> Result<MarketTicker, O2Error>where
M: IntoMarketSymbol,
pub async fn get_ticker<M>(
&mut self,
market_name: M,
) -> Result<MarketTicker, O2Error>where
M: IntoMarketSymbol,
Get market ticker.
Sourcepub async fn get_balances(
&mut self,
trade_account_id: impl IntoValidId<TradeAccountId>,
) -> Result<HashMap<String, BalanceResponse>, O2Error>
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.
Sourcepub 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>where
M: IntoMarketSymbol,
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>where
M: IntoMarketSymbol,
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).
Sourcepub async fn get_order<M>(
&mut self,
market_name: M,
order_id: impl IntoValidId<OrderId>,
) -> Result<Order, O2Error>where
M: IntoMarketSymbol,
pub async fn get_order<M>(
&mut self,
market_name: M,
order_id: impl IntoValidId<OrderId>,
) -> Result<Order, O2Error>where
M: IntoMarketSymbol,
Get a single order.
Sourcepub async fn get_nonce(
&self,
trade_account_id: impl IntoValidId<TradeAccountId>,
) -> Result<u64, O2Error>
pub async fn get_nonce( &self, trade_account_id: impl IntoValidId<TradeAccountId>, ) -> Result<u64, O2Error>
Get the current nonce for a trading account.
Sourcepub async fn refresh_nonce(&self, session: &mut Session) -> Result<u64, O2Error>
pub async fn refresh_nonce(&self, session: &mut Session) -> Result<u64, O2Error>
Refresh the nonce on a session from the API.
Sourcepub async fn withdraw<W: SignableWallet>(
&mut self,
owner: &W,
session: &Session,
asset_id: &AssetId,
amount: &str,
to: Option<&str>,
) -> Result<WithdrawResponse, O2Error>
pub async fn withdraw<W: SignableWallet>( &mut self, owner: &W, session: &Session, asset_id: &AssetId, amount: &str, to: Option<&str>, ) -> Result<WithdrawResponse, O2Error>
Sourceasync fn ensure_ws(
ws_slot: &mut Option<O2WebSocket>,
ws_url: &str,
) -> Result<(), O2Error>
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.
Sourcepub async fn stream_depth(
&self,
market_id: impl IntoValidId<MarketId>,
precision: u64,
) -> Result<TypedStream<DepthUpdate>, O2Error>
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 asget_depth.
§Errors
Returns O2Error::InvalidRequest if precision is outside 1–18.
Sourcepub async fn stream_orders(
&self,
identities: &[Identity],
) -> Result<TypedStream<OrderUpdate>, O2Error>
pub async fn stream_orders( &self, identities: &[Identity], ) -> Result<TypedStream<OrderUpdate>, O2Error>
Stream order updates over a shared WebSocket connection.
Sourcepub async fn stream_trades(
&self,
market_id: impl IntoValidId<MarketId>,
) -> Result<TypedStream<TradeUpdate>, O2Error>
pub async fn stream_trades( &self, market_id: impl IntoValidId<MarketId>, ) -> Result<TypedStream<TradeUpdate>, O2Error>
Stream trade updates over a shared WebSocket connection.
Sourcepub async fn stream_balances(
&self,
identities: &[Identity],
) -> Result<TypedStream<BalanceUpdate>, O2Error>
pub async fn stream_balances( &self, identities: &[Identity], ) -> Result<TypedStream<BalanceUpdate>, O2Error>
Stream balance updates over a shared WebSocket connection.
Sourcepub async fn stream_nonce(
&self,
identities: &[Identity],
) -> Result<TypedStream<NonceUpdate>, O2Error>
pub async fn stream_nonce( &self, identities: &[Identity], ) -> Result<TypedStream<NonceUpdate>, O2Error>
Stream nonce updates over a shared WebSocket connection.
Sourcepub async fn subscribe_ws_lifecycle(
&self,
) -> Result<Receiver<WsLifecycleEvent>, O2Error>
pub async fn subscribe_ws_lifecycle( &self, ) -> Result<Receiver<WsLifecycleEvent>, O2Error>
Subscribe to shared WebSocket lifecycle events (reconnect/disconnect).
Sourcepub async fn disconnect_ws(&self) -> Result<(), O2Error>
pub async fn disconnect_ws(&self) -> Result<(), O2Error>
Disconnect the shared WebSocket connection and release resources.