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
//! Trait contracts for exchange integrations.
//!
//! Concrete exchange clients (KuCoin, Binance, …) implement [`ExchangeClient`]
//! so the bot framework can stay exchange-agnostic. A client crate like
//! `exchange-apiws` already provides most of this — these traits are the
//! framework-side view.
use Duration;
use async_trait;
use crateResult;
use crate;
use crate;
/// Optional adapter capabilities, queried via [`ExchangeClient::supports`].
///
/// The framework consults this to degrade gracefully when an adapter
/// doesn't implement a feature an [`Order`] or strategy requests — e.g.
/// rejecting an order with `Order.stop = Some(...)` against an adapter
/// that returns `false` for [`Capability::StopOrders`] rather than
/// silently dropping the attachment.
/// Status of an order as reported by the exchange.
/// What the bot framework needs from an exchange to trade.
///
/// This trait is intentionally narrow — the full surface of a real exchange
/// client (ws token management, stop orders, funding history, account tiers)
/// belongs in the concrete adapter crate, not here. The framework only
/// needs to: place orders, close positions, read balance and position state.
///
/// # Async + object-safe
///
/// `async_trait` is used so `Arc<dyn ExchangeClient>` works — downstream
/// code can swap concrete exchanges at runtime without generics propagating
/// through the whole system.
///
/// # Example
///
/// A stub adapter useful for examples and tests. Real adapters connect
/// to a network and report actual state.
///
/// ```
/// use async_trait::async_trait;
/// use rustrade_core::{Capability, ExchangeClient, Order, Position, Result, Symbol};
///
/// struct StubExchange;
///
/// #[async_trait]
/// impl ExchangeClient for StubExchange {
/// fn name(&self) -> &str { "stub" }
/// async fn place_order(&self, _order: &Order) -> Result<String> {
/// Ok("order-1".into())
/// }
/// async fn cancel_all(&self, _symbol: &Symbol) -> Result<usize> { Ok(0) }
/// async fn close_position(&self, _symbol: &Symbol, _p: &Position) -> Result<String> {
/// Ok("close-1".into())
/// }
/// async fn get_position(&self, _symbol: &Symbol) -> Result<Position> {
/// Ok(Position::FLAT)
/// }
/// async fn get_balance(&self, _currency: &str) -> Result<f64> { Ok(0.0) }
/// fn supports(&self, c: Capability) -> bool {
/// matches!(c, Capability::ReduceOnly)
/// }
/// }
/// ```
/// A source of live market data (WebSocket feed, backtest replay, simulator).
///
/// Implementors push events into the bot via the
/// [`MarketDataBus`](crate::bus::MarketDataBus) that the supervisor creates.
/// `MarketSource` is intended to be wrapped by a `TradingService` in
/// `rustrade-supervisor` so it inherits lifecycle management and
/// auto-restart; this trait just documents the contract on the data side.
///
/// # Example
///
/// A loopback source that publishes a single tick and exits. Production
/// sources hold the `MarketDataBus` sender they were constructed with
/// and publish to it from `run`.
///
/// ```
/// use async_trait::async_trait;
/// use rustrade_core::{MarketSource, Result};
///
/// struct OneShotSource {
/// name: String,
/// }
///
/// #[async_trait]
/// impl MarketSource for OneShotSource {
/// fn name(&self) -> &str { &self.name }
/// async fn run(&self) -> Result<()> {
/// // In a real impl: connect to feed, loop publishing events to
/// // the bus, return Ok(()) on clean shutdown.
/// Ok(())
/// }
/// fn is_live(&self) -> bool { false }
/// }
/// ```
///
/// # Cancellation contract
///
/// `run` does **not** take a `CancellationToken` directly. Cancellation is
/// expected to flow through the wrapping `TradingService` — when the
/// supervisor cancels that service's token, it drops the
/// `MarketSource::run` future at its next `.await`.
///
/// Implementors must therefore be **drop-safe**: any open resources
/// (WebSocket connections, HTTP sessions, file handles) must release
/// cleanly when their containing future is dropped. In practice this
/// means:
///
/// - Use `tokio::select!` against external events only inside your own
/// loop, not against an externally-owned cancel signal here.
/// - Don't hold a `MutexGuard` across an `.await` that could be dropped
/// mid-flight — dropping a guard is fine, but holding one while the
/// future is destructured can deadlock the lock.
/// - If you need explicit teardown, perform it in a `Drop` impl on the
/// implementing type rather than at the end of `run`.
/// Received fill events from the exchange's private feed.
///
/// Adapters implement this to route fills into the bot. Most exchanges push
/// both order updates and fill events; this trait abstracts the "fill" part.
///
/// # Example
///
/// An in-memory fill source backed by a [`tokio::sync::mpsc`] channel —
/// useful for tests and replay drivers.
///
/// ```
/// use async_trait::async_trait;
/// use rustrade_core::{Fill, FillSource};
/// use tokio::sync::mpsc;
/// use tokio::sync::Mutex;
///
/// struct ChannelFills {
/// rx: Mutex<mpsc::UnboundedReceiver<Fill>>,
/// }
///
/// #[async_trait]
/// impl FillSource for ChannelFills {
/// async fn next_fill(&self) -> Option<Fill> {
/// self.rx.lock().await.recv().await
/// }
/// }
/// ```
/// Received order-book / market-data events from the exchange's public feed.
///
/// # Example
///
/// A simple channel-backed event source — typical for tests that push
/// scripted ticks/candles into the bot.
///
/// ```
/// use async_trait::async_trait;
/// use rustrade_core::{EventSource, MarketDataEvent};
/// use tokio::sync::mpsc;
/// use tokio::sync::Mutex;
///
/// struct ChannelEvents {
/// rx: Mutex<mpsc::UnboundedReceiver<MarketDataEvent>>,
/// }
///
/// #[async_trait]
/// impl EventSource for ChannelEvents {
/// async fn next_event(&self) -> Option<MarketDataEvent> {
/// self.rx.lock().await.recv().await
/// }
/// }
/// ```
/// Periodic candle source — separate from [`MarketSource`] because
/// candle polling has a fundamentally different shape (pull, paced)
/// than streaming events (push, unbounded).
///
/// Spot-only adapters don't need to implement this; the framework will
/// only spawn a candle poller when one is wired via
/// `Bot::with_candle_poller`. Futures adapters with native candle
/// endpoints (KuCoin, Binance, Bybit, …) implement it directly.
///
/// # Example
///
/// A fixed-series source useful for backtests and replays. The
/// framework's poller will dedupe by `Candle::time`, so repeated polls
/// returning the same head are safe.
///
/// ```
/// use std::time::Duration;
/// use async_trait::async_trait;
/// use rustrade_core::{Candle, CandleSource, Result, Symbol};
///
/// struct FixedCandles {
/// candles: Vec<Candle>,
/// }
///
/// #[async_trait]
/// impl CandleSource for FixedCandles {
/// fn name(&self) -> &str { "fixed" }
/// async fn poll(
/// &self,
/// _symbol: &Symbol,
/// _interval: Duration,
/// limit: usize,
/// ) -> Result<Vec<Candle>> {
/// Ok(self.candles.iter().rev().take(limit).rev().copied().collect())
/// }
/// }
/// ```