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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! Bot configuration types and strategy builder.
//!
//! This module contains:
//! - `BotConfig` — V2 unified config format
//! - Strategy-specific JSON config structs (GridConfigJson, DCAConfigJson, etc.)
//! - `build_strategy()` — construct `Box<dyn Strategy>` from BotConfig
//! - `build_instrument_meta()` — construct InstrumentMeta from Market

use anyhow::{Context, Result};
use bot_core::{
    AssetId, Environment, HyperliquidMarket, InstrumentId, InstrumentMeta, Market, Strategy,
    StrategyId,
};
use bot_orchestrator::{
    BotOrchestrator, GroupRiskConfig, OrchestratorCondition, OrchestratorConditions,
    OrchestratorLeg,
};
use rust_decimal::Decimal;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;

// Strategy imports
use strategy_arbitrage::{ArbitrageConfig, ArbitrageStrategy};
use strategy_dca::{DCAConfig, DCADirection, DCAStrategy};
use strategy_grid::{GridConfig, GridMode, GridStrategy};
use strategy_market_maker::{MarketMaker, MarketMakerConfig, SkewMode};
#[cfg(feature = "strategy-rsi")]
use strategy_rsi::{RsiStrategy, RsiStrategyConfig};
#[cfg(feature = "strategy-tick-trader")]
use strategy_tick_trader::{TickTrader, TickTraderConfig};

// =============================================================================
// Bot Configuration (V2 Format)
// =============================================================================

fn push_price_bound_errors(market: &Market, prices: &[(&str, Decimal)], errors: &mut Vec<String>) {
    let Some((lower, upper)) = market.price_bounds() else {
        return;
    };

    for (label, price) in prices {
        if *price <= lower || *price >= upper {
            errors.push(format!(
                "{} ({}) must be > {} and < {} for {}",
                label,
                price,
                lower,
                upper,
                market.instrument_id()
            ));
        }
    }
}

