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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! Trade syncer: syncs fills to upstream API for PnL tracking.
//!
//! This module provides async HTTP syncing of fills to an external API
//! (like the AlgoBot API) for centralized PnL calculation and persistence.

use bot_core::{now_ms, Fill, InstrumentId};
use reqwest::Client;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::time::Duration;

use crate::performance_metrics::PerformanceMetricsSnapshot;
// Re-use SyncError from account_syncer to avoid duplication
pub use crate::account_syncer::SyncError;

/// Configuration for trade syncing
#[derive(Debug, Clone)]
pub struct TradeSyncerConfig {
    /// Bot ID for upstream API
    pub bot_id: String,
    /// Upstream API base URL (e.g., `<https://api.example.com/bot-api>`)
    pub upstream_url: String,
    /// Sync interval in milliseconds (default: 10000)
    pub sync_interval_ms: u64,
    /// HTTP timeout in seconds
    pub timeout_secs: u64,
    /// Maximum retries for failed syncs
    pub max_retries: u32,
    /// Initial retry delay in milliseconds
    pub retry_delay_ms: u64,
    /// Instruments to filter fills (only sync fills for these instruments)
    /// Empty = sync all fills (no filter)
    pub instruments: Vec<InstrumentId>,
    /// Optional strategy type hint for upstream routing/aggregation.
    pub strategy_type: Option<String>,
    /// Optional shared secret for upstream sync auth.
    pub sync_secret: Option<String>,
}

impl Default for TradeSyncerConfig {
    fn default() -> Self {
        Self {
            bot_id: String::new(),
            upstream_url: String::new(),
            sync_interval_ms: 10_000,
            timeout_secs: 10,
            max_retries: 3,
            retry_delay_ms: 1000,
            instruments: Vec::new(),
            strategy_type: None,
            sync_secret: None,
        }
    }
}

/// Trade format for upstream API (matches botRoutes.py Trade schema)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpstreamTrade {
    /// Stable trade ID.
    pub trade_id: String,
    /// Client order ID.
    pub client_order_id: String,
    /// Venue/exchange order ID.
    pub venue_order_id: String,
    /// Instrument ID.
    pub instrument_id: String,
    /// Fill side.
    pub side: String,
    /// Order type label.
    pub order_type: String,
    /// Filled quantity string.
    pub qty: String,
    /// Fill price string.
    pub price: String,
    /// Quote notional string.
    pub quote_notional: String,
    /// Fee amount string.
    pub fee: String,
    /// Fee currency.
    pub fee_currency: String,
    /// Liquidity role.
    pub liquidity: String,
    /// Event timestamp in milliseconds.
    pub ts_event: i64,
}

/// Request payload for sync API
#[derive(Debug, Clone, Serialize)]
pub struct SyncRequest {
    /// Trades to sync.
    pub trades: Vec<UpstreamTrade>,
    /// Request timestamp in milliseconds.
    pub ts: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Current price, if known.
    pub current_price: Option<String>,
    /// Whether this request marks bot shutdown.
    pub stop_bot: bool,
    /// Shutdown reason when `stop_bot` is true.
    pub stop_reason: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional metrics or strategy metadata.
    pub metadata: Option<serde_json::Value>,
}

/// Response from sync API
#[derive(Debug, Clone, Deserialize)]
pub struct SyncResponse {
    /// Last synced trade info.
    pub synced: SyncedInfo,
    #[serde(default)]
    /// Upstream-calculated PnL.
    pub pnl: f64,
}

/// Info about last synced trade
#[derive(Debug, Clone, Deserialize)]
pub struct SyncedInfo {
    /// Last synced trade ID.
    pub trade_id: String,
    /// Last synced timestamp.
    pub ts: i64,
}

/// Response from sync API
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// Whether the sync succeeded.
    pub success: bool,
    /// Upstream-calculated PnL, if returned.
    pub pnl: Option<f64>,
    /// Last synced trade ID.
    pub last_synced_trade_id: Option<String>,
    /// Number of trades synced.
    pub trades_synced: usize,
}

