Trading SDK — API Reference

Full technical reference for all classes, methods, models, and exceptions in the Trading SDK.

→ User Guide


TradingClient

Location: swarm/trading_sdk/sdk/client.py

Main entry point for unified multi-platform trading. Orchestrates quote aggregation, smart routing, and trade execution across Market Maker and Cross-Chain Access.

Constructor

TradingClient(
    network: Network,
    private_key: str,
    rpq_api_key: str,
    user_email: Optional[str] = None,
    rpc_url: Optional[str] = None,
    routing_strategy: RoutingStrategy = RoutingStrategy.BEST_PRICE,
)

ParameterTypeRequiredDescription
networkNetworkBlockchain network
private_keystrWallet private key (with 0x prefix)
rpq_api_keystrAPI key for Market Maker RPQ Service
user_emailstrUser email for Cross-Chain Access
rpc_urlstrCustom RPC endpoint
routing_strategyRoutingStrategyDefault routing strategy (default: BEST_PRICE)

Attributes: networkrouting_strategymarket_maker_clientcross_chain_access_client


get_quotes()

Get quotes from all available platforms in parallel.

async def get_quotes(
    from_token: str,
    to_token: str,
    from_amount: Optional[Decimal] = None,
    to_amount: Optional[Decimal] = None,
    to_token_symbol: Optional[str] = None,
) -> dict[str, Optional[Quote]]

ParameterTypeRequiredDescription
from_tokenstrToken address to sell
to_tokenstrToken address to buy
from_amountDecimal⚠️Amount to sell (provide this or to_amount)
to_amountDecimal⚠️Amount to buy (provide this or from_amount)
to_token_symbolstrToken symbol for Cross-Chain Access (e.g. "AAPL")

Returns: {"market_maker": Quote | None, "cross_chain_access": Quote | None}

Never raises — unavailable platforms return None.


trade()

Execute a trade with smart routing.

async def trade(
    from_token: str,
    to_token: str,
    user_email: str,
    from_amount: Optional[Decimal] = None,
    to_amount: Optional[Decimal] = None,
    to_token_symbol: Optional[str] = None,
    routing_strategy: Optional[RoutingStrategy] = None,
) -> TradeResult

ParameterTypeRequiredDescription
from_tokenstrToken address to sell
to_tokenstrToken address to buy
user_emailstrUser email for notifications
from_amountDecimal⚠️Amount to sell (provide this or to_amount)
to_amountDecimal⚠️Amount to buy (provide this or from_amount)
to_token_symbolstrToken symbol (required if Cross-Chain Access may be used)
routing_strategyRoutingStrategyOverride default strategy for this trade

Trade flow: quotes fetched in parallel → strategy applied → trade executed → fallback attempted if primary fails (where strategy allows).

Raises: ValueErrorNoLiquidityExceptionAllPlatformsFailedExceptionTradingException

Returns: TradeResult


close()

Close all clients and release resources.

async def close() -> None

Called automatically when using async with. Only needed for manual lifecycle management.


Router

Location: swarm/trading_sdk/routing.py

Internal routing engine. Selects the optimal platform based on availability, price, and strategy.

select_platform()

@staticmethod
def select_platform(
    cross_chain_access_option: PlatformOption,
    market_maker_option: PlatformOption,
    strategy: RoutingStrategy,
    is_buy: bool,
) -> PlatformOption

Price comparison logic for BEST_PRICE:

  • Buy orders: lower rate = better (more tokens per USDC)
  • Sell orders: higher rate = better (more USDC per token)

Raises: NoLiquidityException if no platforms are available under the given strategy.


Data models

Quote

Location: swarm/shared/models.py

FieldTypeDescription
sell_token_addressstrToken being sold
sell_amountDecimalAmount being sold
buy_token_addressstrToken being bought
buy_amountDecimalAmount being bought
rateDecimalExchange rate (buy_amount / sell_amount)
sourcestrPlatform ("market_maker" or "cross_chain_access")
timestampdatetimeQuote timestamp

