Skip to main content

Crate rustrade

Crate rustrade 

Source
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

§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 (a SessionPnl and a CircuitBreaker whose ring buffer is bounded by loss_limit).
  • Channel buffers: market_bus_capacity + signal_bus_capacity slots per bus, each holding a clone of MarketDataEvent / Signal. Backed by tokio::sync::broadcast, which has drop-oldest semantics: slow subscribers see RecvError::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

ModuleSurface
botBot, BotConfig, BotConfigBuilder, RiskConfig
handleBotHandle, BotHealth, record_trade_outcome
executionExecutionService with full risk-gate pipeline
servicesMarketFeedService, FillRoutingService
logginginit_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 Bot entry point and its BotConfig builder.
execution
Framework-side execution: subscribes to the MarketDataBus and routes each event through the risk gates to the ExchangeClient.
handle
Cheap cloneable handle into a running Bot.
json_store
JsonFileStore — a durable StateStore backed 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§

BackoffConfig
Configuration for the exponential backoff strategy.
BrainHealth
Reported health of a Brain. Surfaces to the supervisor’s health endpoint.
Candle
OHLCV candle — the atomic unit of batched market data.
CircuitBreaker
Sliding-window loss breaker.
CircuitBreakerConfig
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.
InMemoryStore
Non-durable StateStore backed by an in-memory map.
InstrumentSpec
Exchange/asset metadata for one instrument.
ManualClock
A manually-advanceable clock for tests.
MarketDataBus
Broadcast channel for normalized market-data events.
NoopSink
Default sink that discards everything. Lower overhead than even a tracing::trace! call.
OpenOrder
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.
PortfolioRisk
Account-wide risk: a latching daily-loss halt plus a pre-trade entry gate over aggregate exposure and concurrency. See the module docs.
PortfolioRiskConfig
Configuration for PortfolioRisk. Every limit is independently disable-able, and the Default disables them all (opt-in).
PortfolioState
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.
PositionSizer
Computes order sizes from margin + leverage + price + contract multiplier.
Price
Price in the quote currency (e.g. USD / USDT).
ServiceLifecycleSnapshot
Point-in-time snapshot of a service’s lifecycle, suitable for serialization (e.g., for a /health JSON endpoint).
SessionPnl
Running PnL totals for one trading session, with an optional drawdown cap that auto-resets at the daily 00:00 UTC boundary.
SessionPnlConfig
Configuration for SessionPnl.
Signal
A richer signal carrying confidence, source, and arbitrary metadata for logging.
SignalBus
Broadcast channel for trading signals.
SizingConfig
Configuration for PositionSizer.
SpawnOptions
Per-service spawn configuration.
StopAttachment
Stop-order attachment on an Order.
Supervisor
The central supervisor.
SupervisorConfig
Configuration for the Supervisor.
Symbol
Identifies an exchange-symbol pair.
SystemClock
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§

AssetClass
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.
MarketDataEvent
A normalized market-data event that can come from any exchange.
OrderKind
Order kind (market vs limit and their time-in-force variants).
OrderStatus
Status of an order as reported by the exchange.
PortfolioBlock
Why PortfolioRisk::check_entry blocked a new entry.
RestartPolicy
Restart policy for a TradingService under supervisor control.
ServicePhase
Lifecycle phase of a supervised service.
Side
Side of a trade or order.
SignalType
A trading signal direction.
SizeHint
How large the brain wants the next order to be. The risk layer can honour, scale down, or reject this hint.
StopKind
What kind of stop attachment an Order carries.
TerminationReason
Why a service reached the Terminated phase.

Traits§

Brain
The strategic layer of a trading bot.
CandleSource
Periodic candle source — separate from MarketSource because candle polling has a fundamentally different shape (pull, paced) than streaming events (push, unbounded).
Clock
Source of wall-clock time, in whole UNIX seconds.
EventSource
Received order-book / market-data events from the exchange’s public feed.
ExchangeClient
What the bot framework needs from an exchange to trade.
FillSource
Received fill events from the exchange’s private feed.
MarketSource
A source of live market data (WebSocket feed, backtest replay, simulator).
MetricsSink
Push-based metrics interface.
StateStore
A durable key/value store for framework state snapshots.
TradingService
A long-running task managed by the crate::Supervisor.

Type Aliases§

Result
Result alias used throughout rustrade.