/// Bot configuration - V2 format with markets array.
/// This is the unified config format for all strategies.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BotConfig {
    /// Environment: "testnet" or "mainnet"
    pub environment: String,

    /// Private key (hex, with or without 0x prefix).
    /// Optional — resolved at runtime from `~/.supurr/credentials.json` if absent.
    #[serde(default)]
    pub private_key: String,

    /// Wallet address.
    /// Optional — resolved at runtime from `~/.supurr/credentials.json` if absent.
    #[serde(default)]
    pub address: String,

    /// Optional vault address
    #[serde(default)]
    pub vault_address: Option<String>,

    /// Optional Hyperliquid base URL override.
    /// When set, both /info and /exchange requests use this gateway.
    #[serde(default)]
    pub base_url_override: Option<String>,

    /// Strategy type: "grid", "mm", "dca", or "arbitrage"
    pub strategy_type: String,

    /// Markets to trade on (V2 format - uses bot_core::Market enum)
    pub markets: Vec<Market>,

    /// Polling delay in milliseconds
    #[serde(default = "default_poll_delay_ms")]
    pub poll_delay_ms: u64,

    // -------------------------------------------------------------------------
    // Strategy-specific configs (only one should be set based on strategy_type)
    // -------------------------------------------------------------------------
    /// Grid strategy configuration
    #[serde(default)]
    pub grid: Option<GridConfigJson>,

    /// Market Maker strategy configuration
    #[serde(default)]
    pub mm: Option<MMConfigJson>,

    /// DCA strategy configuration
    #[serde(default)]
    pub dca: Option<DCAConfigJson>,

    /// Arbitrage strategy configuration
    #[serde(default)]
    pub arbitrage: Option<ArbitrageConfigJson>,

    /// Parent strategy configuration for grouped child strategies.
    #[serde(default)]
    pub orchestrator: Option<OrchestratorConfigJson>,

    // -------------------------------------------------------------------------
    // Common config
    // -------------------------------------------------------------------------
    /// Builder fee configuration
    #[serde(default)]
    pub builder_fee: Option<BuilderFeeConfig>,

    /// Trade sync configuration for upstream API PnL tracking
    #[serde(default)]
    pub sync: Option<SyncConfigJson>,

    /// Simulation configuration (paper/backtest)
    /// Optional — uses sensible defaults if absent.
    #[serde(default)]
    pub simulation: Option<SimulationConfig>,

    // -------------------------------------------------------------------------
    // Custom strategy configs (captured automatically via serde flatten)
    // -------------------------------------------------------------------------
    /// Catch-all for custom strategy configuration sections.
    /// Any JSON key that doesn't match a named field above lands here.
    /// Custom strategies read their config via `config.custom_config("mystrategy")`.
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl BotConfig {
    /// Get the primary market from the markets array
    pub fn primary_market(&self) -> &Market {
        &self.markets[0]
    }

    /// Check if this is a spot market
    pub fn is_spot(&self) -> bool {
        self.primary_market().is_spot()
    }

    /// Check if the primary market settles like spot with no margin/leverage.
    pub fn is_spot_like(&self) -> bool {
        self.primary_market().is_spot_like()
    }

    /// Check if the primary market uses margin/leverage.
    pub fn primary_market_uses_margin(&self) -> bool {
        self.primary_market().uses_margin()
    }

    /// Check if this is a prediction market outcome
    pub fn is_outcome(&self) -> bool {
        self.primary_market().is_outcome()
    }

    /// Get instrument ID from primary market
    pub fn instrument_id(&self) -> InstrumentId {
        self.primary_market().instrument_id()
    }

    /// Get market index from primary market
    pub fn market_index(&self) -> bot_core::MarketIndex {
        self.primary_market().market_index()
    }

    /// Get HIP-3 config if this is a HIP-3 market
    pub fn hip3_config(&self) -> Option<bot_core::market::Hip3MarketConfig> {
        self.primary_market().hip3_config()
    }

    /// Get custom strategy config as typed struct.
    /// Looks up the strategy name in the `extra` catch-all map and deserializes.
    ///
    /// # Example
    /// ```rust,ignore
    /// let my_config: MyConfig = config.custom_config("mystrategy")?;
    /// ```
    pub fn custom_config<T: serde::de::DeserializeOwned>(&self, strategy_name: &str) -> Result<T> {
        let raw = self.extra.get(strategy_name).with_context(|| {
            format!(
                "Custom strategy config missing: add '\"{}\"' section to your JSON config",
                strategy_name
            )
        })?;
        serde_json::from_value(raw.clone())
            .with_context(|| format!("Failed to parse '{}' config section", strategy_name))
    }

    /// Load config from environment variables.
    /// V2 configs require a JSON file, so this returns an error.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_env() -> Result<Self> {
        Err(anyhow::anyhow!(
            "V2 config format requires a JSON file. Use --config <file>"
        ))
    }

    /// Resolve wallet credentials: use fields from config if present,
    /// otherwise fall back to `~/.supurr/credentials.json`.
    ///
    /// Returns `(private_key, address)`.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn resolve_credentials(&self) -> Result<(String, String)> {
        if !self.private_key.is_empty() && !self.address.is_empty() {
            return Ok((self.private_key.clone(), self.address.clone()));
        }

        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .context("Cannot determine home directory")?;
        let creds_path = std::path::PathBuf::from(home).join(".supurr/credentials.json");

        let content = std::fs::read_to_string(&creds_path).with_context(|| {
            format!(
                "No credentials in config and ~/.supurr/credentials.json not found. \
                 Run 'supurr init' to configure your wallet."
            )
        })?;

        #[derive(serde::Deserialize)]
        struct Creds {
            address: String,
            private_key: String,
        }

        let creds: Creds =
            serde_json::from_str(&content).context("Failed to parse ~/.supurr/credentials.json")?;

        // Use config values if present, fallback to credentials file
        let pk = if self.private_key.is_empty() {
            creds.private_key
        } else {
            self.private_key.clone()
        };
        let addr = if self.address.is_empty() {
            creds.address
        } else {
            self.address.clone()
        };

        Ok((pk, addr))
    }

    /// Load config from a JSON file
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_file(path: &PathBuf) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {:?}", path))?;
        let config: Self = serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {:?}", path))?;

        // Validate markets array is not empty
        if config.markets.is_empty() {
            anyhow::bail!("Config must have at least one market in the 'markets' array");
        }

        let market_errors: Vec<String> = config
            .markets
            .iter()
            .enumerate()
            .flat_map(|(idx, market)| {
                market
                    .validation_errors()
                    .into_iter()
                    .map(move |error| format!("markets[{}]: {}", idx, error))
            })
            .collect();
        if !market_errors.is_empty() {
            anyhow::bail!(
                "Market configuration validation failed: {}",
                market_errors.join(", ")
            );
        }

        Ok(config)
    }

    /// Parse environment from string
    pub fn parse_environment(&self) -> Environment {
        match self.environment.to_lowercase().as_str() {
            "mainnet" | "main" | "prod" => Environment::Mainnet,
            _ => Environment::Testnet,
        }
    }

    /// Extract strategy leverage and max_leverage from whichever strategy config is active.
    /// Returns `Some((leverage, max_leverage))` if the active strategy has leverage settings.
    pub fn strategy_leverage(&self) -> Option<(Decimal, Decimal)> {
        if let Some(ref g) = self.grid {
            let lev = Decimal::from_str(&g.leverage).ok()?;
            let max = Decimal::from_str(&g.max_leverage).ok()?;
            Some((lev, max))
        } else if let Some(ref d) = self.dca {
            let lev = Decimal::from_str(&d.leverage).ok()?;
            let max = Decimal::from_str(&d.max_leverage).ok()?;
            Some((lev, max))
        } else if let Some(ref a) = self.arbitrage {
            let lev = Decimal::from_str(&a.perp_leverage).ok()?;
            // Arb doesn't have explicit max_leverage, use a sensible default
            Some((lev, Decimal::new(50, 0)))
        } else {
            None
        }
    }

    /// Capital allocated to the active strategy, used as the performance metric base.
    ///
    /// This is deliberately strategy-scoped. Wallet/account equity is not used here because
    /// unrelated idle wallet capital would dilute APR, Sharpe, and drawdown percentages.
    pub fn strategy_allocated_capital_usdc(&self) -> Option<Decimal> {
        let strategy_type = self.strategy_type.to_lowercase();

        if strategy_type == "grid" {
            return self
                .grid
                .as_ref()
                .and_then(|grid| Decimal::from_str(&grid.max_investment_quote).ok());
        }

        if strategy_type == "orchestrator" {
            return self
                .grid
                .as_ref()
                .and_then(|grid| Decimal::from_str(&grid.max_investment_quote).ok());
        }

        if strategy_type == "arbitrage" || strategy_type == "arb" {
            return self
                .arbitrage
                .as_ref()
                .and_then(|arb| Decimal::from_str(&arb.order_amount).ok());
        }

        if strategy_type == "dca" {
            let dca = self.dca.as_ref()?;
            let direction = match dca.direction.to_lowercase().as_str() {
                "short" => DCADirection::Short,
                _ => DCADirection::Long,
            };
            let config = DCAConfig {
                strategy_id: StrategyId::new("metrics-dca"),
                environment: self.parse_environment(),
                market: self.primary_market().clone(),
                direction,
                trigger_price: Decimal::from_str(&dca.trigger_price).ok()?,
                base_order_size: Decimal::from_str(&dca.base_order_size).ok()?,
                dca_order_size: Decimal::from_str(&dca.dca_order_size).ok()?,
                max_dca_orders: dca.max_dca_orders,
                size_multiplier: Decimal::from_str(&dca.size_multiplier).ok()?,
                price_deviation_pct: Decimal::from_str(&dca.price_deviation_pct).ok()?,
                deviation_multiplier: Decimal::from_str(&dca.deviation_multiplier).ok()?,
                take_profit_pct: Decimal::from_str(&dca.take_profit_pct).ok()?,
                stop_loss: dca
                    .stop_loss
                    .as_ref()
                    .and_then(|value| Decimal::from_str(value).ok()),
                leverage: Decimal::from_str(&dca.leverage).ok()?,
                max_leverage: Decimal::from_str(&dca.max_leverage).ok()?,
                restart_on_complete: dca.restart_on_complete,
                cooldown_period_secs: dca.cooldown_period_secs,
            };
            return Some(config.max_total_investment());
        }

        None
    }

    /// Get the effective simulation config, falling back to defaults if absent.
    pub fn effective_simulation_config(&self) -> SimulationConfig {
        self.simulation.clone().unwrap_or(SimulationConfig {
            starting_balance_usdc: default_starting_balance(),
            fee_rate: default_fee_rate(),
        })
    }
}

// =============================================================================
// Market Maker Config
// =============================================================================

/// Market Maker strategy configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MMConfigJson {
    /// Base order size in base asset
    pub base_order_size: String,
    /// Base spread between bid and ask
    pub base_spread: String,
    /// Maximum position size in base asset
    pub max_position_size: String,
    /// Skew mode: "both", "size", "price", or "none"
    #[serde(default = "default_skew_mode")]
    pub skew_mode: String,
    /// Price skew gamma (how aggressively to skew quotes based on position)
    #[serde(default = "default_price_skew_gamma")]
    pub price_skew_gamma: String,
    /// Size skew floor (minimum size for quotes)
    #[serde(default = "default_size_skew_floor")]
    pub size_skew_floor: String,
    /// Minimum price change to update quotes
    #[serde(default = "default_min_price_change_pct")]
    pub min_price_change_pct: String,
    /// Stop loss (optional)
    #[serde(default)]
    pub stop_loss: Option<String>,
    /// Take profit (optional)
    #[serde(default)]
    pub take_profit: Option<String>,
}

// =============================================================================
// Grid Config
// =============================================================================

