bot-engine 0.1.0

Trading bot engine: order manager, inventory, event routing
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
//! Mock Syncers for testing backend integration without real API calls.

use async_lock::RwLock;
use bot_core::AccountState;
use rust_decimal::Decimal;
use std::sync::Arc;
use std::time::Duration;

// Re-export error types
pub use crate::account_syncer::{SyncError, SyncResult};
pub use bot_core::Fill;

// === MockAccountSyncer (for Arbitrage/Snapshot strategies) ===

/// Recorded account-sync call for assertions.
#[derive(Debug, Clone)]
pub struct AccountSyncCall {
    /// Account value sent to the syncer.
    pub account_value: Decimal,
    /// Unrealized PnL sent to the syncer.
    pub unrealized_pnl: Decimal,
    /// Position payload sent to the syncer.
    pub positions: Vec<PositionInfo>,
    /// Sync timestamp in seconds.
    pub ts: i64,
    /// Whether this was a shutdown sync.
    pub stop_bot: bool,
    /// Stop reason for shutdown syncs.
    pub stop_reason: String,
}

/// Position payload recorded by the account mock.
#[derive(Debug, Clone)]
pub struct PositionInfo {
    /// Instrument ID string.
    pub instrument_id: String,
    /// Position quantity string.
    pub qty: String,
    /// Entry price string.
    pub entry_px: String,
    /// Unrealized PnL string.
    pub unrealized_pnl: String,
}

struct MockAccountSyncerState {
    sync_calls: Vec<AccountSyncCall>,
    should_fail: bool,
    simulated_pnl: f64,
    network_delay_ms: u64,
}

/// Mock account syncer for snapshot-account strategies.
pub struct MockAccountSyncer {
    inner: Arc<RwLock<MockAccountSyncerState>>,
}

impl MockAccountSyncer {
    /// Create a mock account syncer.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(MockAccountSyncerState {
                sync_calls: Vec::new(),
                should_fail: false,
                simulated_pnl: 0.0,
                network_delay_ms: 0,
            })),
        }
    }

    // === KNOBS ===

    /// Configure whether sync calls should fail.
    pub async fn set_should_fail(&self, should_fail: bool) {
        self.inner.write().await.should_fail = should_fail;
    }

    /// Set the PnL returned by successful sync calls.
    pub async fn set_simulated_pnl(&self, pnl: f64) {
        self.inner.write().await.simulated_pnl = pnl;
    }

    /// Set simulated network delay in milliseconds.
    pub async fn set_network_delay(&self, ms: u64) {
        self.inner.write().await.network_delay_ms = ms;
    }

    // === VERIFICATION ===

    /// Return all recorded account sync calls.
    pub async fn sync_calls(&self) -> Vec<AccountSyncCall> {
        self.inner.read().await.sync_calls.clone()
    }

    /// Return the latest recorded account sync call.
    pub async fn last_sync(&self) -> Option<AccountSyncCall> {
        self.inner.read().await.sync_calls.last().cloned()
    }

    /// Return recorded shutdown sync calls.
    pub async fn shutdown_syncs(&self) -> Vec<AccountSyncCall> {
        self.inner
            .read()
            .await
            .sync_calls
            .iter()
            .filter(|c| c.stop_bot)
            .cloned()
            .collect()
    }

    /// Assert exactly one shutdown sync was recorded.
    pub async fn assert_shutdown_sync_sent(&self) {
        let shutdowns = self.shutdown_syncs().await;
        assert!(!shutdowns.is_empty(), "No shutdown sync was sent");
        assert_eq!(shutdowns.len(), 1, "Multiple shutdown syncs sent");
    }

    /// Assert at least `min_count` non-shutdown syncs were recorded.
    pub async fn assert_periodic_syncs(&self, min_count: usize) {
        let state = self.inner.read().await;
        let active_syncs: Vec<_> = state.sync_calls.iter().filter(|c| !c.stop_bot).collect();

        assert!(
            active_syncs.len() >= min_count,
            "Expected at least {} periodic syncs, got {}",
            min_count,
            active_syncs.len()
        );
    }

    // === SYNCER IMPLEMENTATION ===

    /// Record an account sync call and return the configured mock result.
    pub async fn sync(
        &mut self,
        account_state: &AccountState,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<SyncResult, SyncError> {
        let mut state = self.inner.write().await;

        // Simulate network delay
        if state.network_delay_ms > 0 {
            let delay_ms = state.network_delay_ms;
            drop(state); // Release lock during sleep
            tokio::time::sleep(Duration::from_millis(delay_ms)).await;
            state = self.inner.write().await;
        }

        // Check failure mode
        if state.should_fail {
            return Err(SyncError::Network("Mock network failure".into()));
        }

        // Record the sync call
        let positions: Vec<PositionInfo> = account_state
            .positions
            .iter()
            .map(|p| PositionInfo {
                instrument_id: p.instrument.to_string(),
                qty: p.qty.to_string(),
                entry_px: p
                    .avg_entry_px
                    .map(|px| px.0.to_string())
                    .unwrap_or_else(|| "0".into()),
                unrealized_pnl: p
                    .unrealized_pnl
                    .map(|pnl| pnl.to_string())
                    .unwrap_or_else(|| "0".into()),
            })
            .collect();

        state.sync_calls.push(AccountSyncCall {
            account_value: account_state.account_value.unwrap_or_default(),
            unrealized_pnl: account_state.unrealized_pnl.unwrap_or_default(),
            positions,
            ts: bot_core::now_ms() / 1000,
            stop_bot,
            stop_reason: stop_reason.to_string(),
        });

        Ok(SyncResult {
            success: true,
            pnl: Some(state.simulated_pnl),
        })
    }

    /// Record a shutdown account sync call.
    pub async fn shutdown_sync(
        &mut self,
        account_state: &AccountState,
        stop_reason: &str,
    ) -> Result<SyncResult, SyncError> {
        self.sync(account_state, true, stop_reason).await
    }
}

