Repository navigation
Expand file tree
/
Copy pathconfig.rs
More file actions
1315 lines (1195 loc) · 54.1 KB
/
Copy pathconfig.rs
File metadata and controls
1315 lines (1195 loc) · 54.1 KB
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
use arb_common::config::merge_local_overlay;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::path::Path;
// ── SlippagePct: "max" or fixed number ────────────────────────────────────────
/// Slippage percentage: either a fixed number or "max" (use per-symbol exchange limit).
/// In TOML: `entry_slippage_pct = "max"` or `entry_slippage_pct = 5`.
#[derive(Debug, Clone, PartialEq)]
#[derive(Default)]
pub enum SlippagePct {
/// Use per-symbol limitPriceCap from exchange API (maximum allowed).
#[default]
Max,
/// Fixed percentage (e.g. 5.0 = 5%).
Fixed(f64),
}
impl SlippagePct {
pub fn is_max(&self) -> bool { matches!(self, Self::Max) }
/// Return the fixed value in %, or None if Max.
pub fn fixed_pct(&self) -> Option<f64> {
match self { Self::Fixed(v) => Some(*v), _ => None }
}
/// Resolve slippage to a fraction (e.g. 0.05 for 5%).
/// `cap` is the per-symbol exchange limit (fraction), or None if no limit.
pub fn resolve(&self, cap: Option<f64>) -> f64 {
match self {
Self::Max => {
let c = cap.unwrap_or(crate::constants::NO_CAP_SLIPPAGE_FALLBACK);
c * (1.0 - crate::constants::SLIPPAGE_CAP_MARGIN)
}
Self::Fixed(pct) => {
let frac = pct / 100.0;
match cap {
Some(c) => frac.min(c),
None => frac,
}
}
}
}
}
impl std::fmt::Display for SlippagePct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Max => write!(f, "max"),
Self::Fixed(v) => write!(f, "{v}"),
}
}
}
impl<'de> Deserialize<'de> for SlippagePct {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de;
struct V;
impl<'de> de::Visitor<'de> for V {
type Value = SlippagePct;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a number or \"max\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
if v.eq_ignore_ascii_case("max") {
Ok(SlippagePct::Max)
} else {
let pct: f64 = v.parse().map_err(de::Error::custom)?;
if pct < 0.0 { return Err(de::Error::custom("slippage must be >= 0")); }
Ok(SlippagePct::Fixed(pct))
}
}
fn visit_f64<E: de::Error>(self, v: f64) -> Result<Self::Value, E> {
if v < 0.0 { return Err(de::Error::custom("slippage must be >= 0")); }
Ok(SlippagePct::Fixed(v))
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
if v < 0 { return Err(de::Error::custom("slippage must be >= 0")); }
Ok(SlippagePct::Fixed(v as f64))
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
Ok(SlippagePct::Fixed(v as f64))
}
}
deserializer.deserialize_any(V)
}
}
impl Serialize for SlippagePct {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Max => serializer.serialize_str("max"),
Self::Fixed(v) => serializer.serialize_f64(*v),
}
}
}
#[derive(Debug, Deserialize)]
pub struct Config {
pub strategy: StrategyConfig,
pub position: PositionConfig,
pub risk: RiskConfig,
#[serde(default)]
pub bot: BotConfig,
/// Active trading pairs: which exchanges to arb between.
/// `exchanges = ["lighter", "extended"]` → all C(N,2) pairs generated.
#[serde(default)]
pub trading_pairs: TradingPairsConfig,
/// Per-exchange trading params, keyed by exchange name. E.g. [exchanges.lighter], [exchanges.extended].
/// Uses `IndexMap` so iteration order matches the TOML file's section order
/// — required for stable eid assignment across process restarts.
#[serde(default)]
pub exchanges: indexmap::IndexMap<String, ExchangeConfig>,
#[serde(default)]
pub monitoring: MonitoringConfig,
#[serde(default)]
pub telegram: TelegramConfig,
#[serde(default)]
pub startup: StartupConfig,
/// Per-exchange secrets loaded from env vars at runtime (not in TOML).
/// Keyed by exchange name (lowercase). E.g. "lighter" → LIGHTER_* env vars.
#[serde(skip)]
pub secrets: std::collections::HashMap<String, ExchangeSecrets>,
}
#[derive(Debug, Deserialize)]
pub struct StrategyConfig {
pub min_entry_spread_bps: Decimal,
pub min_exit_spread_bps: Decimal,
/// Minimum seconds between open signals for the same symbol.
#[serde(default = "default_signal_cooldown_secs")]
pub signal_cooldown_secs: f64,
/// Exit mode: "spread" (captured PnL in bps) or "pnl" (captured PnL in %).
/// Mathematically equivalent — only units differ (1% = 100 bps).
#[serde(default = "default_exit_mode")]
pub exit_mode: ExitMode,
/// Threshold as % of position notional. Used when exit_mode = "pnl".
/// NET PnL% (after fees) if include_fees_in_exit=true, GROSS otherwise. E.g. 0.05 = 0.05%.
#[serde(default)]
pub min_exit_pnl_pct: Decimal,
/// Number of consecutive exit checks that must pass before triggering close.
/// Protects against single-tick OB spikes. E.g. 3 = three consecutive ticks above target.
#[serde(default = "default_min_exit_checks")]
pub min_exit_checks: u32,
/// Deduct round-trip fees from ENTRY spread calculation.
/// When true, net_spread = gross_spread - 2*(lighter_fee + extended_fee).
/// When false, spread is gross (fees not subtracted).
#[serde(default)]
pub include_fees_in_entry: bool,
/// Deduct round-trip fees when evaluating EXIT thresholds (both spread and pnl modes).
/// When true, threshold is compared to NET value (after all fees).
/// When false, threshold is compared to GROSS value (no fee deduction).
#[serde(default = "default_include_fees_in_exit")]
pub include_fees_in_exit: bool,
/// Minimum USD on top orderbook level (ask1 for buy, bid1 for sell) on each exchange.
/// Entry signals are skipped if either side has less than this amount.
/// Protects against thin top levels that can be consumed during order flight (~300ms).
/// 0 = disabled.
#[serde(default)]
pub min_top_level_usd: f64,
/// Maximum BBO range (bps) within the spike window on any exchange.
/// Signals (entry and exit) are skipped if bid or ask range exceeds this.
/// Protects against flash crashes and stale-data phantom spreads.
/// 0 = disabled.
#[serde(default)]
pub tick_max_spike_bps: f64,
/// Rolling window (ms) for spike detection. 0 = single-tick comparison.
/// When > 0, computes max-min range over last N ms instead of prev vs cur tick.
#[serde(default)]
pub tick_spike_window_ms: f64,
/// Maximum divergence (bps) of recent public trades from the relevant BBO level
/// (bid for sell, ask for buy). Signals are skipped if any recent trade on any
/// exchange executed further than this from the BBO we'd hit.
/// Catches thin DEX books where displayed BBO doesn't reflect executable price.
/// 0 = disabled.
#[serde(default)]
pub max_trade_divergence_bps: f64,
/// Wall-clock receive-time staleness diff between the two legs (seconds).
/// Measures the gap between OUR local receive timestamps for the two legs'
/// last received frames — independent of any exchange clock. Catches the
/// case where one venue's WS goes silent while the other keeps delivering.
/// 0 = disabled.
#[serde(default)]
pub max_recv_staleness_secs: f64,
/// Tick age (milliseconds): `now() - oldest(last_exchange_ts)` across both
/// legs. Covers Tick→Recv (network latency) + Recv→Sig (local staleness) in
/// a single gate. Venues forwarding `exchange_ts = recv_ts` (e.g. ZERO1)
/// degrade automatically to Recv→Sig for that leg. 0 = disabled.
#[serde(default)]
pub max_tick_age_ms: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitMode {
Spread,
Pnl,
}
impl<'de> Deserialize<'de> for ExitMode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"spread" => Ok(ExitMode::Spread),
"pnl" => Ok(ExitMode::Pnl),
other => Err(serde::de::Error::custom(format!(
"unknown exit_mode '{other}', expected 'spread' or 'pnl'"
))),
}
}
}
fn default_exit_mode() -> ExitMode { ExitMode::Spread }
fn default_include_fees_in_exit() -> bool { true }
fn default_signal_cooldown_secs() -> f64 { 5.0 }
#[derive(Debug, Deserialize)]
pub struct PositionConfig {
pub max_order_size_usd: Decimal,
pub max_used_capital_usd: Decimal,
#[serde(default = "default_max_positions_per_symbol")]
pub max_positions_per_symbol: usize,
pub leverage: u16,
/// Asynchronous leg closing: place TP limit orders on each exchange independently.
/// When one leg's TP fills, close the other leg with market order.
#[serde(default)]
pub async_leg_close: bool,
/// Take-profit target as % of notional. Each leg targets half.
/// E.g. 0.1 = each leg aims for 0.05%, total ~0.1%.
#[serde(default)]
pub take_profit_pct: f64,
/// How long to wait for maker close on exchange_2 before falling back to taker (seconds).
#[serde(default = "default_maker_close_timeout_secs")]
pub maker_close_timeout_secs: u64,
/// Stop-loss buffer before liquidation (% of entry price).
/// E.g. 1.0 = stop-loss fires 1% before liquidation price.
#[serde(default = "default_stop_loss_buffer_pct")]
pub stop_loss_buffer_pct: f64,
#[serde(default = "default_max_open_positions")]
pub max_open_positions: usize,
/// Enable automatic SL movement when liquidation price drifts.
#[serde(default = "default_sl_movement_enabled")]
pub sl_movement_enabled: bool,
/// Minimum liq price drift (% of liq_price_at_placement) before moving SL.
/// E.g. 0.5 = move SL when liq price changed by >=0.5% from when SL was placed.
#[serde(default = "default_sl_movement_threshold_pct")]
pub sl_movement_threshold_pct: f64,
}
fn default_max_positions_per_symbol() -> usize { 1 }
fn default_min_exit_checks() -> u32 { 1 }
fn default_maker_close_timeout_secs() -> u64 { 45 }
fn default_stop_loss_buffer_pct() -> f64 { 1.0 }
fn default_max_open_positions() -> usize { 1 }
fn default_sl_movement_enabled() -> bool { true }
fn default_sl_movement_threshold_pct() -> f64 { 0.5 }
/// Bot infrastructure config — not strategy or position sizing.
#[derive(Debug, Deserialize)]
pub struct BotConfig {
/// How often to snapshot in-memory state (live PnL, spreads, positions) to DB and dashboard (seconds).
/// 0 = disabled.
#[serde(default = "default_snapshot_interval_secs")]
pub snapshot_interval_secs: u64,
/// How often to poll exchange balances via REST (seconds). 0 = only on trade events.
#[serde(default = "default_balance_refresh_interval_secs")]
pub balance_refresh_interval_secs: u64,
/// Minimum free disk space (GB) for the in-bot tick writer's cleanup. 0 = disabled.
#[serde(default = "default_min_free_disk_gb")]
pub min_free_disk_gb: f64,
/// If true, the bot itself records orderbook ticks + public funding rates
/// to `data/ticks/` and `data/funding/` (via `tick_writer_task` and
/// `funding::rates_poll`). Recorded data is byte-identical to what
/// `spread_detector` observed and is the ground truth for backtests.
#[serde(default = "default_log_ticks")]
pub log_ticks: bool,
/// If true, write observed public trades to `data/trades/<exchange>/
/// <symbol>/*.parquet` via `trade_writer_task`. Parallel to `log_ticks`
/// — same semantic, same on/off knob shape, same storage pattern.
///
/// **Scope**: this toggle controls parquet recording **only**. The
/// detector's recent-trades ring and the `signals.legs.recent_trades`
/// DB snapshot are populated unconditionally — they're part of the
/// signal observability pipeline, not user-configurable. Public trade
/// WS subscriptions always spawn at startup.
#[serde(default = "default_log_public_trades")]
pub log_public_trades: bool,
}
fn default_snapshot_interval_secs() -> u64 { 1 }
fn default_balance_refresh_interval_secs() -> u64 { 30 }
fn default_min_free_disk_gb() -> f64 { 5.0 }
fn default_log_ticks() -> bool { true }
fn default_log_public_trades() -> bool { true }
impl Default for BotConfig {
fn default() -> Self {
Self {
snapshot_interval_secs: default_snapshot_interval_secs(),
balance_refresh_interval_secs: default_balance_refresh_interval_secs(),
min_free_disk_gb: default_min_free_disk_gb(),
log_ticks: default_log_ticks(),
log_public_trades: default_log_public_trades(),
}
}
}
#[derive(Debug, Deserialize)]
pub struct RiskConfig {
pub daily_loss_limit_usd: Decimal,
/// Stop-loss order expiry in days. Lighter rejects very long expiry.
#[serde(default = "default_sl_expiry_days")]
pub sl_expiry_days: u64,
}
fn default_sl_expiry_days() -> u64 { 7 }
#[derive(Debug, Deserialize)]
pub struct MonitoringConfig {
/// Enable web dashboard (axum HTTP server with SSE).
#[serde(default = "default_web_enabled")]
pub web_enabled: bool,
/// Web dashboard bind address.
#[serde(default = "default_web_addr")]
pub web_addr: String,
}
fn default_web_enabled() -> bool { true }
fn default_web_addr() -> String { "0.0.0.0:3030".into() }
impl Default for MonitoringConfig {
fn default() -> Self {
Self {
web_enabled: default_web_enabled(),
web_addr: default_web_addr(),
}
}
}
/// Telegram notification config. Empty bot_token or chat_id = disabled.
#[derive(Debug, Deserialize)]
#[derive(Default)]
pub struct TelegramConfig {
#[serde(default)]
pub bot_token: String,
#[serde(default)]
pub chat_id: String,
}
impl TelegramConfig {
pub fn is_enabled(&self) -> bool {
!self.bot_token.is_empty() && !self.chat_id.is_empty()
}
}
/// Startup mode: how to handle existing positions on bot restart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartupMode {
/// Detect & resume hedged positions, close only orphans.
Resume,
/// Cancel all orders, close all positions (old behavior).
Clean,
}
impl<'de> Deserialize<'de> for StartupMode {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"resume" => Ok(StartupMode::Resume),
"clean" => Ok(StartupMode::Clean),
other => Err(serde::de::Error::custom(format!(
"unknown startup mode '{other}', expected 'resume' or 'clean'"
))),
}
}
}
fn default_startup_mode() -> StartupMode { StartupMode::Resume }
#[derive(Debug, Deserialize)]
pub struct StartupConfig {
/// "resume" = detect & resume hedged positions (default).
/// "clean" = cancel all, close all (old behavior).
#[serde(default = "default_startup_mode")]
pub mode: StartupMode,
}
impl Default for StartupConfig {
fn default() -> Self {
Self { mode: default_startup_mode() }
}
}
// ─── Trading pairs config ────────────────────────────────────────────────────
/// Which exchange pairs to trade. All C(N,2) pairs from the `exchanges` list
/// are generated automatically, minus any in `exclude`.
#[derive(Debug, Deserialize)]
#[derive(Default)]
pub struct TradingPairsConfig {
/// List of exchange names to trade between. All combinations generated.
/// E.g. ["lighter", "extended", "hyperliquid"] → 3 pairs.
/// Empty = trade all exchanges from [exchanges.*] sections.
#[serde(default)]
pub exchanges: Vec<String>,
/// Pairs to exclude. Each element is [exchange_1, exchange_2].
/// Order doesn't matter: ["a", "b"] == ["b", "a"].
#[serde(default)]
pub exclude: Vec<[String; 2]>,
}
impl TradingPairsConfig {
/// Resolve exchange list: if empty, use all configured exchange names.
pub fn resolve_exchanges(&self, all_configured: &[String]) -> Vec<String> {
if self.exchanges.is_empty() {
all_configured.to_vec()
} else {
self.exchanges.clone()
}
}
/// Generate all active pairs: C(N,2) minus excluded.
/// `all_configured`: exchange names from [exchanges.*] sections (fallback when exchanges list is empty).
pub fn active_pairs(&self, all_configured: &[String]) -> Vec<(String, String)> {
let exchanges = self.resolve_exchanges(all_configured);
let mut pairs = Vec::new();
let n = exchanges.len();
for i in 0..n {
for j in (i + 1)..n {
let a = &exchanges[i];
let b = &exchanges[j];
// Check exclude list (order-independent)
let excluded = self.exclude.iter().any(|ex| {
(ex[0] == *a && ex[1] == *b) || (ex[0] == *b && ex[1] == *a)
});
if !excluded {
pairs.push((a.clone(), b.clone()));
}
}
}
pairs
}
}
// ─── Exchange config (unified for all exchanges) ─────────────────────────────
/// Trading parameters for an exchange. Same struct for both Lighter and Extended.
/// Fields that don't apply to a specific exchange use sensible defaults (e.g. exit_slippage_pct=0 for Lighter).
#[derive(Debug, Clone, Deserialize)]
pub struct ExchangeConfig {
/// Whether this exchange is enabled for opening new positions.
/// `false` = spread detector skips all pairs involving this exchange.
/// Existing positions still close/SL normally. WS stays alive.
/// Hot-reloadable via web UI toggle — no restart required.
#[serde(default = "default_enabled")]
pub enabled: bool,
/// Margin mode: "isolated" or "cross".
#[serde(default = "default_margin_mode")]
pub margin_mode: String,
/// Entry order type: "ioc" (limit+IOC with slippage) or "market" (guaranteed fill).
#[serde(default = "default_entry_order_type")]
pub entry_order_type: String,
/// Entry slippage: "max" (per-symbol exchange limit) or number in % (e.g. 5 = 5%).
#[serde(default)]
pub entry_slippage_pct: SlippagePct,
/// Timeout (ms) for entry fill confirmation via WS.
#[serde(default = "default_confirmation_timeout_ms")]
pub entry_confirmation_timeout_ms: u64,
/// Timeout (ms) for exit/close fill confirmation via WS.
/// Close orders are critical (position is hedged) — shorter timeout + REST fallback.
#[serde(default = "default_exit_confirmation_timeout_ms")]
pub exit_confirmation_timeout_ms: u64,
/// Exit order type: "market", "ioc", "gtt".
#[serde(default = "default_exit_order_type")]
pub exit_order_type: String,
/// Exit slippage: "max" (per-symbol exchange limit) or number in % (e.g. 5 = 5%).
#[serde(default)]
pub exit_slippage_pct: SlippagePct,
/// Emergency slippage: "max" (per-symbol exchange limit) or number in % (e.g. 5 = 5%).
/// Used for must-fill closes: abort on failed entry, orphan cleanup, startup close-all.
#[serde(default)]
pub emergency_slippage_pct: SlippagePct,
/// Stop-loss type: "market" (guaranteed fill) or "limit" (better price, may not fill).
#[serde(default = "default_stop_loss_type")]
pub stop_loss_type: String,
/// Order expiry for GTT/stop-loss orders (seconds). Default 300 (5 min).
#[serde(default = "default_order_expiry_secs")]
pub order_expiry_secs: u64,
/// WS read timeout (seconds). If no data received at TCP level for this long, the connection
/// is considered dead and will be reconnected. Protects against silent WS hangs where the
/// server stops sending data but TCP stays alive. 0 = disabled. Default 30.
#[serde(default = "default_ws_read_timeout_secs")]
pub ws_read_timeout_secs: u64,
/// WS orderbook connection mode.
/// "single" = one connection for all markets (lower connection count, good for tick history).
/// "per_market" = one connection per traded symbol (eliminates head-of-line blocking).
#[serde(default)]
pub ws_ob_mode: WsObMode,
/// How deep to subscribe to the orderbook. `"full"` = whatever the exchange
/// sends by default (deep delta stream). `1` = top-of-book only (BBO).
/// Currently only Extended uses this: see `docs/STRATEGY_OPTIMIZE.md` §1 —
/// Extended's full-depth delta stream suffers multi-second p99 staleness,
/// while `?depth=1` gives clean ~130ms p99 SNAPSHOT frames. Other exchanges
/// ignore this field until their WS clients are updated.
#[serde(default)]
pub orderbook_depth: OrderbookDepth,
/// Which API carries signed trading actions (place/cancel/SL/close).
/// Currently honored only by Hyperliquid (the only exchange with a WS POST
/// channel). Other exchanges ignore it. Used for A/B latency testing —
/// deploy two servers with different values and compare per-leg timings.
#[serde(default)]
pub trading_api: HyperliquidTradingApi,
/// Restrict which exchanges this exchange arbs with.
/// Empty = no restriction (arbs with all enabled exchanges in trading_pairs).
/// E.g. `["lighter"]` → this exchange only looks for arb with Lighter;
/// all other pairs involving this exchange are skipped.
/// Pair (A, B) is blocked if A.allowed_with is non-empty and B ∉ A.allowed_with,
/// OR B.allowed_with is non-empty and A ∉ B.allowed_with.
#[serde(default)]
pub allowed_with: Vec<String>,
}
/// Which API carries signed trading actions on exchanges that support both
/// transports (Hyperliquid). `Ws` keeps the current behavior: WS POST first
/// with REST fallback on timeout/disconnect. `Rest` skips WS entirely.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum HyperliquidTradingApi {
#[default]
Ws,
Rest,
}
/// WS orderbook connection mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum WsObMode {
/// Single all-markets connection.
Single,
/// One WS connection per traded symbol — eliminates TCP head-of-line blocking.
#[default]
PerMarket,
}
/// How deep to subscribe to the orderbook on each exchange.
///
/// Accepts two TOML forms:
/// ```toml
/// orderbook_depth = "full" # exchange default (deep book)
/// orderbook_depth = 1 # top-of-book only
/// ```
///
/// Currently Extended is the only exchange whose client code knows how to
/// request `?depth=1` (see [`crate::exchange::extended::ws`]). Probe testing
/// confirmed Extended accepts only `1` or no `depth=` param — any other value
/// silently closes the connection. So anything that isn't literally `1` is
/// coerced to `Full` (with a warning logged on startup) rather than parsed
/// strictly — the goal is "never fail closed because of a config typo", not
/// to be pedantic about the syntax.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrderbookDepth {
Full,
Top,
}
impl Default for OrderbookDepth {
/// Struct default is deliberately `Full` (not `Top`) so that parsing a
/// TOML that omits the field entirely produces the most conservative
/// behavior — "keep the existing deep-book subscription" — rather than
/// silently switching to BBO. The shipped `config/default.toml` explicitly
/// sets `orderbook_depth = 1` for Extended so the BBO mode is live out of
/// the box despite this default.
fn default() -> Self { Self::Full }
}
impl<'de> Deserialize<'de> for OrderbookDepth {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
// Accept either a string ("full") or an integer (1). Anything else
// becomes Full with a startup warning.
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw { Str(String), Int(i64) }
match Raw::deserialize(d)? {
Raw::Str(s) if s.eq_ignore_ascii_case("full") => Ok(Self::Full),
Raw::Str(other) => {
eprintln!(
"WARNING: orderbook_depth = {other:?} not recognized, \
falling back to \"full\". Valid values: \"full\" or 1."
);
Ok(Self::Full)
}
Raw::Int(1) => Ok(Self::Top),
Raw::Int(n) => {
eprintln!(
"WARNING: orderbook_depth = {n}: Extended accepts only 1 \
or full; falling back to \"full\"."
);
Ok(Self::Full)
}
}
}
}
fn default_enabled() -> bool { true }
fn default_order_expiry_secs() -> u64 { 300 }
fn default_ws_read_timeout_secs() -> u64 { 30 }
fn default_margin_mode() -> String { "isolated".into() }
fn default_entry_order_type() -> String { "ioc".into() }
// SlippagePct defaults to Max via Default trait
fn default_confirmation_timeout_ms() -> u64 { 1500 }
fn default_exit_confirmation_timeout_ms() -> u64 { 1500 }
fn default_exit_order_type() -> String { "ioc".into() }
fn default_stop_loss_type() -> String { "ioc".into() }
impl Default for ExchangeConfig {
fn default() -> Self {
Self {
enabled: default_enabled(),
margin_mode: default_margin_mode(),
entry_order_type: default_entry_order_type(),
entry_slippage_pct: SlippagePct::Max,
entry_confirmation_timeout_ms: default_confirmation_timeout_ms(),
exit_confirmation_timeout_ms: default_exit_confirmation_timeout_ms(),
exit_order_type: default_exit_order_type(),
exit_slippage_pct: SlippagePct::Max,
emergency_slippage_pct: SlippagePct::Max,
stop_loss_type: default_stop_loss_type(),
order_expiry_secs: default_order_expiry_secs(),
ws_read_timeout_secs: default_ws_read_timeout_secs(),
ws_ob_mode: WsObMode::default(),
orderbook_depth: OrderbookDepth::default(),
trading_api: HyperliquidTradingApi::default(),
allowed_with: Vec::new(),
}
}
}
// ─── Secrets from env vars ──────────────────────────────────────────────────
/// Generic exchange secrets loaded from env vars.
/// Convention: env var `{EXCHANGE_NAME_UPPER}_{KEY_NAME}`.
/// E.g. LIGHTER_PRIVATE_KEY, EXTENDED_API_KEY, HYPERLIQUID_PRIVATE_KEY.
#[derive(Default)]
pub struct ExchangeSecrets {
values: std::collections::HashMap<String, String>,
}
impl ExchangeSecrets {
/// Load all env vars matching `{PREFIX}_*` pattern.
pub fn from_env(exchange_name: &str) -> Self {
let prefix = format!("{}_", exchange_name.to_uppercase());
let values: std::collections::HashMap<String, String> = std::env::vars()
.filter(|(k, _)| k.starts_with(&prefix))
.map(|(k, v)| (k[prefix.len()..].to_string(), v))
.collect();
Self { values }
}
/// Get a required secret. Returns error with helpful message if missing.
pub fn require(&self, key: &str) -> anyhow::Result<&str> {
self.values.get(key).map(|s| s.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing env var for key: {key}"))
}
/// Return the stored value for a key, if any. Used by credentials UI
/// to display last-4 preview of non-secret fields (e.g. account index).
pub fn peek(&self, key: &str) -> Option<&str> {
self.values.get(key).map(|s| s.as_str())
}
/// Build directly from a pre-filtered, prefix-stripped map.
/// Used by the credentials UI which reads secrets from the on-disk
/// `.env` file instead of the (potentially stale) process env.
pub fn from_map(values: std::collections::HashMap<String, String>) -> Self {
Self { values }
}
/// Insert or overwrite a single value. Used by the credentials UI to
/// splice auto-resolved fields (e.g. Extended's derived stark public key)
/// into the in-memory secrets before running the final auth check.
pub fn set(&mut self, key: &str, value: String) {
self.values.insert(key.to_string(), value);
}
}
impl std::fmt::Debug for ExchangeSecrets {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let keys: Vec<&String> = self.values.keys().collect();
f.debug_struct("ExchangeSecrets")
.field("keys", &keys)
.finish()
}
}
impl Drop for ExchangeSecrets {
fn drop(&mut self) {
for v in self.values.values_mut() {
// Zero secret memory on drop
// SAFETY: we have exclusive &mut access; no other references exist
unsafe { v.as_bytes_mut().fill(0); }
}
}
}
// ─── Combined configs for exchange modules ──────────────────────────────────
/// Everything an exchange module needs — URLs + secrets merged.
pub struct LighterConfig {
pub account_index: u64,
pub api_key_index: u64,
pub private_key_hex: String,
pub rest_url: String,
pub ws_url: String,
/// WS read timeout (seconds). 0 = disabled. Default 30.
pub ws_read_timeout_secs: u64,
/// WS orderbook connection mode (all-subs vs per-market).
pub ws_ob_mode: WsObMode,
/// Full L2 via `order_book/{mid}` vs BBO via `ticker/{mid}`. BBO
/// bypasses Lighter's 50ms order_book batching. Probe evidence:
/// docs/STRATEGY_OPTIMIZE.md §2.
pub orderbook_depth: OrderbookDepth,
}
/// Combined config for the zero1 (01.xyz / N1) exchange.
///
/// `keypair_b58` and `keypair_path` are mutually-exclusive — set exactly
/// one in the `[secrets.zero1]` env block. Same convention as Lighter:
/// `ZERO1_KEYPAIR_B58=<base58>` (Phantom export) **or**
/// `ZERO1_KEYPAIR_PATH=/abs/path/id.json` (Solana CLI keypair file).
///
/// `account_id` is the engine-side `u32` returned by
/// `GET /user/{pubkey}.account_ids` after the operator's first deposit.
/// Look it up via `cargo test --test tools -- zero1_poke ...` and add it
/// to `.env` as `ZERO1_ACCOUNT_ID=<id>`.
pub struct Zero1Config {
/// Base58-encoded Solana secret key (Phantom "Show Private Key" output).
/// Empty if `keypair_path` is used instead.
pub keypair_b58: String,
/// Filesystem path to a Solana CLI JSON keypair file (`solana-keygen new`).
/// Empty if `keypair_b58` is used instead.
pub keypair_path: String,
/// Engine-side account id (uint32). Required.
pub account_id: u32,
/// REST base URL — `https://zo-mainnet.n1.xyz` for production.
pub rest_url: String,
/// WS base URL — `wss://zo-mainnet.n1.xyz/ws` (multi-stream paths
/// are appended at runtime by `zero1/ws.rs`).
pub ws_url: String,
/// WS read timeout (seconds). 0 = disabled.
pub ws_read_timeout_secs: u64,
/// WS orderbook connection mode (all-markets batched vs per-market).
pub ws_ob_mode: WsObMode,
}
/// Hyperliquid exchange configuration.
///
/// Three keys in `.env`:
/// `HYPERLIQUID_API_PRIVATE_KEY=0x...` — agent (API) wallet private key
/// `HYPERLIQUID_API_WALLET_ADDRESS=0x...` — agent wallet address (cross-check)
/// `HYPERLIQUID_ACCOUNT_ADDRESS=0x...` — main account address (owner wallet)
///
/// Agent wallet signs all trading actions (orders, cancel, leverage).
/// Agent wallet address is validated at startup: must match the address
/// derived from the private key. Prevents silent misconfiguration.
/// Account address is the main wallet where deposits/positions/balances live —
/// used for read-only queries (`clearinghouseState`, `userFees`, `openOrders`,
/// WS `userFills`/`orderUpdates` subscriptions, etc.).
pub struct HyperliquidConfig {
/// Hex-encoded secp256k1 private key of the agent (API) wallet.
pub api_private_key: String,
/// Agent wallet address (0x...). Validated against derived address at startup.
pub api_wallet_address: String,
/// Main account address (0x...). Owner wallet where positions live.
pub account_address: String,
/// REST base URL — `https://api.hyperliquid.xyz` for production.
pub rest_url: String,
/// WS URL — `wss://api.hyperliquid.xyz/ws`.
pub ws_url: String,
/// WS read timeout (seconds). 0 = disabled.
pub ws_read_timeout_secs: u64,
/// WS orderbook connection mode.
pub ws_ob_mode: WsObMode,
/// Transport for signed trading actions. See [`HyperliquidTradingApi`].
pub trading_api: HyperliquidTradingApi,
}
/// Bybit V5 USDT Linear Perpetuals exchange configuration.
///
/// Two keys in `.env`:
/// `BYBIT_API_KEY=<your unified API key>`
/// `BYBIT_API_SECRET=<your API secret>`
///
/// Both authenticate REST (HMAC-SHA256 over `{ts}{api_key}{recv_window}{params}`)
/// and the private/trade WS streams (HMAC over `GET/realtime{expires_ms}`).
pub struct BybitConfig {
pub api_key: String,
pub api_secret: String,
/// REST base URL — `https://api.bybit.com` for production.
pub rest_url: String,
/// Public OB stream — `wss://stream.bybit.com/v5/public/linear`.
pub ws_public_url: String,
/// Private account stream (executions / positions / orders).
pub ws_private_url: String,
/// Trade WS — write-only `order.create` / `order.cancel` channel.
pub ws_trade_url: String,
/// WS read timeout (seconds). 0 = disabled.
pub ws_read_timeout_secs: u64,
}
pub struct ExtendedConfig {
pub api_key: String,
pub stark_private_key_hex: String,
pub stark_public_key_hex: String,
pub vault_id: String,
pub rest_url: String,
pub ws_orderbook_url: String,
pub ws_account_url: String,
/// Public trades stream base URL. Per-market connections append `/{market}`
/// to this (e.g. `.../v1/publicTrades/BTC-USD`). Always populated from
/// `arb_common::constants::EXTENDED_WS_PUBLIC_TRADES_URL` — kept as a
/// field (rather than referenced directly) so the Config struct remains
/// the single source of URL values for per-exchange clients.
pub ws_public_trades_url: String,
/// Emergency close slippage: "max" (per-symbol exchange limit) or number in %.
/// Initial value from config. Live updates go through ExchangeClient::update_emergency_slippage().
pub emergency_slippage_pct: SlippagePct,
/// Symbol aliases: maps API names to canonical names (e.g., CL → WTI).
/// Loaded from exchange_symbol_overrides DB at build time.
pub symbol_aliases: std::collections::HashMap<String, String>,
/// WS read timeout (seconds). 0 = disabled.
pub ws_read_timeout_secs: u64,
/// WS orderbook connection mode (all-markets vs per-market).
pub ws_ob_mode: WsObMode,
/// See `ExchangeConfig::orderbook_depth`.
pub orderbook_depth: OrderbookDepth,
}
// Manual `Debug` for the merged exchange configs: they carry plaintext private
// keys / API secrets, so a stray `{:?}` (log line, Telegram error, panic
// message) must never print them. Non-secret fields (URLs, public addresses,
// ids, timeouts) are shown to keep the output useful for diagnostics. Mirrors
// the redacting `Debug` on `ExchangeSecrets`.
impl std::fmt::Debug for LighterConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LighterConfig")
.field("account_index", &self.account_index)
.field("api_key_index", &self.api_key_index)
.field("private_key_hex", &"<redacted>")
.field("rest_url", &self.rest_url)
.field("ws_url", &self.ws_url)
.field("ws_read_timeout_secs", &self.ws_read_timeout_secs)
.field("ws_ob_mode", &self.ws_ob_mode)
.field("orderbook_depth", &self.orderbook_depth)
.finish()
}
}
impl std::fmt::Debug for Zero1Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Zero1Config")
.field("keypair_b58", &"<redacted>")
.field("keypair_path", &self.keypair_path)
.field("account_id", &self.account_id)
.field("rest_url", &self.rest_url)
.field("ws_url", &self.ws_url)
.field("ws_read_timeout_secs", &self.ws_read_timeout_secs)
.field("ws_ob_mode", &self.ws_ob_mode)
.finish()
}
}
impl std::fmt::Debug for HyperliquidConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HyperliquidConfig")
.field("api_private_key", &"<redacted>")
.field("api_wallet_address", &self.api_wallet_address)
.field("account_address", &self.account_address)
.field("rest_url", &self.rest_url)
.field("ws_url", &self.ws_url)
.field("ws_read_timeout_secs", &self.ws_read_timeout_secs)
.field("ws_ob_mode", &self.ws_ob_mode)
.field("trading_api", &self.trading_api)
.finish()
}
}
impl std::fmt::Debug for BybitConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BybitConfig")
.field("api_key", &"<redacted>")
.field("api_secret", &"<redacted>")
.field("rest_url", &self.rest_url)
.field("ws_public_url", &self.ws_public_url)
.field("ws_private_url", &self.ws_private_url)
.field("ws_trade_url", &self.ws_trade_url)
.field("ws_read_timeout_secs", &self.ws_read_timeout_secs)
.finish()
}
}
impl std::fmt::Debug for ExtendedConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExtendedConfig")
.field("api_key", &"<redacted>")
.field("stark_private_key_hex", &"<redacted>")
.field("stark_public_key_hex", &self.stark_public_key_hex)
.field("vault_id", &self.vault_id)
.field("rest_url", &self.rest_url)
.field("ws_orderbook_url", &self.ws_orderbook_url)
.field("ws_account_url", &self.ws_account_url)
.field("ws_public_trades_url", &self.ws_public_trades_url)
.field("emergency_slippage_pct", &self.emergency_slippage_pct)
.field("symbol_aliases", &self.symbol_aliases)
.field("ws_read_timeout_secs", &self.ws_read_timeout_secs)
.field("ws_ob_mode", &self.ws_ob_mode)
.field("orderbook_depth", &self.orderbook_depth)
.finish()
}
}
impl Config {
pub fn load(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let path = path.as_ref();
let content = std::fs::read_to_string(path)?;
let mut value: toml::Value = toml::from_str(&content)?;
// Apply config/local.toml overlay (local overrides, not in git)
if let Some(dir) = path.parent() {
merge_local_overlay(&mut value, dir.join("local.toml"));
}
let mut config: Config = value.try_into()?;
// Load secrets from env vars for each configured exchange
let exchange_names: Vec<String> = config.exchanges.keys().cloned().collect();
for name in &exchange_names {
config.secrets.insert(name.clone(), ExchangeSecrets::from_env(name));
}
config.enforce_exchange_limits();
Ok(config)
}
/// Clamp fixed slippage values to hard exchange limits. "max" is not clamped here —
/// it resolves to per-symbol limitPriceCap at order time.
fn enforce_exchange_limits(&mut self) {
use crate::constants::EXTENDED_MAX_SLIPPAGE_PCT;
if let Some(ext) = self.exchanges.get_mut("extended") {
let max = EXTENDED_MAX_SLIPPAGE_PCT;
let fields: &mut [(&str, &mut SlippagePct)] = &mut [
("entry_slippage_pct", &mut ext.entry_slippage_pct),
("exit_slippage_pct", &mut ext.exit_slippage_pct),
("emergency_slippage_pct", &mut ext.emergency_slippage_pct),
];
for (name, val) in fields {
if let SlippagePct::Fixed(v) = val
&& *v > max {
eprintln!(
"WARNING: exchanges.extended.{name} = {v}% exceeds min exchange limit ({max}%), clamped to {max}%",
);
*v = max;
}
}
}
}
/// Access exchange trading config by name. Returns default if not configured.
pub fn exchange_config(&self, name: &str) -> &ExchangeConfig {
static DEFAULT: std::sync::LazyLock<ExchangeConfig> = std::sync::LazyLock::new(ExchangeConfig::default);
self.exchanges.get(name).unwrap_or(&DEFAULT)
}
/// Configured exchange names in canonical order — exactly the order in
/// which `[exchanges.X]` sections appear in `default.toml`. Stable across
/// process restarts because `Config.exchanges` is an `IndexMap` (std
/// HashMap would randomize per-process iteration order, which would
/// shuffle eid assignment and produce non-reproducible behavior).
///
/// Used as the default exchange list for backtest UI initialization
/// (see `bot/src/web/backtest.rs::api_backtest_config`) and anywhere
/// else that needs "all exchanges this bot is configured to trade".
pub fn configured_exchange_names(&self) -> Vec<String> {
self.exchanges.keys().cloned().collect()
}
/// Access exchange secrets by name.
pub fn exchange_secrets(&self, name: &str) -> Option<&ExchangeSecrets> {