models — Data models

All API response types are implemented as Python dataclasses with from_dict() class methods for JSON parsing.

Enums

class o2_sdk.models.OrderSide[source]

Side of an order.

BUY = "Buy"
SELL = "Sell"
class o2_sdk.models.OrderType[source]

Type of an order (simple types without additional parameters).

For order types that require additional parameters, use the dedicated dataclasses instead: LimitOrder (for limit orders with price + timestamp) or BoundedMarketOrder (for bounded market orders with max_price + min_price).

SPOT = "Spot"
MARKET = "Market"
FILL_OR_KILL = "FillOrKill"
POST_ONLY = "PostOnly"

Order type parameter classes

class o2_sdk.models.LimitOrder(price, timestamp=None)[source]

Limit order with expiry. In create_order(), price is human-readable and auto-scaled. In CreateOrderAction, price should be the pre-scaled chain integer.

price: float
timestamp: int | None

Unix timestamp for time-in-force. None defaults to the current time.

class o2_sdk.models.BoundedMarketOrder(max_price, min_price)[source]

Bounded market order with price bounds. In create_order(), prices are human-readable and auto-scaled. In CreateOrderAction, prices should be pre-scaled chain integers.

max_price: float
min_price: float

Scalar types

class o2_sdk.models.Id(value)[source]

A hex identifier that always displays with a 0x prefix.

The O2 API returns hex identifiers inconsistently — sometimes with the 0x prefix and sometimes without. Id normalizes the value on construction so that str(id) always starts with 0x, and compares case-insensitively.

Id is a str subclass, so it works transparently in f-strings, comparisons, dict keys, and is not None checks.

Parameters:

value (str) – The hex string, with or without 0x prefix.

>>> from o2_sdk import Id
>>> Id("97edbbf5")
Id('0x97edbbf5')
>>> Id("0x97EDBBF5")
Id('0x97edbbf5')

Market models

class o2_sdk.models.MarketAsset[source]

An asset within a market (base or quote).

symbol: str

The human-readable asset symbol (e.g., "FUEL", "USDC").

asset: str

The on-chain asset ID (0x-prefixed hex).

decimals: int

The number of decimal places for this asset.

max_precision: int

Maximum price precision (number of significant digits).

class o2_sdk.models.Market[source]

A trading market (order book) on the O2 Exchange.

contract_id: Id

The on-chain contract ID managing this order book.

market_id: Id

The unique market identifier within the contract.

maker_fee: str

Maker fee rate (string representation).

taker_fee: str

Taker fee rate (string representation).

min_order: str

Minimum order size (in quote-scaled units).

dust: str

Dust threshold.

price_window: int

Price window constraint.

base: MarketAsset

The base asset definition.

quote: MarketAsset

The quote asset definition.

property pair: str

The human-readable pair string (e.g., "FUEL/USDC").

scale_price(human_value)[source]

Convert a human-readable price to an on-chain integer, truncated to the market’s max_precision.

Parameters:

human_value (float) – The price as a float (e.g., 0.025).

Returns:

The scaled price integer.

Return type:

int

format_price(chain_value)[source]

Convert an on-chain integer price back to a human-readable float.

Parameters:

chain_value (int) – The on-chain price integer.

Returns:

The human-readable price.

Return type:

float

scale_quantity(human_value)[source]

Convert a human-readable quantity to an on-chain integer.

Parameters:

human_value (float) – The quantity as a float (e.g., 100.0).

Returns:

The scaled quantity integer.

Return type:

int

format_quantity(chain_value)[source]

Convert an on-chain integer quantity to a human-readable float.

Parameters:

chain_value (int) – The on-chain quantity integer.

Returns:

The human-readable quantity.

Return type:

float

validate_order(price, quantity)[source]

Validate scaled price/quantity against on-chain constraints.

Checks:

  • PricePrecision: price must be a multiple of the truncation factor.

  • FractionalPrice: (price * quantity) % 10^base_decimals == 0.

  • min_order: forwarded quote amount must meet the minimum.

Parameters:
  • price (int) – The scaled price (on-chain integer).

  • quantity (int) – The scaled quantity (on-chain integer).

Raises:

ValueError – If any constraint is violated.

adjust_quantity(price, quantity)[source]

Adjust a quantity to satisfy the FractionalPrice constraint.

Returns the largest quantity <= the input such that (price * quantity) % 10^base_decimals == 0.

Parameters:
  • price (int) – The scaled price.

  • quantity (int) – The scaled quantity.

Returns:

The adjusted quantity.

Return type:

int

class o2_sdk.models.MarketsResponse[source]

Response from GET /v1/markets.

books_registry_id: Id
accounts_registry_id: Id
trade_account_oracle_id: Id
chain_id: str
base_asset_id: Id
markets: list[Market]
property chain_id_int: int

The chain ID as a plain integer.

Account models

class o2_sdk.models.Identity[source]

Base identity type — either an Address or a ContractId. Use AddressIdentity or ContractIdentity to construct instances directly, or from_dict() to parse from API responses.

value: str

The 0x-prefixed hex string.