/// Grid strategy configuration from JSON
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GridConfigJson {
    /// Grid mode: "long", "short", "neutral"
    #[serde(default = "default_grid_mode")]
    pub mode: String,
    /// Number of grid levels
    #[serde(default = "default_grid_levels")]
    pub levels: u32,
    /// Start price of the grid
    pub start_price: String,
    /// End price of the grid
    pub end_price: String,
    /// Maximum investment in quote currency (USDC)
    pub max_investment_quote: String,
    /// Leverage to use
    #[serde(default = "default_leverage")]
    pub leverage: String,
    /// Maximum leverage allowed (for liquidation calculation)
    #[serde(default = "default_max_leverage")]
    pub max_leverage: String,
    /// Use post-only orders
    #[serde(default)]
    pub post_only: bool,
    /// Stop loss (optional)
    #[serde(default)]
    pub stop_loss: Option<String>,
    /// Take profit (optional)
    #[serde(default)]
    pub take_profit: Option<String>,
    /// Trailing upper limit price (optional). When set, enables trailing-up:
    /// the grid slides up as price rises, until the top of the window would
    /// exceed this ceiling.
    #[serde(default)]
    pub trailing_up_limit: Option<String>,
    /// Trailing lower limit price (optional). When set, enables trailing-down:
    /// the grid slides down as price falls, until the bottom of the window
    /// would go below this floor.
    #[serde(default)]
    pub trailing_down_limit: Option<String>,
}

// =============================================================================
// Arbitrage Config
// =============================================================================

/// Arbitrage strategy configuration from JSON
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ArbitrageConfigJson {
    /// Order amount in quote asset / USDC (e.g., "100" = $100 worth)
    pub order_amount: String,
    /// Leverage for perp position
    pub perp_leverage: String,
    /// Minimum spread to open (e.g., "0.003" = 0.3%)
    pub min_opening_spread_pct: String,
    /// Minimum spread to close (e.g., "-0.001" = -0.1%)
    pub min_closing_spread_pct: String,
    /// Slippage buffer for spot orders
    #[serde(default = "default_slippage")]
    pub spot_slippage_buffer_pct: String,
    /// Slippage buffer for perp orders
    #[serde(default = "default_slippage")]
    pub perp_slippage_buffer_pct: String,
}

// =============================================================================
// DCA Config
// =============================================================================

/// DCA strategy configuration from JSON
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DCAConfigJson {
    /// Direction: "long" or "short"
    #[serde(default = "default_dca_direction")]
    pub direction: String,
    /// Price to trigger base order
    pub trigger_price: String,
    /// Base order size in base asset
    pub base_order_size: String,
    /// DCA order size in base asset
    pub dca_order_size: String,
    /// Maximum number of DCA orders
    #[serde(default = "default_max_dca_orders")]
    pub max_dca_orders: u32,
    /// Size multiplier for each subsequent DCA order
    #[serde(default = "default_size_multiplier")]
    pub size_multiplier: String,
    /// Price deviation percentage to trigger first DCA
    pub price_deviation_pct: String,
    /// Deviation multiplier for subsequent triggers
    #[serde(default = "default_deviation_multiplier")]
    pub deviation_multiplier: String,
    /// Take profit percentage from average entry
    pub take_profit_pct: String,
    /// Optional stop loss as absolute PnL threshold (negative value)
    #[serde(default)]
    pub stop_loss: Option<String>,
    /// Leverage (1 for spot-like)
    #[serde(default = "default_leverage")]
    pub leverage: String,
    /// Max leverage allowed
    #[serde(default = "default_max_leverage")]
    pub max_leverage: String,
    /// Whether to restart cycle after take profit
    #[serde(default)]
    pub restart_on_complete: bool,
    /// Cooldown period in seconds between cycles (default: 60)
    #[serde(default = "default_cooldown_period")]
    pub cooldown_period_secs: u64,
}

// =============================================================================
// Orchestrator Config
// =============================================================================

/// Parent strategy configuration for grouped child strategies.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OrchestratorConfigJson {
    /// V1 kind: "prediction_yes_no_grid"
    #[serde(default = "default_orchestrator_kind")]
    pub kind: String,
    /// Static allocation mode for child legs. V1 supports "static_50_50".
    #[serde(default = "default_allocation_mode")]
    pub allocation_mode: String,
    /// Group take-profit threshold in percentage units. Example: "10" = +10%.
    #[serde(default)]
    pub take_profit_pct: Option<String>,
    /// Group stop-loss threshold in percentage units. Example: "5" = -5%.
    #[serde(default)]
    pub stop_loss_pct: Option<String>,
    /// Conditions that must pass before child strategies start.
    #[serde(default)]
    pub start_conditions: Vec<OrchestratorCondition>,
    /// Conditions that must remain valid while waiting/running.
    #[serde(default)]
    pub validation_conditions: Vec<OrchestratorCondition>,
    /// Conditions that trigger a risk exit.
    #[serde(default)]
    pub risk_conditions: Vec<OrchestratorCondition>,
    /// Generic child strategy plans. V1 generic orchestrator supports grid and dca only.
    #[serde(default)]
    pub children: Vec<OrchestratorChildConfigJson>,
    /// Explicit child-leg ranges supplied by the client from live prices.
    #[serde(default)]
    pub legs: Vec<OrchestratorLegConfigJson>,
}

/// Generic child strategy plan owned by the orchestrator.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OrchestratorChildConfigJson {
    /// Grid child strategy plan.
    Grid {
        /// Optional stable child ID used in logs and strategy IDs.
        #[serde(default)]
        id: Option<String>,
        /// Market this child trades.
        market: Market,
        /// Grid configuration for this child.
        grid: GridConfigJson,
    },
    /// DCA child strategy plan.
    Dca {
        /// Optional stable child ID used in logs and strategy IDs.
        #[serde(default)]
        id: Option<String>,
        /// Market this child trades.
        market: Market,
        /// DCA configuration for this child.
        dca: DCAConfigJson,
    },
}

/// Per-leg range override for orchestrated child strategies.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OrchestratorLegConfigJson {
    /// Outcome side: 0 = Yes, 1 = No
    pub side: u8,
    /// Child grid start price for this side.
    pub start_price: String,
    /// Child grid end price for this side.
    pub end_price: String,
    /// Optional child trailing ceiling for this side.
    #[serde(default)]
    pub trailing_up_limit: Option<String>,
    /// Optional child trailing floor for this side.
    #[serde(default)]
    pub trailing_down_limit: Option<String>,
}

// =============================================================================
// Common Config Structs
// =============================================================================

/// Builder fee configuration for JSON config
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BuilderFeeConfig {
    /// Builder address to receive the fee
    pub address: String,
    /// Fee in tenths of a basis point (e.g., 30 = 3 bp = 0.03%)
    pub fee_tenths_bp: u32,
}

/// Trade syncer configuration for upstream API PnL tracking
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SyncConfigJson {
    /// Bot ID for upstream API (required if enabled)
    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)
    #[serde(default = "default_sync_interval_ms")]
    pub sync_interval_ms: u64,
    /// HTTP timeout in seconds (default: 10)
    #[serde(default = "default_sync_timeout")]
    pub timeout_secs: u64,
    /// Optional shared secret sent as x-bot-sync-secret.
    #[serde(default)]
    pub sync_secret: Option<String>,
    /// Enable syncing (default: true if sync section is present)
    #[serde(default = "default_sync_enabled")]
    pub enabled: bool,
}