TradeResult

Location: swarm/shared/models.py

FieldTypeDescription
tx_hashstrBlockchain transaction hash
order_idstrPlatform-specific order/offer ID
sell_token_addressstrToken sold
sell_amountDecimalAmount sold
buy_token_addressstrToken bought
buy_amountDecimalAmount bought
rateDecimalExchange rate
sourcestrPlatform used ("market_maker" or "cross_chain_access")
timestampdatetimeTrade execution time
networkNetworkBlockchain network

PlatformOption

Location: swarm/trading_sdk/routing.py

FieldTypeDescription
platformstr"cross_chain_access" or "market_maker"
quoteQuoteQuote from this platform
availableboolWhether the platform is available
errorstrError message if unavailable

Methods: get_effective_rate() -> Decimal


Enumerations

RoutingStrategy

Location: swarm/trading_sdk/routing.py

class RoutingStrategy(str, Enum):
    BEST_PRICE = "best_price"
    # Compares both platforms, selects best rate. Falls back if primary fails.

    CROSS_CHAIN_ACCESS_FIRST = "cross_chain_access_first"
    # Tries Cross-Chain Access first, falls back to Market Maker.

    MARKET_MAKER_FIRST = "market_maker_first"
    # Tries Market Maker first, falls back to Cross-Chain Access.

    CROSS_CHAIN_ACCESS_ONLY = "cross_chain_access_only"
    # Cross-Chain Access only. No fallback.

    MARKET_MAKER_ONLY = "market_maker_only"
    # Market Maker only. No fallback.

StrategyTries both?Fallback?
BEST_PRICE
CROSS_CHAIN_ACCESS_FIRST
MARKET_MAKER_FIRST
CROSS_CHAIN_ACCESS_ONLY
MARKET_MAKER_ONLY

Exceptions

Exception hierarchy

TradingException (base)
├── NoLiquidityException
├── AllPlatformsFailedException
└── InvalidRoutingStrategyException

TradingException

Base exception for all Trading SDK errors. Location: swarm/trading_sdk/exceptions.py

NoLiquidityException

Raised when no platforms are available under the selected strategy. Includes platform-specific details (e.g. "Market closed" / "No offers").

AllPlatformsFailedException

Raised when both primary and fallback execution attempts fail. Error message includes details for both platforms.

InvalidRoutingStrategyException

Raised when an unrecognised routing strategy is provided. Indicates a programming error.


Platform selection logic

1. Fetch quotes from both platforms in parallel
   ├─ Cross-Chain Access: check market hours, get quote
   └─ Market Maker: query RPQ API, get quote

2. Apply routing strategy
   ├─ BEST_PRICE        → compare rates, pick winner
   ├─ CC_FIRST          → Cross-Chain Access if available, else Market Maker
   ├─ MM_FIRST          → Market Maker if available, else Cross-Chain Access
   ├─ CC_ONLY           → Cross-Chain Access or raise NoLiquidityException
   └─ MM_ONLY           → Market Maker or raise NoLiquidityException

3. Execute trade on selected platform

4. If primary fails and strategy permits fallback:
   ├─ Log primary error
   ├─ Select alternative platform
   └─ Execute fallback trade

5. Return TradeResult or raise exception


Performance notes

Quotes are fetched in parallel, so total quote time ≈ max(Market Maker time, Cross-Chain Access time), not the sum. Typical quote latency is ~300ms.

If a quote fails, the platform is excluded at zero cost (no gas). If a trade fails after on-chain submission, gas is spent and the fallback incurs a second transaction.

Tips:

  • Reuse client instances — don't create a new TradingClient per trade
  • Always provide to_token_symbol to enable Cross-Chain Access quotes
  • Use BEST_PRICE — it fetches both quotes anyway, so there's no overhead vs. a single-platform strategy