rustrade-framework 0.3.0

Open-source trading bot framework — the facade crate downstream services depend on (imported as `rustrade`)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Optional framework-side services wired in via builder methods on
//! [`Bot`](crate::Bot):
//!
//! - [`MarketFeedService`] — `Bot::with_market_source(...)`. Drives a
//!   [`MarketSource`] under supervisor control; the source publishes
//!   events to the in-process `MarketDataBus` (the bus reference is the
//!   source implementor's responsibility — typically obtained via
//!   `bot.market_data_bus().clone()` before construction).
//! - [`FillRoutingService`] — `Bot::with_fill_source(...)`. Polls a
//!   [`FillSource`], calls [`Brain::on_fill`] on each brain, refreshes
//!   the per-symbol position cache from the exchange, and auto-feeds
//!   realised PnL into the risk gates using weighted-average entry
//!   accounting.
//! - [`CandlePollerService`] — `Bot::with_candle_poller(...)`. Periodic
//!   poll of a [`CandleSource`]; publishes the newest closed candle for
//!   each `(symbol, interval)` pair to the market-data bus.

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use async_trait::async_trait;
use rustrade_core::{
    Brain, CandleSource, Exchange, ExchangeClient, Fill, FillSource, MarketDataBus,
    MarketDataEvent, MarketSource, MetricsSink, Side, Symbol,
};
use rustrade_supervisor::{RestartPolicy, TradingService};
use tokio_util::sync::CancellationToken;

use crate::risk_state::{PositionCache, RiskPersister, RiskStateMap};

// ───────────────────────────────────────────────────────────────────────
// MarketFeedService
// ───────────────────────────────────────────────────────────────────────

/// Drives a [`MarketSource`] under supervisor control.
///
/// The wrapper does not interact with the bus directly — the source's
/// `run` method is expected to publish events to whatever bus it was
/// constructed with. This service just makes the source restartable and
/// drop-safe under the supervisor's cancellation contract.
pub struct MarketFeedService {
    name: String,
    source: Arc<dyn MarketSource>,
}

impl MarketFeedService {
    /// Wrap a [`MarketSource`] into a [`TradingService`].
    pub fn new(source: Arc<dyn MarketSource>) -> Self {
        let name = format!("market-feed[{}]", source.name());
        Self { name, source }
    }
}

#[async_trait]
impl TradingService for MarketFeedService {
    fn name(&self) -> &str {
        &self.name
    }

    fn restart_policy(&self) -> RestartPolicy {
        RestartPolicy::OnFailure
    }

    async fn run(&self, cancel: CancellationToken) -> anyhow::Result<()> {
        tracing::info!(service = %self.name, "market feed starting");
        tokio::select! {
            _ = cancel.cancelled() => {
                tracing::info!(service = %self.name, "market feed cancelled");
                Ok(())
            }
            r = self.source.run() => {
                match &r {
                    Ok(()) => tracing::info!(service = %self.name, "market feed exited cleanly"),
                    Err(e) => tracing::warn!(service = %self.name, error = %e, "market feed exited with error"),
                }
                r.map_err(|e| anyhow::anyhow!("market source error: {e}"))
            }
        }
    }
}

// ───────────────────────────────────────────────────────────────────────
// FillRoutingService
// ───────────────────────────────────────────────────────────────────────