/// Simulation configuration for paper trading and backtesting.
/// All fields are optional with sensible defaults.
///
/// Example JSON:
/// ```json
/// { "simulation": { "starting_balance_usdc": "5000", "fee_rate": "0.0002" } }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SimulationConfig {
    /// Starting USDC balance (default: "10000")
    #[serde(default = "default_starting_balance")]
    pub starting_balance_usdc: String,
    /// Fee rate as decimal (default: "0.00025" = 0.025%)
    #[serde(default = "default_fee_rate")]
    pub fee_rate: String,
}

// =============================================================================
// Default value functions
// =============================================================================

fn default_dca_direction() -> String {
    "long".to_string()
}

fn default_max_dca_orders() -> u32 {
    5
}

fn default_size_multiplier() -> String {
    "2.0".to_string()
}

fn default_deviation_multiplier() -> String {
    "1.0".to_string()
}

fn default_cooldown_period() -> u64 {
    60 // 60 seconds like Binance
}

fn default_slippage() -> String {
    "0.001".to_string()
}

fn default_grid_mode() -> String {
    "long".to_string()
}

fn default_grid_levels() -> u32 {
    20
}

fn default_leverage() -> String {
    "5".to_string()
}

fn default_max_leverage() -> String {
    "50".to_string()
}

fn default_sync_interval_ms() -> u64 {
    10_000
}

fn default_sync_timeout() -> u64 {
    10
}

fn default_sync_enabled() -> bool {
    true
}

fn default_starting_balance() -> String {
    "10000".to_string()
}

fn default_fee_rate() -> String {
    "0.00025".to_string() // 0.025% taker fee (Hyperliquid default)
}

fn default_poll_delay_ms() -> u64 {
    500
}

fn default_orchestrator_kind() -> String {
    "prediction_yes_no_grid".to_string()
}

fn default_allocation_mode() -> String {
    "static_50_50".to_string()
}

fn default_skew_mode() -> String {
    "both".to_string()
}
fn default_price_skew_gamma() -> String {
    "0.05".to_string()
}
fn default_size_skew_floor() -> String {
    "0.2".to_string()
}
fn default_min_price_change_pct() -> String {
    "0.0005".to_string()
}

// =============================================================================
// Strategy Builder
// =============================================================================

fn outcome_side_label(side: u8) -> &'static str {
    match side {
        0 => "yes",
        1 => "no",
        _ => "unknown",
    }
}

fn opposite_outcome_market(market: &Market) -> Result<Market> {
    match market {
        Market::Hyperliquid(HyperliquidMarket::Outcome {
            name,
            outcome_id,
            side,
            instrument_meta,
        }) => {
            let opposite_side = if *side == 0 { 1 } else { 0 };
            Ok(Market::Hyperliquid(HyperliquidMarket::Outcome {
                name: name.clone(),
                outcome_id: *outcome_id,
                side: opposite_side,
                instrument_meta: instrument_meta.clone(),
            }))
        }
        _ => anyhow::bail!("prediction_yes_no_grid orchestrator requires an outcome market"),
    }
}

fn orchestrator_markets(config: &BotConfig) -> Result<Vec<Market>> {
    let strategy_type = config.strategy_type.to_lowercase();
    if strategy_type != "orchestrator" {
        return Ok(config.markets.clone());
    }

    let orchestrator_json = config
        .orchestrator
        .as_ref()
        .context("Orchestrator config missing: add 'orchestrator' section")?;
    if orchestrator_json.kind == "generic" {
        anyhow::ensure!(
            !orchestrator_json.children.is_empty(),
            "generic orchestrator requires orchestrator.children"
        );
        return Ok(orchestrator_json
            .children
            .iter()
            .map(|child| match child {
                OrchestratorChildConfigJson::Grid { market, .. }
                | OrchestratorChildConfigJson::Dca { market, .. } => market.clone(),
            })
            .collect());
    }

    anyhow::ensure!(
        config.markets.len() == 1,
        "Orchestrator V1 expects exactly one configured market; it mirrors the opposite outcome side internally"
    );

    let primary = config.primary_market().clone();
    let opposite = opposite_outcome_market(&primary)?;
    Ok(vec![primary, opposite])
}

fn grid_mode_from_json(mode: &str) -> GridMode {
    match mode.to_lowercase().as_str() {
        "short" => GridMode::Short,
        "neutral" => GridMode::Neutral,
        _ => GridMode::Long,
    }
}

fn build_grid_config_for_market(
    config: &BotConfig,
    grid_json: &GridConfigJson,
    market: Market,
    strategy_id: StrategyId,
    allocation_override: Option<Decimal>,
    force_long: bool,
    disable_child_exits: bool,
) -> Result<GridConfig> {
    Ok(GridConfig {
        strategy_id,
        environment: config.parse_environment(),
        market,
        grid_mode: if force_long {
            GridMode::Long
        } else {
            grid_mode_from_json(&grid_json.mode)
        },
        grid_levels: grid_json.levels,
        start_price: Decimal::from_str(&grid_json.start_price).context("Invalid start_price")?,
        end_price: Decimal::from_str(&grid_json.end_price).context("Invalid end_price")?,
        max_investment_quote: match allocation_override {
            Some(value) => value,
            None => Decimal::from_str(&grid_json.max_investment_quote)
                .context("Invalid max_investment_quote")?,
        },
        base_order_size: Decimal::new(1, 3),
        leverage: Decimal::from_str(&grid_json.leverage).context("Invalid leverage")?,
        max_leverage: Decimal::from_str(&grid_json.max_leverage).context("Invalid max_leverage")?,
        post_only: grid_json.post_only,
        stop_loss: if disable_child_exits {
            None
        } else {
            grid_json
                .stop_loss
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid stop_loss")?
        },
        take_profit: if disable_child_exits {
            None
        } else {
            grid_json
                .take_profit
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid take_profit")?
        },
        trailing_up_limit: grid_json
            .trailing_up_limit
            .as_ref()
            .map(|s| Decimal::from_str(s))
            .transpose()
            .context("Invalid grid trailing_up_limit")?,
        trailing_down_limit: grid_json
            .trailing_down_limit
            .as_ref()
            .map(|s| Decimal::from_str(s))
            .transpose()
            .context("Invalid grid trailing_down_limit")?,
    })
}