classmethod from_dict(d)[source]

Factory method that returns the appropriate subclass.

Parameters:

d (dict) – A dict like {"Address": "0x..."} or {"ContractId": "0x..."}.

Returns:

An AddressIdentity or ContractIdentity.

Return type:

Identity

Raises:

ValueError – If the dict format is not recognized.

property address_bytes: bytes

The address as raw bytes (32 bytes).

to_dict()[source]

Serialize to the API’s JSON format. Implemented by subclasses.

Return type:

dict

property discriminant: int

0 for Address, 1 for ContractId. Implemented by subclasses.

class o2_sdk.models.AddressIdentity(value)[source]

Identity for a Fuel Address. Subclass of Identity.

addr = AddressIdentity("0xabc...")
addr.to_dict()      # {"Address": "0xabc..."}
addr.discriminant    # 0
class o2_sdk.models.ContractIdentity(value)[source]

Identity for a Fuel ContractId. Subclass of Identity.

contract = ContractIdentity("0xdef...")
contract.to_dict()      # {"ContractId": "0xdef..."}
contract.discriminant    # 1
class o2_sdk.models.AccountInfo[source]

Trading account information.

trade_account_id: Id | None

The trading account contract ID, or None if the account does not exist.

trade_account: TradeAccount | None

Detailed account data (nonce, owner, etc.), or None.

session: dict | None

Active session data, if any.

property exists: bool

True if the account exists (i.e., trade_account_id is not None).

property nonce: int

The current nonce for this account. Returns 0 if the account does not exist.

class o2_sdk.models.AccountCreateResponse[source]

Response from POST /v1/accounts.

trade_account_id: Id
nonce: str

Session models

class o2_sdk.models.SessionInfo[source]

An active trading session, returned by create_session().

session_id: Identity

The session identity (the session wallet’s address).

trade_account_id: Id

The trading account this session operates on.

contract_ids: list[Id]

The market contracts this session is authorised for.

session_expiry: str

Unix timestamp (as string) when the session expires.

session_private_key: bytes | None

The session wallet’s private key (used internally for signing actions).

owner_address: str | None

The owner wallet’s B256 address.

nonce: int

The current nonce, updated after each action.

class o2_sdk.models.SessionResponse[source]

Raw response from PUT /v1/session.

tx_id: Id
trade_account_id: Id
contract_ids: list[Id]
session_id: Identity
session_expiry: str

Order models

class o2_sdk.models.Order[source]

An order on the O2 Exchange.

order_id: Id

The unique order identifier.

side: str

"Buy" or "Sell".

order_type: Any

The order type (string or dict for Limit/BoundedMarket).

quantity: str

The order quantity (on-chain scaled, as string).

quantity_fill: str

The filled quantity (on-chain scaled, as string).

price: str

The order price (on-chain scaled, as string).

price_fill: str

The fill price (on-chain scaled, as string).

timestamp: str

The order creation timestamp.

close: bool

True if the order is closed (fully filled or canceled).

partially_filled: bool

True if the order has been partially filled.

cancel: bool

True if the order was canceled.

property is_open: bool

True if the order is still active (not closed).

class o2_sdk.models.OrdersResponse[source]

Response from GET /v1/orders.

identity: Identity | None
market_id: Id
orders: list[Order]

Trade models

class o2_sdk.models.Trade[source]

A completed trade on the exchange.

trade_id: str

The unique trade identifier.

side: str

The taker’s side ("Buy" or "Sell").

total: str

The total quote value of the trade.

quantity: str

The traded quantity (on-chain scaled).

price: str

The trade price (on-chain scaled).

timestamp: str

The trade timestamp.

maker: Identity | None
taker: Identity | None
market_id: Id | None

Balance models

class o2_sdk.models.Balance[source]

Asset balance information for a trading account.

order_books: dict[str, OrderBookBalance]

Per-order-book breakdown of locked and unlocked amounts.

total_locked: str

Total amount locked in open orders (on-chain scaled).

total_unlocked: str

Total unlocked (settled) amount (on-chain scaled).

trading_account_balance: str

Total balance in the trading account (on-chain scaled).

property available: int

The trading account balance as an integer.

class o2_sdk.models.OrderBookBalance[source]

Balance breakdown within a single order book.

locked: str

Amount locked in open orders.

unlocked: str

Amount unlocked (settled).

Depth models

class o2_sdk.models.DepthLevel[source]

A single price level in the order book.

price: str

The price at this level (on-chain scaled).

quantity: str

The total quantity at this level (on-chain scaled).

class o2_sdk.models.DepthSnapshot[source]

A snapshot of order book depth.

buys: list[DepthLevel]

Bid (buy) price levels, best first.

sells: list[DepthLevel]

Ask (sell) price levels, best first.

market_id: Id | None
property best_bid: DepthLevel | None

The best (highest) bid price level, or None if the book is empty.

property best_ask: DepthLevel | None

The best (lowest) ask price level, or None if the book is empty.

class o2_sdk.models.DepthUpdate[source]

A real-time depth update from the WebSocket stream.

changes: DepthSnapshot