/// Routes fills from a [`FillSource`] to every brain, refreshes the
/// position cache, and auto-feeds realised PnL into the risk state.
///
/// # PnL accounting
///
/// The service uses a **weighted-average entry** model (the same model
/// the backtest engine uses). It reads the cached `Position` *before*
/// refreshing it from the exchange, so the `entry_price` available is
/// the pre-fill average. From that:
///
/// - A fill in the same direction as the open position **adds** to it.
///   No realised PnL emitted; the post-refresh average from
///   `exchange.get_position` becomes the new entry.
/// - A fill in the opposite direction **reduces** the position. Gross
///   PnL = `(fill_price - entry) * closed_qty * direction`. The
///   service calls `BotHandle::record_trade_outcome` on the closed
///   portion to feed `SessionPnl` + `CircuitBreaker`.
/// - A fill that **flips** the position emits realised PnL for the
///   closed portion only; the opening leg is left for the next
///   reducing fill.
///
/// Fees come from `Fill.fee`. Hosts that need a different accounting
/// model (FIFO, LIFO, tax-lot) should compute PnL themselves and call
/// `BotHandle::record_trade_outcome` directly — but cannot also wire a
/// `FillRoutingService`, since the two would double-count.
pub struct FillRoutingService {
    source: Arc<dyn FillSource>,
    brains: Arc<Vec<Arc<dyn Brain>>>,
    exchange: Arc<dyn ExchangeClient>,
    positions: PositionCache,
    risk: RiskStateMap,
    metrics: Arc<dyn MetricsSink>,
    persister: Option<RiskPersister>,
    oco: Option<crate::order_tracker::OcoRegistry>,
    fills_routed: AtomicU64,
    refresh_errors: AtomicU64,
    trades_recorded: AtomicU64,
    oco_cancels: AtomicU64,
}

impl FillRoutingService {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        source: Arc<dyn FillSource>,
        brains: Arc<Vec<Arc<dyn Brain>>>,
        exchange: Arc<dyn ExchangeClient>,
        positions: PositionCache,
        risk: RiskStateMap,
        metrics: Arc<dyn MetricsSink>,
        persister: Option<RiskPersister>,
        oco: Option<crate::order_tracker::OcoRegistry>,
    ) -> Self {
        Self {
            source,
            brains,
            exchange,
            positions,
            risk,
            metrics,
            persister,
            oco,
            fills_routed: AtomicU64::new(0),
            refresh_errors: AtomicU64::new(0),
            trades_recorded: AtomicU64::new(0),
            oco_cancels: AtomicU64::new(0),
        }
    }

    /// Total OCO siblings cancelled in response to a bracket leg filling.
    pub fn oco_cancels(&self) -> u64 {
        self.oco_cancels.load(Ordering::Relaxed)
    }

    /// Total fills delivered to brains since service start.
    pub fn fills_routed(&self) -> u64 {
        self.fills_routed.load(Ordering::Relaxed)
    }

    /// Total `exchange.get_position` failures during cache refresh.
    pub fn refresh_errors(&self) -> u64 {
        self.refresh_errors.load(Ordering::Relaxed)
    }

    /// Total realised-PnL closures fed into the risk state.
    pub fn trades_recorded(&self) -> u64 {
        self.trades_recorded.load(Ordering::Relaxed)
    }

    /// Compute realised PnL from a reducing fill and feed the risk state.
    /// Returns the gross PnL portion attributable to this fill.
    async fn maybe_record_pnl(&self, fill: &Fill, prior_qty: f64, prior_entry: Option<f64>) {
        // Only reducing or flipping fills produce realised PnL.
        let signed_fill_qty = match fill.side {
            Side::Buy => fill.size.value(),
            Side::Sell => -fill.size.value(),
        };
        if prior_qty == 0.0 || prior_qty.signum() == signed_fill_qty.signum() {
            return;
        }
        let Some(entry) = prior_entry else {
            // Reducing fill but no entry price recorded — can't compute
            // PnL. Log and skip.
            tracing::debug!(
                symbol = %fill.symbol,
                "reducing fill but cached position has no entry price; skipping auto-PnL"
            );
            return;
        };
        let closed_qty = prior_qty.abs().min(fill.size.value());
        if closed_qty <= 0.0 {
            return;
        }
        let direction = prior_qty.signum();
        let gross = (fill.price.value() - entry) * direction * closed_qty;
        // Apportion fee by closing fraction so a flip fill charges
        // fees pro-rata to the closing portion.
        let fee_share = if fill.size.value() > 0.0 {
            fill.fee * (closed_qty / fill.size.value())
        } else {
            0.0
        };

        // Update the per-symbol risk state directly.
        let recorded = {
            let mut map = self.risk.write().await;
            if let Some(risk) = map.get_mut(&fill.symbol) {
                risk.session_pnl.record_close(gross, fee_share);
                let net = gross - fee_share;
                if net > 0.0 {
                    risk.circuit_breaker.record_win();
                } else if net < 0.0 {
                    risk.circuit_breaker.record_loss();
                }
                self.trades_recorded.fetch_add(1, Ordering::Relaxed);
                self.metrics.histogram(
                    "rustrade_realised_pnl_quote",
                    &[("symbol", fill.symbol.as_str())],
                    net,
                );
                true
            } else {
                tracing::debug!(
                    symbol = %fill.symbol,
                    "auto-PnL: symbol not in risk-state map (was it configured?)"
                );
                false
            }
        };

        // Persist the updated risk state (lock released) if a store is wired.
        if recorded && let Some(persister) = &self.persister {
            persister.persist_symbol(&self.risk, &fill.symbol).await;
        }
    }
}