/// Trade syncer - handles syncing fills to upstream API
pub struct TradeSyncer {
    config: TradeSyncerConfig,
    client: Client,
    /// Trade IDs that have been successfully synced
    synced_trade_ids: HashSet<String>,
    /// Accumulated fills waiting to be synced
    pending_fills: Vec<Fill>,
    /// Last successful sync timestamp
    last_sync_ts: i64,
    /// Last sync PnL
    last_pnl: Option<f64>,
    /// Timestamp when the syncer was created (only sync fills after this time)
    start_timestamp: i64,
    /// Latest performance metrics to include in upstream metadata
    metrics_snapshot: Option<PerformanceMetricsSnapshot>,
}

impl TradeSyncer {
    /// Create a new trade syncer with the given configuration
    pub fn new(config: TradeSyncerConfig) -> Result<Self, SyncError> {
        if config.bot_id.is_empty() {
            return Err(SyncError::Config("bot_id is required".to_string()));
        }
        if config.upstream_url.is_empty() {
            return Err(SyncError::Config("upstream_url is required".to_string()));
        }

        let client = Client::builder()
            .timeout(Duration::from_secs(config.timeout_secs))
            .build()
            .map_err(|e| SyncError::Http(e.to_string()))?;

        let start_timestamp = now_ms();
        tracing::info!(
            "[TradeSyncer] Initialized with start_timestamp={} - only fills after this time will be synced",
            start_timestamp
        );

        Ok(Self {
            config,
            client,
            synced_trade_ids: HashSet::new(),
            pending_fills: Vec::new(),
            last_sync_ts: 0,
            last_pnl: None,
            start_timestamp,
            metrics_snapshot: None,
        })
    }

    /// Add a fill to the pending queue (will be synced on next sync call)
    pub fn add_fill(&mut self, fill: Fill) {
        // Skip fills that happened before the syncer started (historical fills)
        if fill.ts < self.start_timestamp {
            tracing::debug!(
                "Skipping historical fill: {} (ts={} < start_ts={})",
                fill.trade_id,
                fill.ts,
                self.start_timestamp
            );
            return;
        }

        // Skip if already synced
        if self.synced_trade_ids.contains(&fill.trade_id.0) {
            tracing::debug!("Skipping already-synced fill: {}", fill.trade_id);
            return;
        }

        // Filter by instruments if configured
        if !self.config.instruments.is_empty()
            && !self.config.instruments.contains(&fill.instrument)
        {
            tracing::debug!(
                "Skipping fill for untracked instrument: {} (tracking: {:?})",
                fill.instrument,
                self.config.instruments
            );
            return;
        }

        tracing::info!(
            "[TradeSyncer] Adding fill to pending queue: {} (ts={})",
            fill.trade_id,
            fill.ts
        );
        self.pending_fills.push(fill);
    }

    /// Check if it's time to sync (based on interval)
    pub fn should_sync(&self) -> bool {
        let now = now_ms();
        now - self.last_sync_ts >= self.config.sync_interval_ms as i64
    }

    /// Get the last known PnL
    pub fn last_pnl(&self) -> Option<f64> {
        self.last_pnl
    }

    /// Get the number of pending fills
    pub fn pending_count(&self) -> usize {
        self.pending_fills.len()
    }

    /// Set the latest performance metrics snapshot for sync metadata.
    pub fn set_metrics_snapshot(&mut self, snapshot: Option<PerformanceMetricsSnapshot>) {
        self.metrics_snapshot = snapshot;
    }