#[allow(dead_code)]
fn build_dca_config_for_market(
    config: &BotConfig,
    dca_json: &DCAConfigJson,
    market: Market,
    strategy_id: StrategyId,
) -> Result<DCAConfig> {
    Ok(DCAConfig {
        strategy_id,
        environment: config.parse_environment(),
        market,
        direction: match dca_json.direction.to_lowercase().as_str() {
            "short" => DCADirection::Short,
            _ => DCADirection::Long,
        },
        trigger_price: Decimal::from_str(&dca_json.trigger_price)
            .context("Invalid trigger_price")?,
        base_order_size: Decimal::from_str(&dca_json.base_order_size)
            .context("Invalid base_order_size")?,
        dca_order_size: Decimal::from_str(&dca_json.dca_order_size)
            .context("Invalid dca_order_size")?,
        max_dca_orders: dca_json.max_dca_orders,
        size_multiplier: Decimal::from_str(&dca_json.size_multiplier)
            .context("Invalid size_multiplier")?,
        price_deviation_pct: Decimal::from_str(&dca_json.price_deviation_pct)
            .context("Invalid price_deviation_pct")?,
        deviation_multiplier: Decimal::from_str(&dca_json.deviation_multiplier)
            .context("Invalid deviation_multiplier")?,
        take_profit_pct: Decimal::from_str(&dca_json.take_profit_pct)
            .context("Invalid take_profit_pct")?,
        stop_loss: dca_json
            .stop_loss
            .as_ref()
            .map(|s| Decimal::from_str(s))
            .transpose()
            .context("Invalid stop_loss")?,
        leverage: Decimal::from_str(&dca_json.leverage).context("Invalid leverage")?,
        max_leverage: Decimal::from_str(&dca_json.max_leverage).context("Invalid max_leverage")?,
        restart_on_complete: dca_json.restart_on_complete,
        cooldown_period_secs: dca_json.cooldown_period_secs,
    })
}

#[allow(dead_code)]
fn validate_dca_config_with_price_bounds(dca_config: &DCAConfig) -> Result<()> {
    let mut errors = dca_config.validate();
    push_price_bound_errors(
        &dca_config.market,
        &[("dca.trigger_price", dca_config.trigger_price)],
        &mut errors,
    );
    if !errors.is_empty() {
        anyhow::bail!("DCA configuration validation failed: {}", errors.join(", "));
    }
    Ok(())
}

fn leg_overrides_by_side(
    orchestrator_json: &OrchestratorConfigJson,
) -> Result<HashMap<u8, OrchestratorLegConfigJson>> {
    let mut overrides = HashMap::new();
    for leg in &orchestrator_json.legs {
        anyhow::ensure!(
            leg.side == 0 || leg.side == 1,
            "orchestrator.legs side must be 0 or 1"
        );
        anyhow::ensure!(
            overrides.insert(leg.side, leg.clone()).is_none(),
            "duplicate orchestrator.legs entry for side {}",
            leg.side
        );
    }
    Ok(overrides)
}

fn apply_leg_override(grid_config: &mut GridConfig, leg: &OrchestratorLegConfigJson) -> Result<()> {
    grid_config.start_price =
        Decimal::from_str(&leg.start_price).context("Invalid orchestrator leg start_price")?;
    grid_config.end_price =
        Decimal::from_str(&leg.end_price).context("Invalid orchestrator leg end_price")?;
    grid_config.trailing_up_limit = leg
        .trailing_up_limit
        .as_ref()
        .map(|s| Decimal::from_str(s))
        .transpose()
        .context("Invalid orchestrator leg trailing_up_limit")?;
    grid_config.trailing_down_limit = leg
        .trailing_down_limit
        .as_ref()
        .map(|s| Decimal::from_str(s))
        .transpose()
        .context("Invalid orchestrator leg trailing_down_limit")?;
    Ok(())
}

fn validate_grid_config_with_price_bounds(grid_config: &GridConfig) -> Result<()> {
    let mut errors = grid_config.validate();
    let mut bounded_prices = vec![
        ("grid.start_price", grid_config.start_price),
        ("grid.end_price", grid_config.end_price),
    ];
    if let Some(price) = grid_config.trailing_up_limit {
        bounded_prices.push(("grid.trailing_up_limit", price));
    }
    if let Some(price) = grid_config.trailing_down_limit {
        bounded_prices.push(("grid.trailing_down_limit", price));
    }
    push_price_bound_errors(&grid_config.market, &bounded_prices, &mut errors);
    if !errors.is_empty() {
        anyhow::bail!(
            "Grid configuration validation failed: {}",
            errors.join(", ")
        );
    }
    Ok(())
}