// Implement AccountSync trait for drop-in substitution
#[async_trait::async_trait]
impl crate::sync_traits::AccountSync for MockAccountSyncer {
    fn should_sync(&self) -> bool {
        true // Mock always returns true, tests control when to call sync
    }

    fn last_pnl(&self) -> Option<f64> {
        // Return from inner state synchronously would require blocking
        // For mock, we just return None - tests should use sync_calls() to verify
        None
    }

    async fn sync(
        &mut self,
        account_state: &AccountState,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::AccountSyncResult, SyncError> {
        let result = MockAccountSyncer::sync(self, account_state, stop_bot, stop_reason).await?;
        Ok(crate::sync_traits::AccountSyncResult {
            success: result.success,
            pnl: result.pnl,
        })
    }

    async fn shutdown_sync(
        &mut self,
        account_state: &AccountState,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::AccountSyncResult, SyncError> {
        let result = MockAccountSyncer::shutdown_sync(self, account_state, stop_reason).await?;
        Ok(crate::sync_traits::AccountSyncResult {
            success: result.success,
            pnl: result.pnl,
        })
    }
}

impl Default for MockAccountSyncer {
    fn default() -> Self {
        Self::new()
    }
}

// === MockTradeSyncer (for Grid/MM strategies) ===

/// Recorded trade-sync call for assertions.
#[derive(Debug, Clone)]
pub struct TradeSyncCall {
    /// Fills sent to the syncer.
    pub fills: Vec<Fill>,
    /// Current market price sent with the sync.
    pub current_price: Option<Decimal>,
    /// Whether this was a shutdown sync.
    pub stop_bot: bool,
    /// Stop reason for shutdown syncs.
    pub stop_reason: String,
    /// Sync timestamp in milliseconds.
    pub timestamp: i64,
}

struct MockTradeSyncerState {
    sync_calls: Vec<TradeSyncCall>,
    should_fail: bool,
    simulated_pnl: f64,
}

/// Mock trade syncer for fill-based strategies.
pub struct MockTradeSyncer {
    inner: Arc<RwLock<MockTradeSyncerState>>,
}

impl MockTradeSyncer {
    /// Create a mock trade syncer.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(MockTradeSyncerState {
                sync_calls: Vec::new(),
                should_fail: false,
                simulated_pnl: 0.0,
            })),
        }
    }

    // === KNOBS ===

    /// Configure whether sync calls should fail.
    pub async fn set_should_fail(&self, should_fail: bool) {
        self.inner.write().await.should_fail = should_fail;
    }

    /// Set the PnL returned by successful sync calls.
    pub async fn set_simulated_pnl(&self, pnl: f64) {
        self.inner.write().await.simulated_pnl = pnl;
    }

    // === VERIFICATION ===

    /// Return all recorded trade sync calls.
    pub async fn sync_calls(&self) -> Vec<TradeSyncCall> {
        self.inner.read().await.sync_calls.clone()
    }

    /// Count fills across all recorded trade sync calls.
    pub async fn total_fills_synced(&self) -> usize {
        self.inner
            .read()
            .await
            .sync_calls
            .iter()
            .map(|c| c.fills.len())
            .sum()
    }

    /// Assert that the expected number of fills was synced.
    pub async fn assert_all_fills_synced(&self, expected_fills: &[Fill]) {
        let total = self.total_fills_synced().await;
        assert_eq!(
            total,
            expected_fills.len(),
            "Expected {} fills synced, got {}",
            expected_fills.len(),
            total
        );
    }

    // === SYNCER IMPLEMENTATION ===

    /// Record a trade sync call and return the configured mock result.
    pub async fn sync(
        &mut self,
        fills: Vec<Fill>,
        current_price: Option<Decimal>,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<SyncResult, SyncError> {
        let mut state = self.inner.write().await;

        if state.should_fail {
            return Err(SyncError::Network("Mock sync failure".into()));
        }

        state.sync_calls.push(TradeSyncCall {
            fills,
            current_price,
            stop_bot,
            stop_reason: stop_reason.to_string(),
            timestamp: bot_core::now_ms(),
        });

        Ok(SyncResult {
            success: true,
            pnl: Some(state.simulated_pnl),
        })
    }
}