    /// Sync pending fills to upstream API
    ///
    /// Returns the PnL from the upstream API on success
    pub async fn sync(
        &mut self,
        current_price: Option<Decimal>,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<SyncResult, SyncError> {
        let now = now_ms();

        // Convert pending fills to upstream format
        let trades: Vec<UpstreamTrade> = self
            .pending_fills
            .iter()
            .filter(|f| !self.synced_trade_ids.contains(&f.trade_id.0))
            .map(|f| self.fill_to_trade(f))
            .collect();

        let trades_count = trades.len();

        tracing::info!(
            "[TradeSyncer] Syncing {} trades to upstream (pending={}, synced={})",
            trades_count,
            self.pending_fills.len(),
            self.synced_trade_ids.len()
        );

        let request = SyncRequest {
            trades,
            ts: now / 1000, // seconds
            current_price: current_price.map(|p| p.to_string()),
            stop_bot,
            stop_reason: stop_reason.to_string(),
            metadata: self.metadata_payload(),
        };

        // Execute with retry
        let response = self.execute_with_retry(&request).await?;

        // Mark all trades as synced
        for fill in &self.pending_fills {
            self.synced_trade_ids.insert(fill.trade_id.0.clone());
        }

        // Clear pending fills
        self.pending_fills.clear();

        // Update state
        self.last_sync_ts = now;
        self.last_pnl = Some(response.pnl);

        tracing::info!(
            "[TradeSyncer] Sync successful: pnl={:.4}, last_trade_id={}",
            response.pnl,
            response.synced.trade_id
        );

        Ok(SyncResult {
            success: true,
            pnl: Some(response.pnl),
            last_synced_trade_id: Some(response.synced.trade_id),
            trades_synced: trades_count,
        })
    }

    fn metadata_payload(&self) -> Option<serde_json::Value> {
        let mut metadata = serde_json::Map::new();

        if let Some(strategy_type) = self
            .config
            .strategy_type
            .as_deref()
            .filter(|s| !s.is_empty())
        {
            metadata.insert(
                "strategy_type".to_string(),
                serde_json::json!(strategy_type),
            );
        }

        if let Some(snapshot) = self.metrics_snapshot.as_ref() {
            metadata.insert(
                "performance_metrics".to_string(),
                serde_json::json!(snapshot),
            );
        }

        (!metadata.is_empty()).then(|| serde_json::Value::Object(metadata))
    }

    /// Execute sync request with retry logic
    async fn execute_with_retry(&self, request: &SyncRequest) -> Result<SyncResponse, SyncError> {
        let url = format!(
            "{}/sync/{}",
            self.config.upstream_url.trim_end_matches('/'),
            self.config.bot_id
        );

        let mut last_error: Option<SyncError> = None;
        let mut delay_ms = self.config.retry_delay_ms;

        for attempt in 1..=self.config.max_retries {
            tracing::debug!(
                "[TradeSyncer] Sync attempt {}/{} to {}",
                attempt,
                self.config.max_retries,
                url
            );

            match self.execute_request(&url, request).await {
                Ok(response) => return Ok(response),
                Err(e) => {
                    tracing::warn!(
                        "[TradeSyncer] Sync attempt {}/{} failed: {}",
                        attempt,
                        self.config.max_retries,
                        e
                    );
                    last_error = Some(e);

                    if attempt < self.config.max_retries {
                        tracing::debug!("[TradeSyncer] Retrying in {}ms...", delay_ms);
                        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                        delay_ms *= 2; // exponential backoff
                    }
                }
            }
        }

        Err(last_error.unwrap_or(SyncError::MaxRetries))
    }

    /// Execute a single sync request
    async fn execute_request(
        &self,
        url: &str,
        request: &SyncRequest,
    ) -> Result<SyncResponse, SyncError> {
        let mut request_builder = self
            .client
            .post(url)
            .header("Content-Type", "application/json");
        if let Some(secret) = self.config.sync_secret.as_deref().filter(|s| !s.is_empty()) {
            request_builder = request_builder.header("x-bot-sync-secret", secret);
        }
        let response = request_builder.json(request).send().await?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(SyncError::Api {
                status: status.as_u16(),
                body,
            });
        }

        let sync_response: SyncResponse = response
            .json()
            .await
            .map_err(|e| SyncError::Parse(e.to_string()))?;

        Ok(sync_response)
    }