#[async_trait]
impl TradingService for FillRoutingService {
    fn name(&self) -> &str {
        "fill-routing"
    }

    fn restart_policy(&self) -> RestartPolicy {
        RestartPolicy::OnFailure
    }

    async fn run(&self, cancel: CancellationToken) -> anyhow::Result<()> {
        tracing::info!("fill-routing service starting");
        loop {
            tokio::select! {
                _ = cancel.cancelled() => {
                    tracing::info!(
                        routed = self.fills_routed(),
                        refresh_errors = self.refresh_errors(),
                        trades_recorded = self.trades_recorded(),
                        "fill-routing service shutting down"
                    );
                    return Ok(());
                }
                next = self.source.next_fill() => {
                    let Some(fill) = next else {
                        tracing::info!("fill source closed; exiting");
                        return Ok(());
                    };

                    let symbol = fill.symbol.clone();

                    // OCO: if this fill belongs to a bracket leg, cancel its
                    // sibling so the position isn't closed twice.
                    if let Some(oco) = &self.oco
                        && let Some((sym, sibling)) = oco.take_sibling(&fill.order_id).await
                    {
                        match self.exchange.cancel_order(&sym, &sibling).await {
                            Ok(_) => {
                                self.oco_cancels.fetch_add(1, Ordering::Relaxed);
                                self.metrics.inc("rustrade_oco_cancels_total");
                                tracing::info!(symbol = %sym, filled = %fill.order_id, cancelled = %sibling, "OCO: cancelled sibling after bracket leg filled");
                            }
                            Err(e) => tracing::warn!(symbol = %sym, sibling = %sibling, error = %e, "OCO: failed to cancel sibling (it may already be gone)"),
                        }
                    }

                    // Snapshot the pre-fill position so we can compute
                    // realised PnL before the exchange refreshes the
                    // entry price.
                    let (prior_qty, prior_entry) = {
                        let map = self.positions.read().await;
                        let p = map.get(&symbol).copied().unwrap_or(rustrade_core::Position::FLAT);
                        (p.qty, p.entry_price)
                    };

                    // Route to every brain. Errors are logged but don't
                    // stop the service — the brain's on_fill is
                    // informational by contract.
                    for brain in self.brains.iter() {
                        if let Err(e) = brain.on_fill(&fill).await {
                            tracing::warn!(
                                brain = brain.name(),
                                error = %e,
                                "brain on_fill returned error"
                            );
                        }
                    }

                    self.maybe_record_pnl(&fill, prior_qty, prior_entry).await;

                    // Refresh position cache from the exchange.
                    match self.exchange.get_position(&symbol).await {
                        Ok(p) => {
                            self.positions.write().await.insert(symbol.clone(), p);
                            tracing::debug!(symbol = %symbol, qty = p.qty, "refreshed position");
                        }
                        Err(e) => {
                            self.refresh_errors.fetch_add(1, Ordering::Relaxed);
                            self.metrics.inc("rustrade_position_refresh_errors_total");
                            tracing::warn!(
                                symbol = %symbol,
                                error = %e,
                                "failed to refresh position after fill"
                            );
                        }
                    }

                    self.fills_routed.fetch_add(1, Ordering::Relaxed);
                    self.metrics.counter(
                        "rustrade_fills_routed_total",
                        &[("symbol", symbol.as_str())],
                        1,
                    );
                }
            }
        }
    }
}

// ───────────────────────────────────────────────────────────────────────
// CandlePollerService
// ───────────────────────────────────────────────────────────────────────