The depth changes (or full snapshot for the initial message).

market_id: Id
onchain_timestamp: str | None
seen_timestamp: str | None
is_snapshot: bool

True if this is the initial full snapshot.

Bar models

class o2_sdk.models.Bar[source]

An OHLCV candlestick bar.

time: int

The bar’s opening time (Unix seconds).

open: str

Opening price.

high: str

Highest price.

low: str

Lowest price.

close: str

Closing price.

volume: str

Trading volume.

Action response models

class o2_sdk.models.ActionsResponse[source]

Response from POST /v1/session/actions.

This is the primary result type returned by trading methods such as create_order(), cancel_order(), and batch_actions().

tx_id: Id | None

The on-chain transaction ID, or None on failure.

orders: list[Order] | None

Created order details (only if collect_orders=True).

message: str | None

Error or status message.

reason: str | None

On-chain revert reason, if applicable.

receipts: list | None

Raw transaction receipts.

code: int | None

Error code (see errors — Error types).

property success: bool

True if the action succeeded (tx_id is not None).

Action input models

These dataclasses are the typed inputs for batch_actions(). Each has a to_dict() method that serializes to the wire format expected by the API.

class o2_sdk.models.CreateOrderAction(side, price, quantity, order_type=OrderType.SPOT)[source]

Create a new order. Prices and quantities must be pre-scaled on-chain integers passed as strings.

side: OrderSide
price: str

Pre-scaled chain integer as string.

quantity: str

Pre-scaled chain integer as string.

order_type: OrderType | LimitOrder | BoundedMarketOrder

Defaults to OrderType.SPOT.

class o2_sdk.models.CancelOrderAction(order_id)[source]

Cancel an existing order.

order_id: Id

The normalised hex order ID.

class o2_sdk.models.SettleBalanceAction(to)[source]

Settle balance to an identity. Accepts an Identity subclass (e.g. ContractIdentity) or an Id, which is auto-wrapped as ContractIdentity during serialisation.

to: Identity | Id
# Pass session.trade_account_id directly (an Id):
SettleBalanceAction(to=session.trade_account_id)

# Or pass an explicit Identity:
SettleBalanceAction(to=ContractIdentity("0xabc..."))
class o2_sdk.models.RegisterRefererAction(to)[source]

Register a referer. Same auto-wrapping behaviour as SettleBalanceAction.

to: Identity | Id
o2_sdk.models.Action

Type alias: CreateOrderAction | CancelOrderAction | SettleBalanceAction | RegisterRefererAction

class o2_sdk.models.MarketActions(market_id, actions)[source]

Groups a list of actions for a specific market. This is the input type for batch_actions().

market_id: str

The market’s hex ID.

actions: list[Action]

The actions to execute on this market (max 5 per request).

from o2_sdk import (
    CancelOrderAction, CreateOrderAction, SettleBalanceAction,
    MarketActions, OrderSide, OrderType,
)

batch = MarketActions(
    market_id=market.market_id,
    actions=[
        SettleBalanceAction(to=session.trade_account_id),
        CreateOrderAction(
            side=OrderSide.BUY,
            price=str(scaled_price),
            quantity=str(scaled_qty),
        ),
    ],
)
result = await client.batch_actions([batch], collect_orders=True)

WebSocket update models

class o2_sdk.models.OrderUpdate[source]

Order update from the WebSocket stream.

orders: list[Order]
onchain_timestamp: str | None
seen_timestamp: str | None
class o2_sdk.models.TradeUpdate[source]

Trade update from the WebSocket stream.

trades: list[Trade]
market_id: Id
onchain_timestamp: str | None
seen_timestamp: str | None
class o2_sdk.models.BalanceUpdate[source]

Balance update from the WebSocket stream.

balance: list[dict]
onchain_timestamp: str | None
seen_timestamp: str | None
class o2_sdk.models.NonceUpdate[source]

Nonce update from the WebSocket stream.

contract_id: Id
nonce: str
onchain_timestamp: str | None
seen_timestamp: str | None

Withdrawal models

class o2_sdk.models.WithdrawResponse[source]

Response from POST /v1/accounts/withdraw.

tx_id: Id | None
message: str | None
property success: bool

True if the withdrawal succeeded.

Whitelist & faucet models

class o2_sdk.models.WhitelistResponse[source]

Response from POST /analytics/v1/whitelist.

success: bool
trade_account: str
already_whitelisted: bool
class o2_sdk.models.FaucetResponse[source]

Response from the testnet/devnet faucet.

message: str | None
error: str | None
property success: bool

True if the mint succeeded.

class o2_sdk.models.ReferralInfo[source]

Referral code information.

valid: bool
owner_address: str | None
is_active: bool | None

Aggregated models

class o2_sdk.models.AggregatedAsset[source]

An asset from the aggregated endpoints.

id: Id
symbol: str
name: str
class o2_sdk.models.MarketSummary[source]

Market summary from the aggregated endpoints.

market_id: Id
data: dict
class o2_sdk.models.MarketTicker[source]

Market ticker from the aggregated endpoints.

market_id: Id
data: dict