    /// Convert a Fill to upstream trade format
    fn fill_to_trade(&self, fill: &Fill) -> UpstreamTrade {
        // Determine side string
        let side = format!("{}", fill.side);

        // Calculate quote notional
        let quote_notional = fill.price.0 * fill.qty.0;

        UpstreamTrade {
            trade_id: fill.trade_id.0.clone(),
            client_order_id: fill
                .client_id
                .as_ref()
                .map(|c| c.0.clone())
                .unwrap_or_default(),
            venue_order_id: fill
                .exchange_order_id
                .as_ref()
                .map(|e| e.0.clone())
                .unwrap_or_default(),
            instrument_id: fill.instrument.0.clone(),
            side,
            order_type: "LIMIT".to_string(),
            qty: fill.qty.0.to_string(),
            price: fill.price.0.to_string(),
            quote_notional: quote_notional.to_string(),
            fee: fill.fee.amount.to_string(),
            fee_currency: fill.fee.asset.0.clone(),
            liquidity: "UNKNOWN".to_string(), // Fill doesn't have maker/taker info
            ts_event: fill.ts,
        }
    }

    /// Perform final sync on shutdown (with stop_bot=true)
    pub async fn shutdown_sync(
        &mut self,
        current_price: Option<Decimal>,
        stop_reason: &str,
    ) -> Result<SyncResult, SyncError> {
        tracing::info!(
            "[TradeSyncer] Performing shutdown sync with reason: {}, price: {:?}",
            stop_reason,
            current_price
        );
        self.sync(current_price, true, stop_reason).await
    }
}

// Implement TradeSync trait for drop-in substitution with MockTradeSyncer
#[async_trait::async_trait]
impl crate::sync_traits::TradeSync for TradeSyncer {
    fn add_fill(&mut self, fill: Fill) {
        TradeSyncer::add_fill(self, fill)
    }

    fn should_sync(&self) -> bool {
        TradeSyncer::should_sync(self)
    }

    fn pending_count(&self) -> usize {
        TradeSyncer::pending_count(self)
    }

    fn last_pnl(&self) -> Option<f64> {
        TradeSyncer::last_pnl(self)
    }

    fn set_metrics_snapshot(
        &mut self,
        snapshot: Option<crate::performance_metrics::PerformanceMetricsSnapshot>,
    ) {
        TradeSyncer::set_metrics_snapshot(self, snapshot)
    }

