Expand description
§rustrade
Open-source trading bot framework — the facade crate downstream
services depend on. Re-exports the core types, the supervisor, and the
risk primitives, and adds the Bot builder that wires them into a
single supervised runtime.
§Quickstart
ⓘ
use std::sync::Arc;
use rustrade::{Bot, BotConfig};
let bot = Bot::new(
BotConfig::builder().name("my-bot").symbol("BTCUSDT").build()?,
Arc::new(MyExchangeAdapter::new()),
vec![Arc::new(MyBrain::new())],
)?;
let handle = bot.handle();
// host can shutdown via handle.shutdown() at any time
bot.run_until_shutdown().await§What this crate adds on top of the sub-crates
Bot/BotConfig/BotConfigBuilder— the embedding entry point. Wraps aSupervisorand the framework-side services.BotHandle/BotHealth— cheap cloneable handle for host services to query state and trigger shutdown without holding theBotitself.Bot::with_market_source/Bot::with_fill_source/Bot::with_external_cancel— optional wirings for adapters and host-driven shutdown.logging::init_tracing— opinionated default tracing subscriber. Skippable; downstream services with their own subscriber don’t use it.
§Tokio runtime requirements
Bot::run_until_shutdown must be awaited inside a multi-thread
tokio runtime context. Internally the supervisor calls
tokio::spawn for every service, and the framework expects the host’s
shutdown to be cooperative (services watch a CancellationToken).
The simplest valid host is:
ⓘ
#[tokio::main(flavor = "multi_thread")]
async fn main() -> anyhow::Result<()> {
// ... build bot ...
bot.run_until_shutdown().await
}Embedding into an existing runtime is supported — just spawn the bot
as a task and hold a BotHandle for control. See
examples/embed-in-service/.
§Resource expectations
- Memory per active symbol: a few hundred bytes for the position
cache entry plus the per-symbol
SymbolRisk(aSessionPnland aCircuitBreakerwhose ring buffer is bounded byloss_limit). - Channel buffers:
market_bus_capacity+signal_bus_capacityslots per bus, each holding a clone ofMarketDataEvent/Signal. Backed bytokio::sync::broadcast, which has drop-oldest semantics: slow subscribers seeRecvError::Lagged(n)and miss the oldest dropped events. - Expected shutdown time: ≤
shutdown_timeout(default 30 s). Well-behaved services drain in milliseconds; the timeout is the worst-case ceiling, not the typical case. - Restart-after-crash latency: bounded by the supervisor’s
rustrade_supervisor::BackoffConfig. Defaults: 100 ms base delay, 60 s cap, 10 retries within a 10-minute window before the circuit breaker trips and the service terminates.
§Module status
| Module | Surface |
|---|---|
bot | Bot, BotConfig, BotConfigBuilder, RiskConfig |
handle | BotHandle, BotHealth, record_trade_outcome |
execution | ExecutionService with full risk-gate pipeline |
services | MarketFeedService, FillRoutingService |
logging | init_tracing |
Re-exports§
pub use bot::Bot;pub use bot::BotConfig;pub use bot::BotConfigBuilder;pub use bot::BracketFailurePolicy;pub use bot::RiskConfig;pub use handle::BotHandle;pub use handle::BotHealth;pub use handle::BrainHealthSnapshot;pub use json_store::JsonFileStore;pub use order_tracker::OcoRegistry;pub use order_tracker::OrderReaperService;pub use order_tracker::OrderTracker;pub use order_tracker::TrackedOrder;pub use services::CandlePollerService;pub use services::FillRoutingService;pub use services::MarketFeedService;
Modules§
- bot
- The
Botentry point and itsBotConfigbuilder. - execution
- Framework-side execution: subscribes to the
MarketDataBusand routes each event through the risk gates to theExchangeClient. - handle
- Cheap cloneable handle into a running
Bot. - json_
store JsonFileStore— a durableStateStorebacked by a single JSON file.- logging
- Opinionated default tracing subscriber for downstream services that don’t already own one.
- order_
tracker - Order lifecycle tracking (0.2c).
- services
- Optional framework-side services wired in via builder methods on
Bot:
Structs§
- Backoff
Config - Configuration for the exponential backoff strategy.
- Brain
Health - Reported health of a
Brain. Surfaces to the supervisor’s health endpoint. - Candle
- OHLCV candle — the atomic unit of batched market data.
- Circuit
Breaker - Sliding-window loss breaker.
- Circuit
Breaker Config - Configuration for
CircuitBreaker. - Decision
- A brain’s decision on a single market event.
- Exchange
- Opaque identifier for which exchange produced this data.
- Fill
- A trade fill reported by the exchange.
- InMemory
Store - Non-durable
StateStorebacked by an in-memory map. - Instrument
Spec - Exchange/asset metadata for one instrument.
- Manual
Clock - A manually-advanceable clock for tests.
- Market
Data Bus - Broadcast channel for normalized market-data events.
- Noop
Sink - Default sink that discards everything. Lower overhead than even a
tracing::trace!call. - Open
Order - A resting (not-yet-terminal) order as reported by the exchange, returned
by
ExchangeClient::get_open_orders. - Order
- A request to enter, exit, or reduce a position.
- Portfolio
Risk - Account-wide risk: a latching daily-loss halt plus a pre-trade entry gate over aggregate exposure and concurrency. See the module docs.
- Portfolio
Risk Config - Configuration for
PortfolioRisk. Every limit is independently disable-able, and theDefaultdisables them all (opt-in). - Portfolio
State - Aggregate account state at the moment of a pre-trade check, assembled by the framework from its per-symbol risk + position state.
- Position
- Current exchange-reported position for a single symbol.
- Position
Sizer - Computes order sizes from margin + leverage + price + contract multiplier.
- Price
- Price in the quote currency (e.g. USD / USDT).
- Service
Lifecycle Snapshot - Point-in-time snapshot of a service’s lifecycle, suitable for
serialization (e.g., for a
/healthJSON endpoint). - Session
Pnl - Running PnL totals for one trading session, with an optional drawdown cap that auto-resets at the daily 00:00 UTC boundary.
- Session
PnlConfig - Configuration for
SessionPnl. - Signal
- A richer signal carrying confidence, source, and arbitrary metadata for logging.
- Signal
Bus - Broadcast channel for trading signals.
- Sizing
Config - Configuration for
PositionSizer. - Spawn
Options - Per-service spawn configuration.
- Stop
Attachment - Stop-order attachment on an
Order. - Supervisor
- The central supervisor.
- Supervisor
Config - Configuration for the
Supervisor. - Symbol
- Identifies an exchange-symbol pair.
- System
Clock - The default clock — reads the OS wall clock via
SystemTime. - Tick
- A single trade tick or best-bid/best-ask snapshot.
- Volume
- Volume / quantity in base-asset units (e.g. BTC, ETH) or in contracts.
Enums§
- Asset
Class - Broad asset class an instrument belongs to. Drives class-aware risk presets (different leverage/stop/size conventions per class) and sizing semantics.
- Capability
- Optional adapter capabilities, queried via
ExchangeClient::supports. - Error
- Framework-level errors.
- Market
Data Event - A normalized market-data event that can come from any exchange.
- Order
Kind - Order kind (market vs limit and their time-in-force variants).
- Order
Status - Status of an order as reported by the exchange.
- Portfolio
Block - Why
PortfolioRisk::check_entryblocked a new entry. - Restart
Policy - Restart policy for a
TradingServiceunder supervisor control. - Service
Phase - Lifecycle phase of a supervised service.
- Side
- Side of a trade or order.
- Signal
Type - A trading signal direction.
- Size
Hint - How large the brain wants the next order to be. The risk layer can honour, scale down, or reject this hint.
- Stop
Kind - What kind of stop attachment an
Ordercarries. - Termination
Reason - Why a service reached the
Terminatedphase.
Traits§
- Brain
- The strategic layer of a trading bot.
- Candle
Source - Periodic candle source — separate from
MarketSourcebecause candle polling has a fundamentally different shape (pull, paced) than streaming events (push, unbounded). - Clock
- Source of wall-clock time, in whole UNIX seconds.
- Event
Source - Received order-book / market-data events from the exchange’s public feed.
- Exchange
Client - What the bot framework needs from an exchange to trade.
- Fill
Source - Received fill events from the exchange’s private feed.
- Market
Source - A source of live market data (WebSocket feed, backtest replay, simulator).
- Metrics
Sink - Push-based metrics interface.
- State
Store - A durable key/value store for framework state snapshots.
- Trading
Service - A long-running task managed by the
crate::Supervisor.
Type Aliases§
- Result
- Result alias used throughout rustrade.