/// Build the strategy from a V2 BotConfig.
/// Works identically on native and WASM.
pub fn build_strategy(config: &BotConfig) -> Result<Box<dyn Strategy>> {
    let environment = config.parse_environment();
    let strategy_type = config.strategy_type.to_lowercase();

    let is_arb = strategy_type == "arbitrage" || strategy_type == "arb";
    let is_grid = strategy_type == "grid";
    let is_dca = strategy_type == "dca";
    let is_mm = strategy_type == "mm" || strategy_type == "market_maker";
    let is_orchestrator = strategy_type == "orchestrator";

    if is_arb {
        // Arbitrage strategy — requires exactly 2 markets: [spot, perp]
        anyhow::ensure!(
            config.markets.len() >= 2,
            "Arbitrage requires 2 markets in config: markets[0]=spot, markets[1]=perp"
        );

        let arb_json = config
            .arbitrage
            .as_ref()
            .context("Arbitrage config missing: add 'arbitrage' section to config")?;

        let spot_market = config.markets[0].clone();
        let perp_market = config.markets[1].clone();

        let arb_config = ArbitrageConfig {
            strategy_id: StrategyId::new(format!("{}-arb", spot_market.base().to_lowercase())),
            spot_market,
            perp_market,
            environment,
            order_amount: Decimal::from_str(&arb_json.order_amount)
                .context("Invalid order_amount")?,
            perp_leverage: Decimal::from_str(&arb_json.perp_leverage)
                .context("Invalid perp_leverage")?,
            min_opening_spread_pct: Decimal::from_str(&arb_json.min_opening_spread_pct)
                .context("Invalid min_opening_spread_pct")?,
            min_closing_spread_pct: Decimal::from_str(&arb_json.min_closing_spread_pct)
                .context("Invalid min_closing_spread_pct")?,
            spot_slippage_buffer_pct: Decimal::from_str(&arb_json.spot_slippage_buffer_pct)
                .context("Invalid spot_slippage_buffer_pct")?,
            perp_slippage_buffer_pct: Decimal::from_str(&arb_json.perp_slippage_buffer_pct)
                .context("Invalid perp_slippage_buffer_pct")?,
        };

        // Validate arb config
        let errors = arb_config.validate();
        if !errors.is_empty() {
            anyhow::bail!(
                "Arbitrage configuration validation failed: {}",
                errors.join(", ")
            );
        }

        Ok(Box::new(ArbitrageStrategy::new(arb_config)))
    } else if is_orchestrator {
        let orchestrator_json = config
            .orchestrator
            .as_ref()
            .context("Orchestrator config missing: add 'orchestrator' section")?;
        let grid_json = config
            .grid
            .as_ref()
            .context("Orchestrator V1 requires a child 'grid' section")?;

        anyhow::ensure!(
            orchestrator_json.kind == "prediction_yes_no_grid",
            "Unsupported orchestrator kind '{}'; supported kind: prediction_yes_no_grid",
            orchestrator_json.kind
        );
        anyhow::ensure!(
            orchestrator_json.allocation_mode == "static_50_50",
            "Unsupported orchestrator allocation_mode '{}'; supported mode: static_50_50",
            orchestrator_json.allocation_mode
        );

        let markets = orchestrator_markets(config)?;
        let leg_overrides = leg_overrides_by_side(orchestrator_json)?;
        let total_allocation = Decimal::from_str(&grid_json.max_investment_quote)
            .context("Invalid max_investment_quote")?;
        let child_allocation = total_allocation / Decimal::TWO;

        let mut legs = Vec::new();
        for market in markets {
            let (_, side, _) = market
                .outcome_params()
                .context("Orchestrator V1 only supports outcome markets")?;
            let label = outcome_side_label(side);
            let mut child_config = build_grid_config_for_market(
                config,
                grid_json,
                market.clone(),
                StrategyId::new(format!("{}-{}-grid", config.primary_market().base(), label)),
                Some(child_allocation),
                true,
                true,
            )?;
            if let Some(leg_override) = leg_overrides.get(&side) {
                apply_leg_override(&mut child_config, leg_override)?;
            }
            validate_grid_config_with_price_bounds(&child_config)?;
            legs.push(OrchestratorLeg::new(
                label,
                child_config.market.instrument_id(),
                Box::new(GridStrategy::new(child_config)),
            ));
        }

        let risk = GroupRiskConfig {
            allocated_capital_quote: total_allocation,
            take_profit_pct: orchestrator_json
                .take_profit_pct
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid orchestrator take_profit_pct")?,
            stop_loss_pct: orchestrator_json
                .stop_loss_pct
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid orchestrator stop_loss_pct")?,
        };
        let conditions = OrchestratorConditions {
            start_conditions: orchestrator_json.start_conditions.clone(),
            validation_conditions: orchestrator_json.validation_conditions.clone(),
            risk_conditions: orchestrator_json.risk_conditions.clone(),
        };

        Ok(Box::new(BotOrchestrator::with_conditions(
            StrategyId::new(format!("{}-orchestrator", config.primary_market().base())),
            legs,
            risk,
            conditions,
        )))
    } else if is_grid {
        // Grid strategy
        let grid_json = config
            .grid
            .as_ref()
            .context("Grid config missing: add 'grid' section to config")?;

        let grid_config = GridConfig {
            strategy_id: StrategyId::new(format!("{}-grid", config.primary_market().base())),
            environment,
            market: config.primary_market().clone(),
            grid_mode: match grid_json.mode.to_lowercase().as_str() {
                "short" => GridMode::Short,
                "neutral" => GridMode::Neutral,
                _ => GridMode::Long,
            },
            grid_levels: grid_json.levels,
            start_price: Decimal::from_str(&grid_json.start_price)
                .context("Invalid start_price")?,
            end_price: Decimal::from_str(&grid_json.end_price).context("Invalid end_price")?,
            max_investment_quote: Decimal::from_str(&grid_json.max_investment_quote)
                .context("Invalid max_investment_quote")?,
            base_order_size: Decimal::new(1, 3), // fallback 0.001
            leverage: Decimal::from_str(&grid_json.leverage).context("Invalid leverage")?,
            max_leverage: Decimal::from_str(&grid_json.max_leverage)
                .context("Invalid max_leverage")?,
            post_only: grid_json.post_only,
            stop_loss: grid_json
                .stop_loss
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid stop_loss")?,
            take_profit: grid_json
                .take_profit
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid take_profit")?,
            // Trailing is opt-in; enabled by the presence of a limit price.
            trailing_up_limit: grid_json
                .trailing_up_limit
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid trailing_up_limit")?,
            trailing_down_limit: grid_json
                .trailing_down_limit
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid grid trailing_down_limit")?,
        };

        // Validate grid config
        let mut errors = grid_config.validate();
        let mut bounded_prices = vec![
            ("grid.start_price", grid_config.start_price),
            ("grid.end_price", grid_config.end_price),
        ];
        if let Some(price) = grid_config.trailing_up_limit {
            bounded_prices.push(("grid.trailing_up_limit", price));
        }
        if let Some(price) = grid_config.trailing_down_limit {
            bounded_prices.push(("grid.trailing_down_limit", price));
        }
        push_price_bound_errors(&grid_config.market, &bounded_prices, &mut errors);
        if !errors.is_empty() {
            anyhow::bail!(
                "Grid configuration validation failed: {}",
                errors.join(", ")
            );
        }

        Ok(Box::new(GridStrategy::new(grid_config)))
    } else if is_dca {
        // DCA strategy
        let dca_json = config
            .dca
            .as_ref()
            .context("DCA config missing: add 'dca' section to config")?;

        let dca_config = DCAConfig {
            strategy_id: StrategyId::new(format!("{}-dca", config.primary_market().base())),
            environment,
            market: config.primary_market().clone(),
            direction: match dca_json.direction.to_lowercase().as_str() {
                "short" => DCADirection::Short,
                _ => DCADirection::Long,
            },
            trigger_price: Decimal::from_str(&dca_json.trigger_price)
                .context("Invalid trigger_price")?,
            base_order_size: Decimal::from_str(&dca_json.base_order_size)
                .context("Invalid base_order_size")?,
            dca_order_size: Decimal::from_str(&dca_json.dca_order_size)
                .context("Invalid dca_order_size")?,
            max_dca_orders: dca_json.max_dca_orders,
            size_multiplier: Decimal::from_str(&dca_json.size_multiplier)
                .context("Invalid size_multiplier")?,
            price_deviation_pct: Decimal::from_str(&dca_json.price_deviation_pct)
                .context("Invalid price_deviation_pct")?,
            deviation_multiplier: Decimal::from_str(&dca_json.deviation_multiplier)
                .context("Invalid deviation_multiplier")?,
            take_profit_pct: Decimal::from_str(&dca_json.take_profit_pct)
                .context("Invalid take_profit_pct")?,
            stop_loss: dca_json
                .stop_loss
                .as_ref()
                .map(|s| Decimal::from_str(s))
                .transpose()
                .context("Invalid stop_loss")?,
            leverage: Decimal::from_str(&dca_json.leverage).context("Invalid leverage")?,
            max_leverage: Decimal::from_str(&dca_json.max_leverage)
                .context("Invalid max_leverage")?,
            restart_on_complete: dca_json.restart_on_complete,
            cooldown_period_secs: dca_json.cooldown_period_secs,
        };

        // Validate DCA config
        let mut errors = dca_config.validate();
        push_price_bound_errors(
            &dca_config.market,
            &[("dca.trigger_price", dca_config.trigger_price)],
            &mut errors,
        );
        if !errors.is_empty() {
            anyhow::bail!("DCA configuration validation failed: {}", errors.join(", "));
        }

        Ok(Box::new(DCAStrategy::new(dca_config)))
    } else if strategy_type == "tick_trader" {
        #[cfg(feature = "strategy-tick-trader")]
        {
            // Tick-trader: custom strategy using custom_config() pattern
            let tick_config: TickTraderConfig = config.custom_config("tick_trader")?;
            let errors = tick_config.validate();
            if !errors.is_empty() {
                anyhow::bail!(
                    "Tick trader config validation failed: {}",
                    errors.join(", ")
                );
            }
            Ok(Box::new(TickTrader::new(tick_config)))
        }
        #[cfg(not(feature = "strategy-tick-trader"))]
        {
            anyhow::bail!("Tick trader strategy is not enabled in this build")
        }
    } else if strategy_type == "rsi" {
        #[cfg(feature = "strategy-rsi")]
        {
            // RSI strategy: uses inline Wilder's RSI indicator + bar aggregation
            let rsi_config: RsiStrategyConfig = config.custom_config("rsi")?;
            let errors = rsi_config.validate();
            if !errors.is_empty() {
                anyhow::bail!("RSI config validation failed: {}", errors.join(", "));
            }
            let market = config.primary_market().clone();
            let environment = config.parse_environment();
            Ok(Box::new(RsiStrategy::new(rsi_config, market, environment)))
        }
        #[cfg(not(feature = "strategy-rsi"))]
        {
            anyhow::bail!("RSI strategy is not enabled in this build")
        }
    } else if is_mm {
        // Market maker strategy
        let mm_json = config
            .mm
            .as_ref()
            .context("MM config missing: add 'mm' section to config for strategy_type='mm'")?;

        let base_order_size =
            Decimal::from_str(&mm_json.base_order_size).context("Invalid base_order_size")?;
        let base_spread = Decimal::from_str(&mm_json.base_spread).context("Invalid base_spread")?;
        let max_position_size =
            Decimal::from_str(&mm_json.max_position_size).context("Invalid max_position_size")?;
        let price_skew_gamma =
            Decimal::from_str(&mm_json.price_skew_gamma).context("Invalid price_skew_gamma")?;
        let size_skew_floor =
            Decimal::from_str(&mm_json.size_skew_floor).context("Invalid size_skew_floor")?;
        let min_price_change_pct = Decimal::from_str(&mm_json.min_price_change_pct)
            .context("Invalid min_price_change_pct")?;

        let stop_loss = mm_json
            .stop_loss
            .as_ref()
            .map(|s| Decimal::from_str(s))
            .transpose()
            .context("Invalid stop_loss")?;
        let take_profit = mm_json
            .take_profit
            .as_ref()
            .map(|s| Decimal::from_str(s))
            .transpose()
            .context("Invalid take_profit")?;

        let skew_mode = match mm_json.skew_mode.to_lowercase().as_str() {
            "none" => SkewMode::None,
            "size" => SkewMode::Size,
            "price" => SkewMode::Price,
            "both" | _ => SkewMode::Both,
        };

        let mm_config = MarketMakerConfig {
            strategy_id: StrategyId::new(format!("{}-mm", config.primary_market().base())),
            environment,
            market: config.primary_market().clone(),
            base_order_size,
            base_spread,
            target_position_pct: Decimal::new(5, 1), // 0.5
            min_position_pct: Decimal::new(1, 1),    // 0.1
            max_position_pct: Decimal::new(9, 1),    // 0.9
            max_position_size,
            skew_mode,
            price_skew_gamma,
            size_skew_floor,
            min_price_change_pct,
            stop_loss,
            take_profit,
        };

        // Validate MM config
        let errors = mm_config.validate();
        if !errors.is_empty() {
            anyhow::bail!("Configuration validation failed: {}", errors.join(", "));
        }

        Ok(Box::new(MarketMaker::new(mm_config)))
    } else {
        // =====================================================================
        // Custom strategy — registered by AI agents / advanced users.
        //
        // To register a custom strategy:
        // 1. Create your strategy crate (use supurr_skill/templates/strategy-template/)
        // 2. Add it to workspace Cargo.toml
        // 3. Add dependency in bot-engine/Cargo.toml
        // 4. Add a branch here:
        //      "mystrategy" => strategy_mystrategy::build_from_json(&config),
        // =====================================================================
        anyhow::bail!(
            "Unknown strategy type: '{}'. Built-in types: grid, dca, mm, arb. \
             For custom strategies, see STRATEGY_API.md.",
            strategy_type
        )
    }
}