    async fn sync(
        &mut self,
        current_price: Option<Decimal>,
        stop_bot: bool,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::TradeSyncResult, SyncError> {
        let result = TradeSyncer::sync(self, 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<Decimal>,
        stop_reason: &str,
    ) -> Result<crate::sync_traits::TradeSyncResult, SyncError> {
        let result = TradeSyncer::shutdown_sync(self, current_price, stop_reason).await?;
        Ok(crate::sync_traits::TradeSyncResult {
            success: result.success,
            pnl: result.pnl,
        })
    }
}

#[cfg(test)]

mod tests {
    use super::*;
    use crate::performance_metrics::{
        PerformanceBenchmark, PerformanceMetrics, PerformanceMetricsSnapshot,
    };
    use bot_core::{AssetId, Fee, OrderSide, Price, Qty, TradeId};

    fn make_metrics_snapshot() -> PerformanceMetricsSnapshot {
        PerformanceMetricsSnapshot {
            schema_version: 1,
            mode: "backtest".to_string(),
            scope: "backtest_window".to_string(),
            run_started_at_ms: None,
            metrics: PerformanceMetrics {
                period_return_pct: Some(1.0),
                apr_pct: Some(365.0),
                sharpe: Some(1.5),
                max_drawdown_pct: Some(0.5),
                max_drawdown_usdc: "5".to_string(),
                win_rate_pct: Some(100.0),
                closed_trade_count: 1,
                winning_trade_count: 1,
                losing_trade_count: 0,
                fill_count: 2,
                total_fees: "0.2".to_string(),
                total_volume: "200".to_string(),
                net_pnl: "10".to_string(),
                fee_drag_pct: Some(0.02),
            },
            benchmark: PerformanceBenchmark {
                start_ts_ms: Some(1),
                end_ts_ms: Some(2),
                duration_ms: Some(1),
                quote_count: 2,
                starting_balance_usdc: Some("1000".to_string()),
                ending_balance_usdc: Some("1010".to_string()),
                instrument: Some("BTC-PERP".to_string()),
            },
            latest_equity: None,
        }
    }

    fn make_test_fill(trade_id: &str, instrument: &str) -> Fill {
        // Use a timestamp in the future to ensure it passes the start_timestamp check
        Fill {
            trade_id: TradeId::new(trade_id),
            client_id: None,
            exchange_order_id: None,
            instrument: InstrumentId::new(instrument),
            side: OrderSide::Buy,
            price: Price::new(Decimal::new(100, 0)),
            qty: Qty::new(Decimal::new(1, 0)),
            fee: Fee::new(Decimal::new(1, 2), AssetId::new("USDC")),
            ts: now_ms() + 1000, // Future timestamp to pass start_timestamp filter
        }
    }

    fn make_test_fill_with_ts(trade_id: &str, instrument: &str, ts: i64) -> Fill {
        Fill {
            trade_id: TradeId::new(trade_id),
            client_id: None,
            exchange_order_id: None,
            instrument: InstrumentId::new(instrument),
            side: OrderSide::Buy,
            price: Price::new(Decimal::new(100, 0)),
            qty: Qty::new(Decimal::new(1, 0)),
            fee: Fee::new(Decimal::new(1, 2), AssetId::new("USDC")),
            ts,
        }
    }

    #[test]
    fn test_config_validation() {
        // Empty bot_id should fail
        let config = TradeSyncerConfig {
            bot_id: String::new(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        assert!(TradeSyncer::new(config).is_err());

        // Empty upstream_url should fail
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: String::new(),
            ..Default::default()
        };
        assert!(TradeSyncer::new(config).is_err());

        // Valid config should succeed
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        assert!(TradeSyncer::new(config).is_ok());
    }

    #[test]
    fn test_add_fill_deduplication() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        let mut syncer = TradeSyncer::new(config).unwrap();

        // Add same fill twice (with future timestamp to pass start_timestamp filter)
        let fill = make_test_fill("trade-1", "BTC-PERP");
        syncer.add_fill(fill.clone());
        syncer.add_fill(fill);

        // Should have both since same trade_id isn't marked as synced yet
        assert_eq!(syncer.pending_count(), 2);

        // Mark as synced
        syncer.synced_trade_ids.insert("trade-1".to_string());

        // Clear pending
        syncer.pending_fills.clear();

        // Try to add again - should be skipped (already synced)
        let fill = make_test_fill("trade-1", "BTC-PERP");
        syncer.add_fill(fill);
        assert_eq!(syncer.pending_count(), 0);
    }

    #[test]
    fn test_start_timestamp_filter() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        let mut syncer = TradeSyncer::new(config).unwrap();

        // Add fill with old timestamp (before syncer started) - should be filtered
        let old_fill =
            make_test_fill_with_ts("trade-old", "BTC-PERP", syncer.start_timestamp - 1000);
        syncer.add_fill(old_fill);
        assert_eq!(
            syncer.pending_count(),
            0,
            "Historical fill should be filtered"
        );

        // Add fill with new timestamp (after syncer started) - should be accepted
        let new_fill =
            make_test_fill_with_ts("trade-new", "BTC-PERP", syncer.start_timestamp + 1000);
        syncer.add_fill(new_fill);
        assert_eq!(syncer.pending_count(), 1, "New fill should be accepted");
    }

    #[test]
    fn test_instrument_filter() {
        // Single instrument filter
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            instruments: vec![InstrumentId::new("BTC-PERP")],
            ..Default::default()
        };
        let mut syncer = TradeSyncer::new(config).unwrap();

        // Add fill for correct instrument
        syncer.add_fill(make_test_fill("trade-1", "BTC-PERP"));
        assert_eq!(syncer.pending_count(), 1);

        // Add fill for different instrument - should be filtered
        syncer.add_fill(make_test_fill("trade-2", "ETH-PERP"));
        assert_eq!(syncer.pending_count(), 1); // Still 1
    }