/// Periodic poll of a [`CandleSource`] for a single `(symbol, interval)`
/// pair. Publishes each newly-closed candle to the
/// [`MarketDataBus`].
///
/// Per-symbol cadences are achieved by spawning multiple services —
/// `Bot::with_candle_poller(...)` accepts repeated calls and spawns one
/// service per registered tuple.
///
/// # Deduplication
///
/// The service tracks the highest `Candle::time` it has already
/// published; only candles with a strictly greater timestamp are
/// re-published. This is robust against exchanges that return overlapping
/// windows on consecutive polls.
pub struct CandlePollerService {
    name: String,
    source: Arc<dyn CandleSource>,
    symbol: Symbol,
    interval: Duration,
    poll_cadence: Duration,
    limit: usize,
    bus: MarketDataBus,
    metrics: Arc<dyn MetricsSink>,
    last_time: std::sync::Mutex<i64>,
    polled: AtomicU64,
    poll_errors: AtomicU64,
    published: AtomicU64,
}

impl CandlePollerService {
    pub(crate) fn new(
        source: Arc<dyn CandleSource>,
        symbol: Symbol,
        interval: Duration,
        poll_cadence: Duration,
        limit: usize,
        bus: MarketDataBus,
        metrics: Arc<dyn MetricsSink>,
    ) -> Self {
        let name = format!("candle-poller[{}@{}s]", symbol.as_str(), interval.as_secs());
        Self {
            name,
            source,
            symbol,
            interval,
            poll_cadence,
            limit,
            bus,
            metrics,
            last_time: std::sync::Mutex::new(i64::MIN),
            polled: AtomicU64::new(0),
            poll_errors: AtomicU64::new(0),
            published: AtomicU64::new(0),
        }
    }

    /// Total successful polls.
    pub fn polled(&self) -> u64 {
        self.polled.load(Ordering::Relaxed)
    }
    /// Total failed polls.
    pub fn poll_errors(&self) -> u64 {
        self.poll_errors.load(Ordering::Relaxed)
    }
    /// Total candles published (deduplicated).
    pub fn published(&self) -> u64 {
        self.published.load(Ordering::Relaxed)
    }
}

#[async_trait]
impl TradingService for CandlePollerService {
    fn name(&self) -> &str {
        &self.name
    }

    fn restart_policy(&self) -> RestartPolicy {
        RestartPolicy::OnFailure
    }

    async fn run(&self, cancel: CancellationToken) -> anyhow::Result<()> {
        tracing::info!(service = %self.name, "candle poller starting");
        let exchange = Exchange::from(self.source.name());

        loop {
            tokio::select! {
                _ = cancel.cancelled() => {
                    tracing::info!(
                        service = %self.name,
                        polled = self.polled(),
                        published = self.published(),
                        errors = self.poll_errors(),
                        "candle poller shutting down"
                    );
                    return Ok(());
                }
                _ = tokio::time::sleep(self.poll_cadence) => {
                    match self.source.poll(&self.symbol, self.interval, self.limit).await {
                        Ok(candles) => {
                            self.polled.fetch_add(1, Ordering::Relaxed);
                            let mut last = self.last_time.lock().expect("last_time poisoned");
                            let mut new_high = *last;
                            for candle in candles {
                                if candle.time <= *last {
                                    continue;
                                }
                                new_high = new_high.max(candle.time);
                                self.bus.publish(MarketDataEvent::Candle {
                                    exchange: exchange.clone(),
                                    symbol: self.symbol.clone(),
                                    candle,
                                });
                                self.published.fetch_add(1, Ordering::Relaxed);
                                self.metrics.counter(
                                    "rustrade_candles_published_total",
                                    &[("symbol", self.symbol.as_str())],
                                    1,
                                );
                            }
                            *last = new_high;
                        }
                        Err(e) => {
                            self.poll_errors.fetch_add(1, Ordering::Relaxed);
                            self.metrics.inc("rustrade_candle_poll_errors_total");
                            tracing::warn!(
                                service = %self.name,
                                error = %e,
                                "candle poll failed"
                            );
                        }
                    }
                }
            }
        }
    }
}