// Implement TradeSync trait for drop-in substitution
#[async_trait::async_trait]
impl crate::sync_traits::TradeSync for MockTradeSyncer {
    fn add_fill(&mut self, _fill: Fill) {
        // For MockTradeSyncer, fills are passed directly to sync()
        // This is a no-op, tests use sync() directly with fills
    }

    fn should_sync(&self) -> bool {
        true // Mock always returns true
    }

    fn pending_count(&self) -> usize {
        0 // Mock doesn't accumulate, passes fills directly to sync
    }

    fn last_pnl(&self) -> Option<f64> {
        None // Tests use sync_calls() to verify
    }

    async fn sync(
        &mut self,
        current_price: Option<rust_decimal::Decimal>,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::TradeSyncResult, SyncError> {
        // For trait impl, we sync with empty fills (trait-based usage)
        let result =
            MockTradeSyncer::sync(self, vec![], current_price, stop_bot, stop_reason).await?;
        Ok(crate::sync_traits::TradeSyncResult {
            success: result.success,
            pnl: result.pnl,
        })
    }

    async fn shutdown_sync(
        &mut self,
        current_price: Option<rust_decimal::Decimal>,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::TradeSyncResult, SyncError> {
        let result = MockTradeSyncer::sync(self, vec![], current_price, true, stop_reason).await?;
        Ok(crate::sync_traits::TradeSyncResult {
            success: result.success,
            pnl: result.pnl,
        })
    }
}

impl Default for MockTradeSyncer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bot_core::{InstrumentId, PositionSnapshot};

    #[tokio::test]
    async fn test_account_syncer_recording() {
        let mut syncer = MockAccountSyncer::new();

        let account_state = AccountState {
            positions: vec![PositionSnapshot {
                instrument: InstrumentId::new("ETH-PERP"),
                qty: Decimal::new(-1, 1), // -0.1
                avg_entry_px: Some(bot_core::Price::new(Decimal::new(3000, 0))),
                unrealized_pnl: Some(Decimal::new(10, 0)),
                liquidation_px: None,
            }],
            account_value: Some(Decimal::new(50000, 0)),
            unrealized_pnl: Some(Decimal::new(10, 0)),
        };

        syncer.sync(&account_state, false, "").await.unwrap();

        let calls = syncer.sync_calls().await;
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].stop_bot, false);
        assert_eq!(calls[0].positions.len(), 1);
    }

    #[tokio::test]
    async fn test_shutdown_sync() {
        let mut syncer = MockAccountSyncer::new();

        let account_state = AccountState {
            positions: vec![],
            account_value: Some(Decimal::new(50000, 0)),
            unrealized_pnl: Some(Decimal::ZERO),
        };

        syncer
            .shutdown_sync(&account_state, "shutdown:external")
            .await
            .unwrap();

        syncer.assert_shutdown_sync_sent().await;

        let shutdown = syncer.last_sync().await.unwrap();
        assert_eq!(shutdown.stop_bot, true);
        assert_eq!(shutdown.stop_reason, "shutdown:external");
    }

    #[tokio::test]
    async fn test_syncer_failure_mode() {
        let mut syncer = MockAccountSyncer::new();
        syncer.set_should_fail(true).await;

        let account_state = AccountState {
            positions: vec![],
            account_value: None,
            unrealized_pnl: None,
        };

        let result = syncer.sync(&account_state, false, "").await;
        assert!(result.is_err());

        // No calls recorded on failure
        let calls = syncer.sync_calls().await;
        assert_eq!(calls.len(), 0);
    }
}