    #[test]
    fn test_multi_instrument_filter() {
        // Multi-instrument filter (arb: spot + perp)
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            instruments: vec![
                InstrumentId::new("UBTC-SPOT"),
                InstrumentId::new("BTC-PERP"),
            ],
            ..Default::default()
        };
        let mut syncer = TradeSyncer::new(config).unwrap();

        // Both instruments should pass
        syncer.add_fill(make_test_fill("trade-1", "UBTC-SPOT"));
        syncer.add_fill(make_test_fill("trade-2", "BTC-PERP"));
        assert_eq!(syncer.pending_count(), 2);

        // Unrelated instrument should be filtered
        syncer.add_fill(make_test_fill("trade-3", "ETH-PERP"));
        assert_eq!(syncer.pending_count(), 2); // Still 2
    }

    #[test]
    fn test_fill_to_trade_conversion() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        let syncer = TradeSyncer::new(config).unwrap();

        let fill = Fill {
            trade_id: TradeId::new("trade-123"),
            client_id: Some(bot_core::ClientOrderId::new("client-456")),
            exchange_order_id: Some(bot_core::ExchangeOrderId::new("exchange-789")),
            instrument: InstrumentId::new("BTC-PERP"),
            side: OrderSide::Sell,
            price: Price::new(Decimal::new(50000, 0)),
            qty: Qty::new(Decimal::new(5, 1)), // 0.5
            fee: Fee::new(Decimal::new(25, 2), AssetId::new("USDC")), // 0.25
            ts: 1700000000000,
        };

        let trade = syncer.fill_to_trade(&fill);

        assert_eq!(trade.trade_id, "trade-123");
        assert_eq!(trade.client_order_id, "client-456");
        assert_eq!(trade.venue_order_id, "exchange-789");
        assert_eq!(trade.instrument_id, "BTC-PERP");
        assert_eq!(trade.side, "SELL");
        assert_eq!(trade.price, "50000");
        assert_eq!(trade.qty, "0.5");
        // quote_notional = 50000 * 0.5 = 25000 (may have trailing decimal depending on Decimal impl)
        assert!(
            trade.quote_notional.starts_with("25000"),
            "Expected quote_notional to start with 25000, got: {}",
            trade.quote_notional
        );
        assert_eq!(trade.fee, "0.25");
        assert_eq!(trade.fee_currency, "USDC");
        assert_eq!(trade.ts_event, 1700000000000);
    }

    #[test]
    fn test_metadata_payload_includes_performance_metrics() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            strategy_type: Some("orchestrator".to_string()),
            ..Default::default()
        };
        let mut syncer = TradeSyncer::new(config).unwrap();
        syncer.set_metrics_snapshot(Some(make_metrics_snapshot()));

        let metadata = syncer.metadata_payload().expect("metadata");
        assert_eq!(metadata["strategy_type"], serde_json::json!("orchestrator"));
        assert_eq!(
            metadata["performance_metrics"]["metrics"]["net_pnl"],
            serde_json::json!("10")
        );
        assert_eq!(
            metadata["performance_metrics"]["mode"],
            serde_json::json!("backtest")
        );
    }

    #[test]
    fn test_metadata_payload_includes_strategy_type_without_metrics() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            strategy_type: Some("grid".to_string()),
            ..Default::default()
        };
        let syncer = TradeSyncer::new(config).unwrap();

        let metadata = syncer.metadata_payload().expect("metadata");
        assert_eq!(metadata["strategy_type"], serde_json::json!("grid"));
        assert!(metadata.get("performance_metrics").is_none());
    }

    #[test]
    fn test_metadata_payload_omitted_without_strategy_type_or_metrics() {
        let config = TradeSyncerConfig {
            bot_id: "test-bot".to_string(),
            upstream_url: "http://test.com".to_string(),
            ..Default::default()
        };
        let syncer = TradeSyncer::new(config).unwrap();

        assert!(syncer.metadata_payload().is_none());
    }
}