/// Build InstrumentMeta from BotConfig's primary market.
pub fn build_instrument_meta(config: &BotConfig) -> InstrumentMeta {
    let primary_market = config.primary_market();
    let quote_currency = primary_market.quote();

    // Extract instrument_meta from Market, use defaults if not provided
    let (tick_size, lot_size, min_qty, min_notional) = primary_market
        .instrument_meta()
        .map(|im| (im.tick_size, im.lot_size, im.min_qty, im.min_notional))
        .unwrap_or((Decimal::new(1, 1), Decimal::new(1, 4), None, None));

    InstrumentMeta {
        instrument_id: primary_market.instrument_id(),
        market_index: primary_market.market_index(),
        base_asset: AssetId::new(primary_market.base()),
        quote_asset: AssetId::new(quote_currency),
        tick_size,
        lot_size,
        min_qty,
        min_notional,
        fee_asset_default: Some(AssetId::new(quote_currency)),
        kind: primary_market.instrument_kind(),
    }
}

/// Build InstrumentMeta for ALL markets in `config.markets[]`.
///
/// For multi-instrument strategies (e.g., Arbitrage with spot + perp),
/// this returns one `InstrumentMeta` per market entry.
pub fn build_instrument_metas(config: &BotConfig) -> Vec<InstrumentMeta> {
    let markets = orchestrator_markets(config).unwrap_or_else(|_| config.markets.clone());

    markets
        .iter()
        .map(|market| {
            let quote_currency = market.quote();
            let (tick_size, lot_size, min_qty, min_notional) = market
                .instrument_meta()
                .map(|im| (im.tick_size, im.lot_size, im.min_qty, im.min_notional))
                .unwrap_or((Decimal::new(1, 1), Decimal::new(1, 4), None, None));

            InstrumentMeta {
                instrument_id: market.instrument_id(),
                market_index: market.market_index(),
                base_asset: AssetId::new(market.base()),
                quote_asset: AssetId::new(quote_currency),
                tick_size,
                lot_size,
                min_qty,
                min_notional,
                fee_asset_default: Some(AssetId::new(quote_currency)),
                kind: market.instrument_kind(),
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use bot_core::HyperliquidMarket;
    use rust_decimal_macros::dec;

    fn btc_perp_market() -> Market {
        Market::Hyperliquid(HyperliquidMarket::Perp {
            base: "BTC".to_string(),
            quote: "USDC".to_string(),
            index: 0,
            instrument_meta: None,
        })
    }

    fn btc_outcome_market() -> Market {
        Market::Hyperliquid(HyperliquidMarket::Outcome {
            name: "BTC > 78213".to_string(),
            outcome_id: 1,
            side: 0,
            instrument_meta: None,
        })
    }

    fn base_config(strategy_type: &str) -> BotConfig {
        BotConfig {
            environment: "mainnet".to_string(),
            private_key: String::new(),
            address: String::new(),
            vault_address: None,
            base_url_override: None,
            strategy_type: strategy_type.to_string(),
            markets: vec![btc_perp_market()],
            poll_delay_ms: 500,
            grid: None,
            mm: None,
            dca: None,
            arbitrage: None,
            orchestrator: None,
            builder_fee: None,
            sync: None,
            simulation: None,
            extra: HashMap::new(),
        }
    }

    #[test]
    fn grid_allocated_capital_uses_max_investment_quote() {
        let mut config = base_config("grid");
        config.grid = Some(GridConfigJson {
            mode: "long".to_string(),
            levels: 10,
            start_price: "77000".to_string(),
            end_price: "78000".to_string(),
            max_investment_quote: "123.45".to_string(),
            leverage: "20".to_string(),
            max_leverage: "40".to_string(),
            post_only: false,
            stop_loss: None,
            take_profit: None,
            trailing_up_limit: None,
            trailing_down_limit: None,
        });

        assert_eq!(config.strategy_allocated_capital_usdc(), Some(dec!(123.45)));
    }

    #[test]
    fn orchestrator_registers_both_outcome_legs_from_one_market() {
        let mut config = base_config("orchestrator");
        config.markets = vec![btc_outcome_market()];
        config.grid = Some(GridConfigJson {
            mode: "long".to_string(),
            levels: 10,
            start_price: "0.2".to_string(),
            end_price: "0.8".to_string(),
            max_investment_quote: "500".to_string(),
            leverage: "1".to_string(),
            max_leverage: "1".to_string(),
            post_only: false,
            stop_loss: Some("10".to_string()),
            take_profit: Some("10".to_string()),
            trailing_up_limit: None,
            trailing_down_limit: None,
        });
        config.orchestrator = Some(OrchestratorConfigJson {
            kind: "prediction_yes_no_grid".to_string(),
            allocation_mode: "static_50_50".to_string(),
            take_profit_pct: Some("10".to_string()),
            stop_loss_pct: Some("5".to_string()),
            start_conditions: Vec::new(),
            validation_conditions: Vec::new(),
            risk_conditions: Vec::new(),
            children: Vec::new(),
            legs: Vec::new(),
        });

        let strategy = build_strategy(&config).expect("orchestrator strategy should build");
        assert_eq!(strategy.id().as_str(), "BTC > 78213-orchestrator");

        let metas = build_instrument_metas(&config);
        let instruments: Vec<String> = metas
            .iter()
            .map(|meta| meta.instrument_id.to_string())
            .collect();
        assert_eq!(instruments, vec!["#10-OUTCOME", "#11-OUTCOME"]);
        assert_eq!(config.strategy_allocated_capital_usdc(), Some(dec!(500)));
    }

    #[test]
    fn orchestrator_accepts_client_supplied_leg_ranges() {
        let orchestrator = OrchestratorConfigJson {
            kind: "prediction_yes_no_grid".to_string(),
            allocation_mode: "static_50_50".to_string(),
            take_profit_pct: None,
            stop_loss_pct: None,
            start_conditions: Vec::new(),
            validation_conditions: Vec::new(),
            risk_conditions: Vec::new(),
            children: Vec::new(),
            legs: vec![
                OrchestratorLegConfigJson {
                    side: 0,
                    start_price: "0.30".to_string(),
                    end_price: "0.36".to_string(),
                    trailing_up_limit: None,
                    trailing_down_limit: None,
                },
                OrchestratorLegConfigJson {
                    side: 1,
                    start_price: "0.64".to_string(),
                    end_price: "0.70".to_string(),
                    trailing_up_limit: None,
                    trailing_down_limit: None,
                },
            ],
        };

        let overrides = leg_overrides_by_side(&orchestrator).expect("valid leg overrides");
        assert_eq!(overrides[&0].start_price, "0.30");
        assert_eq!(overrides[&1].end_price, "0.70");
    }

    #[test]
    fn arbitrage_allocated_capital_uses_order_amount() {
        let mut config = base_config("arb");
        config.arbitrage = Some(ArbitrageConfigJson {
            order_amount: "50".to_string(),
            perp_leverage: "5".to_string(),
            min_opening_spread_pct: "0.2".to_string(),
            min_closing_spread_pct: "0.05".to_string(),
            spot_slippage_buffer_pct: "0.1".to_string(),
            perp_slippage_buffer_pct: "0.1".to_string(),
        });

        assert_eq!(config.strategy_allocated_capital_usdc(), Some(dec!(50)));
    }

    #[test]
    fn dca_allocated_capital_uses_full_ladder_not_wallet_balance() {
        let mut config = base_config("dca");
        config.dca = Some(DCAConfigJson {
            direction: "long".to_string(),
            trigger_price: "100".to_string(),
            base_order_size: "1".to_string(),
            dca_order_size: "1".to_string(),
            max_dca_orders: 2,
            size_multiplier: "2".to_string(),
            price_deviation_pct: "10".to_string(),
            deviation_multiplier: "1".to_string(),
            take_profit_pct: "2".to_string(),
            stop_loss: None,
            leverage: "1".to_string(),
            max_leverage: "10".to_string(),
            restart_on_complete: false,
            cooldown_period_secs: 60,
        });

        // Base: 1 * 100 = 100
        // DCA 1: 1 * 90 = 90
        // DCA 2: 2 * 81 = 162
        assert_eq!(config.strategy_allocated_capital_usdc(), Some(dec!(352)));
    }

    #[test]
    fn grid_rejects_outcome_prices_outside_probability_bounds() {
        let mut config = base_config("grid");
        config.markets = vec![btc_outcome_market()];
        config.grid = Some(GridConfigJson {
            mode: "long".to_string(),
            levels: 2,
            start_price: "0.50".to_string(),
            end_price: "1.20".to_string(),
            max_investment_quote: "20".to_string(),
            leverage: "1".to_string(),
            max_leverage: "1".to_string(),
            post_only: false,
            stop_loss: None,
            take_profit: None,
            trailing_up_limit: None,
            trailing_down_limit: None,
        });

        let error = match build_strategy(&config) {
            Ok(_) => panic!("outcome grid should fail bounds"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("grid.end_price"));
    }

    #[test]
    fn dca_rejects_outcome_trigger_outside_probability_bounds() {
        let mut config = base_config("dca");
        config.markets = vec![btc_outcome_market()];
        config.dca = Some(DCAConfigJson {
            direction: "long".to_string(),
            trigger_price: "1.01".to_string(),
            base_order_size: "1".to_string(),
            dca_order_size: "1".to_string(),
            max_dca_orders: 1,
            size_multiplier: "1".to_string(),
            price_deviation_pct: "1".to_string(),
            deviation_multiplier: "1".to_string(),
            take_profit_pct: "1".to_string(),
            stop_loss: None,
            leverage: "1".to_string(),
            max_leverage: "1".to_string(),
            restart_on_complete: false,
            cooldown_period_secs: 60,
        });

        let error = match build_strategy(&config) {
            Ok(_) => panic!("outcome dca should fail bounds"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("dca.trigger_price"));
    }
}