longtrader-worker 0.2.1

Local strategy host running portable strategies against pluggable backends (exchange daemon / terminal API / mock)
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
use std::path::Path;

use color_eyre::{Result, eyre::WrapErr};
use rust_decimal::Decimal;
use serde::Deserialize;

/// Reject unknown keys, so a removed or misspelled setting is a startup error
/// rather than a silent fallback. This matters most for the keys that were
/// removed when the single-representation contract landed: a config still
/// carrying `api_endpoint` used to override the backend selection, and without
/// this attribute it would parse cleanly and quietly connect somewhere else.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Legacy sibling-repo key, intentionally ignored by this worker.
    /// Kept optional for backward compatibility: old configs still parse,
    /// new configs should omit it.
    #[serde(default)]
    pub daemon_endpoint: String,
    /// Endpoint the remote backend talks to. Only consulted when `backend` is
    /// the remote one; `backend = "mock"` ignores it.
    #[serde(default)]
    pub endpoint: Option<String>,
    /// Optional path to a file containing the terminal API token.
    #[serde(default)]
    pub api_token_file: Option<String>,
    /// Deprecated: the real kill-switch is `worker.v1.KillSwitchPolicy`
    /// (see `SessionPolicy` / `apply_policy`). This boolean is parsed for
    /// backward compatibility but never read; setting it has no effect.
    #[serde(default)]
    pub kill_switch_on_disconnect: Option<bool>,
    /// Backend selection: `"api"` (the unified `longtrader.{market,trading}.v1`
    /// services, reached over Connect) or `"mock"` (in-process, offline
    /// dry-run). Defaults to `"api"`.
    #[serde(default)]
    pub backend: Option<String>,
    /// Optional bind address for the control-plane RPC server
    /// (`WorkerSessionService` + unified trading/market proxies).
    #[serde(default)]
    pub listen_endpoint: Option<String>,
    /// Optional pre-trade risk gate. Absent (or all-`None`) means every
    /// submission reaches the venue unmeasured — see [`crate::risk`].
    #[serde(default)]
    pub risk: RiskConfig,
    pub strategy: StrategyConfig,
}

/// The `[risk]` table: one optional limit per row, `None` meaning "not
/// enforced". Quantities are `rust_decimal` decimals, written as strings like
/// every other decimal in this config so a limit is exact.
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct RiskConfig {
    #[serde(default)]
    pub max_order_qty: Option<Decimal>,
    #[serde(default)]
    pub max_order_notional: Option<Decimal>,
    #[serde(default)]
    pub max_orders_per_minute: Option<u32>,
    #[serde(default)]
    pub max_open_orders: Option<u32>,
    #[serde(default)]
    pub max_net_qty_per_symbol: Option<Decimal>,
}

impl RiskConfig {
    /// The gate's view of these limits.
    #[must_use]
    pub const fn limits(&self) -> crate::risk::RiskLimits {
        crate::risk::RiskLimits {
            max_order_qty: self.max_order_qty,
            max_order_notional: self.max_order_notional,
            max_orders_per_minute: self.max_orders_per_minute,
            max_open_orders: self.max_open_orders,
            max_net_qty_per_symbol: self.max_net_qty_per_symbol,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct StrategyConfig {
    #[serde(rename = "type")]
    pub strategy_type: String,
    #[serde(default)]
    pub params: StrategyParams,
}

/// The on-file shape of [`StrategyParams`], before the well-known keys are
/// merged back into the catch-all table.
#[derive(Deserialize)]
struct StrategyParamsWire {
    #[serde(default)]
    exchange_id: Option<String>,
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    symbol: Option<String>,
    #[serde(default)]
    lower_price: Option<Decimal>,
    #[serde(default)]
    upper_price: Option<Decimal>,
    #[serde(default)]
    num_levels: Option<u32>,
    #[serde(default)]
    qty_per_level: Option<Decimal>,
    #[serde(flatten)]
    extra: toml::Table,
}

impl<'de> Deserialize<'de> for StrategyParams {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        let wire = StrategyParamsWire::deserialize(de)?;
        let mut params = Self {
            exchange_id: wire.exchange_id,
            label: wire.label,
            symbol: wire.symbol,
            lower_price: wire.lower_price,
            upper_price: wire.upper_price,
            num_levels: wire.num_levels,
            qty_per_level: wire.qty_per_level,
            extra: wire.extra,
        };
        params.merge_known_keys();
        Ok(params)
    }
}

/// Render a decimal as a TOML string.
///
/// A string (not a float) is deliberate: a config that round-trips through
/// `f64` would lose precision on a price, and every strategy parses these back
/// as `Decimal`.
fn decimal_value(v: Decimal) -> toml::Value {
    toml::Value::String(v.normalize().to_string())
}

#[derive(Debug, Clone, Default)]
pub struct StrategyParams {
    pub exchange_id: Option<String>,
    pub label: Option<String>,
    pub symbol: Option<String>,
    pub lower_price: Option<Decimal>,
    pub upper_price: Option<Decimal>,
    pub num_levels: Option<u32>,
    pub qty_per_level: Option<Decimal>,
    /// Catch-all for strategy-specific parameters (strategy-specific keys). Each
    /// strategy deserializes its own config struct from this table. Also
    /// carries the well-known keys above, merged in by [`Deserialize`] — see
    /// [`StrategyParams::table`].
    pub extra: toml::Table,
}

impl StrategyParams {
    /// The full parameter table a strategy deserializes its config from.
    ///
    /// This is the *merged* view: the well-known keys serde consumed
    /// (`symbol`, `exchange_id`, `label`, the grid bounds) are written back
    /// into `extra` by [`Deserialize`], so a strategy's own config struct sees
    /// everything the file declared. Returning the catch-all alone silently
    /// dropped every well-known key, so the documented
    /// `[strategy.params] symbol = "..."` never reached a strategy and any
    /// strategy requiring a symbol failed at startup with "missing field".
    pub const fn table(&self) -> &toml::Table {
        &self.extra
    }

    /// Merge the well-known keys back into the catch-all table.
    fn merge_known_keys(&mut self) {
        // An explicit `extra` entry wins: it is the more specific source, and
        // serde cannot have produced a collision here from a real document.
        let put = |table: &mut toml::Table, key: &str, value: toml::Value| {
            table.entry(key).or_insert(value);
        };
        if let Some(v) = self.exchange_id.clone() {
            put(&mut self.extra, "exchange_id", toml::Value::String(v));
        }
        if let Some(v) = self.label.clone() {
            put(&mut self.extra, "label", toml::Value::String(v));
        }
        if let Some(v) = self.symbol.clone() {
            put(&mut self.extra, "symbol", toml::Value::String(v));
        }
        if let Some(v) = self.lower_price {
            put(&mut self.extra, "lower_price", decimal_value(v));
        }
        if let Some(v) = self.upper_price {
            put(&mut self.extra, "upper_price", decimal_value(v));
        }
        if let Some(v) = self.num_levels {
            put(&mut self.extra, "num_levels", toml::Value::Integer(i64::from(v)));
        }
        if let Some(v) = self.qty_per_level {
            put(&mut self.extra, "qty_per_level", decimal_value(v));
        }
    }

    /// Venue identifier string, defaulting to `"mock"`.
    pub fn venue(&self) -> &str {
        self.exchange_id.as_deref().unwrap_or("mock")
    }

    /// Optional sub-account label.
    pub fn venue_label(&self) -> &str {
        self.label.as_deref().unwrap_or_default()
    }
}

impl Config {
    /// The configured backend, defaulting to `"api"`.
    ///
    /// There is nothing to resolve: one selector picks one backend. An unset or
    /// blank value is the default rather than an error, so an operator who omits
    /// the key gets the real backend instead of a startup failure.
    pub fn backend(&self) -> &str {
        self.backend.as_deref().map(str::trim).filter(|b| !b.is_empty()).unwrap_or("api")
    }

    /// Backend after whitelist validation (`"api"` or `"mock"` only).
    /// Rejects typos at config-load time instead of at runtime dispatch.
    pub fn validated_backend(&self) -> Result<&str> {
        match self.backend() {
            backend @ ("api" | "mock") => Ok(backend),
            other => {
                Err(color_eyre::eyre::eyre!("unknown backend: {other} (expected 'mock' or 'api')"))
            }
        }
    }

    /// The endpoint the remote backend should use.
    pub fn endpoint_or_default(&self, default: &str) -> String {
        self.endpoint.clone().unwrap_or_else(|| default.to_string())
    }

    /// Terminal API token loaded from `api_token_file`.
    ///
    /// Fail-fast lives here, with the loader, not at each call site: a
    /// configured token file that is missing, unreadable or empty means the
    /// worker would otherwise come up **unauthenticated**, and a future call
    /// site that forgets the empty check would silently run that way. An unset
    /// `api_token_file` is the deliberate local-dev case and yields an empty
    /// token without an error.
    ///
    /// # Errors
    ///
    /// Returns an error when the configured file cannot be read or holds only
    /// whitespace.
    pub fn api_token(&self) -> Result<String> {
        let Some(path) = self.api_token_file.as_deref() else {
            return Ok(String::new());
        };
        let raw = std::fs::read_to_string(path)
            .wrap_err_with(|| format!("failed to read api_token_file {path}"))?;
        let token = raw.trim().to_string();
        if token.is_empty() {
            return Err(color_eyre::eyre::eyre!(
                "api_token_file {path} is empty; refusing to start unauthenticated"
            ));
        }
        Ok(token)
    }

    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let contents = std::fs::read_to_string(path)
            .wrap_err_with(|| format!("failed to read config file: {}", path.display()))?;
        let config: Self = toml::from_str(&contents)
            .wrap_err_with(|| format!("failed to parse config file: {}", path.display()))?;
        // Fail fast on typos: an unknown backend can never run, so reject it
        // here rather than at runtime dispatch in `main`.
        config
            .validated_backend()
            .wrap_err_with(|| format!("invalid config file: {}", path.display()))?;
        if config.kill_switch_on_disconnect.is_some() {
            tracing::warn!(
                "config `kill_switch_on_disconnect` is deprecated and ignored; \
                 configure `worker.v1.KillSwitchPolicy` instead"
            );
        }
        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;
    use rust_decimal_macros::dec;

    use super::*;

    /// Parse a config the way the README documents it.
    fn parse(params_toml: &str) -> StrategyParams {
        let doc = format!(
            "daemon_endpoint = \"http://127.0.0.1:8810\"\n[strategy]\ntype = \"simple_grid\"\n[strategy.params]\n{params_toml}\n"
        );
        let config: Config = toml::from_str(&doc).expect("config parses");
        config.strategy.params
    }

    /// The well-known keys serde consumed must be written back into the table a
    /// strategy deserializes from. Before this merge, `table()` returned only
    /// the catch-all, so the documented `[strategy.params] symbol = "..."` never
    /// reached a strategy and every symbol-requiring strategy failed at
    /// startup with "missing field `symbol`".
    #[test]
    fn well_known_keys_reach_the_strategy_table() {
        let params = parse(
            "symbol = \"BTCUSDT\"\nexchange_id = \"binance\"\nnum_levels = 7\nlower_price = \"90000\"\nqty_per_level = \"0.001\"\n",
        );
        let table = params.table();
        assert_eq!(table.get("symbol").and_then(toml::Value::as_str), Some("BTCUSDT"));
        assert_eq!(table.get("exchange_id").and_then(toml::Value::as_str), Some("binance"));
        assert_eq!(table.get("num_levels").and_then(toml::Value::as_integer), Some(7));
        // Decimals round-trip as strings, so a price never loses precision by
        // passing through `f64`.
        assert_eq!(table.get("lower_price").and_then(toml::Value::as_str), Some("90000"));
        assert_eq!(table.get("qty_per_level").and_then(toml::Value::as_str), Some("0.001"));
    }

    #[test]
    fn strategy_specific_keys_survive_the_merge() {
        let params = parse("symbol = \"BTCUSDT\"\nfunding_rate_threshold = \"0.0005\"\n");
        assert_eq!(
            params.table().get("funding_rate_threshold").and_then(toml::Value::as_str),
            Some("0.0005")
        );
    }

    /// The whole point of the merge: a strategy's own config struct must
    /// deserialize from the table the file produced.
    #[test]
    fn a_strategy_config_deserializes_from_the_merged_table() {
        #[derive(serde::Deserialize)]
        struct GridConfig {
            symbol: String,
            num_levels: u32,
            qty_per_level: Decimal,
        }
        let params = parse(
            "symbol = \"BTCUSDT\"\nexchange_id = \"mock\"\nnum_levels = 5\nqty_per_level = \"0.001\"\n",
        );
        let cfg: GridConfig = toml::Value::Table(params.table().clone())
            .try_into()
            .expect("the documented config must deserialize");
        assert_eq!(cfg.symbol, "BTCUSDT");
        assert_eq!(cfg.num_levels, 5);
        assert_eq!(cfg.qty_per_level, dec!(0.001));
    }

    /// An absent well-known key must stay absent rather than materialise as a
    /// zero: a strategy that treats `num_levels = 0` as "use the default" would
    /// otherwise silently get a different code path from "not specified".
    #[test]
    fn absent_well_known_keys_stay_absent() {
        let params = parse("symbol = \"BTCUSDT\"\n");
        assert!(!params.table().contains_key("num_levels"));
        assert!(!params.table().contains_key("lower_price"));
        assert!(!params.table().contains_key("label"));
    }

    /// The accessors keep working off the typed fields, and still default.
    #[test]
    fn venue_accessor_defaults_to_mock() {
        assert_eq!(parse("symbol = \"X\"\n").venue(), "mock");
        assert_eq!(parse("symbol = \"X\"\nexchange_id = \"htx\"\n").venue(), "htx");
    }

    // -----------------------------------------------------------------------
    // backend selection
    // -----------------------------------------------------------------------

    fn full_config(doc: &str) -> Config {
        // `doc` holds **top-level** keys, so it must be emitted before the
        // `[strategy]` table: a key written after a table header belongs to that
        // table, and `Config` would silently never see it.
        let body = format!(
            "daemon_endpoint = \"http://127.0.0.1:8810\"\n{doc}\n[strategy]\ntype = \"simple_grid\"\n"
        );
        toml::from_str(&body).expect("config parses")
    }

    /// The configured backend is used verbatim for the two supported names.
    /// Unknown names are rejected by `validated_backend()` at load time.
    #[test]
    fn an_explicit_backend_is_used_verbatim() {
        assert_eq!(full_config("backend = \"api\"\n").backend(), "api");
        assert_eq!(full_config("backend = \"mock\"\n").backend(), "mock");
        assert!(full_config("backend = \"api\"\n").validated_backend().is_ok());
        assert!(full_config("backend = \"mock\"\n").validated_backend().is_ok());
    }

    /// Unknown backends fail fast at load time instead of at runtime dispatch.
    #[test]
    fn an_unknown_backend_is_rejected_by_validation() {
        // Only the exact lowercase names pass: the whitelist is case-sensitive
        // so a typo like "API" cannot silently select a backend.
        for backend in ["custom", "daemon", "API", "Mock ", ""] {
            let config = full_config(&format!("backend = \"{backend}\"\n"));
            if backend.trim().is_empty() {
                assert!(config.validated_backend().is_ok(), "blank falls back to api");
            } else {
                assert!(config.validated_backend().is_err(), "{backend} must be rejected");
            }
        }
    }

    /// An empty or blank value is a config mistake, not a backend. Falling back
    /// to the real one beats starting a worker that cannot connect.
    #[test]
    fn an_absent_or_blank_backend_falls_back_to_api() {
        assert_eq!(full_config("").backend(), "api");
        assert_eq!(full_config("backend = \"\"\n").backend(), "api");
        assert_eq!(full_config("backend = \"  \"\n").backend(), "api", "blank is trimmed");
        assert_eq!(full_config("backend = \" mock \"\n").backend(), "mock", "and so is a name");
    }

    /// The endpoint is a plain URL with no effect on which backend runs.
    #[test]
    fn an_endpoint_does_not_choose_the_backend() {
        let config = full_config("endpoint = \"http://api:9000\"\n");
        assert_eq!(config.backend(), "api", "an endpoint is not a backend selector");
        assert_eq!(config.endpoint_or_default("fallback"), "http://api:9000");
    }

    /// The `api_endpoint` key is gone. A config still carrying it must fail
    /// loudly rather than parse cleanly and quietly connect to the default
    /// endpoint — the override it used to provide cannot be honoured, and
    /// silently ignoring it points the worker at the wrong host.
    #[test]
    fn a_removed_api_endpoint_key_is_rejected_rather_than_ignored() {
        let err = toml::from_str::<Config>(
            "daemon_endpoint = \"http://x:1\"\napi_endpoint = \"http://internal:9000\"\n\
             [strategy]\ntype = \"simple_grid\"\n",
        )
        .expect_err("a removed key must not be silently dropped");
        let message = err.to_string();
        assert!(
            message.contains("api_endpoint"),
            "the error must name the offending key so the operator knows what to fix: {message}"
        );
    }

    /// A misspelled key is the same hazard: it silently vanishes and the worker
    /// runs against the default endpoint with no indication why.
    #[test]
    fn a_misspelled_endpoint_key_is_rejected() {
        // Assembled at runtime: the point is that *some* unknown key is
        // reported, and spelling a real typo literally would trip `typos`.
        let typo = ["end", "pi", "ont"].join("");
        let err = toml::from_str::<Config>(&format!(
            "daemon_endpoint = \"http://x:1\"\n{typo} = \"http://typo:9000\"\n\
             [strategy]\ntype = \"simple_grid\"\n"
        ))
        .expect_err("an unknown key must be reported");
        assert!(err.to_string().contains(&typo), "{err}");
    }

    #[test]
    fn an_absent_endpoint_falls_back_to_the_default() {
        assert_eq!(full_config("").endpoint_or_default("http://fallback"), "http://fallback");
    }

    // -----------------------------------------------------------------------
    // api_token
    // -----------------------------------------------------------------------

    #[test]
    fn an_unset_token_file_yields_an_empty_token() {
        assert!(full_config("").api_token().expect("unset is not an error").is_empty());
    }

    /// A token file usually ends in a newline from `echo`; the whitespace must
    /// not be sent as part of the bearer credential.
    #[test]
    fn a_token_file_is_trimmed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("token");
        std::fs::write(&path, "  secret-token\n").expect("write");
        let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
        assert_eq!(config.api_token().expect("readable token"), "secret-token");
    }

    /// A missing or unreadable secret file must fail startup rather than
    /// degrade to an empty token: an unauthenticated worker is a worse outcome
    /// than a worker that refuses to boot.
    #[test]
    fn an_unreadable_token_file_is_an_error() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("absent");
        let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
        let err = config.api_token().expect_err("an unreadable token file must fail");
        assert!(err.to_string().contains("api_token_file"), "got {err}");
    }

    /// Whitespace-only is the same misconfiguration as empty: the file exists
    /// but carries no credential.
    #[test]
    fn a_whitespace_only_token_file_is_an_error() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("token");
        std::fs::write(&path, "\n\t  \n").expect("write");
        let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
        let err = config.api_token().expect_err("an empty token file must fail");
        assert!(err.to_string().contains("empty"), "got {err}");
    }

    // -----------------------------------------------------------------------
    // Config::load
    // -----------------------------------------------------------------------

    #[test]
    fn load_reads_a_valid_config_off_disk() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("worker.toml");
        std::fs::write(
            &path,
            "daemon_endpoint = \"http://127.0.0.1:8810\"\nkill_switch_on_disconnect = true\nlisten_endpoint = \"127.0.0.1:0\"\n[strategy]\ntype = \"ema_cross\"\n[strategy.params]\nsymbol = \"BTC/USDT\"\n",
        )
        .expect("write");
        let config = Config::load(&path).expect("loads");
        assert_eq!(config.daemon_endpoint, "http://127.0.0.1:8810");
        assert_eq!(config.kill_switch_on_disconnect, Some(true));
        assert_eq!(config.listen_endpoint.as_deref(), Some("127.0.0.1:0"));
        assert_eq!(config.strategy.strategy_type, "ema_cross");
        assert_eq!(config.strategy.params.symbol.as_deref(), Some("BTC/USDT"));
    }

    /// A missing file is reported with its path so the operator knows which one.
    #[test]
    fn load_reports_a_missing_file_with_its_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("nope.toml");
        let err = Config::load(&path).expect_err("missing file");
        let message = err.to_string();
        assert!(message.contains("failed to read config file"), "{message}");
        assert!(message.contains("nope.toml"), "{message}");
    }

    #[test]
    fn load_reports_malformed_toml_with_its_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("bad.toml");
        std::fs::write(&path, "this is not = = toml\n").expect("write");
        let err = Config::load(&path).expect_err("malformed");
        let message = err.to_string();
        assert!(message.contains("failed to parse config file"), "{message}");
        assert!(message.contains("bad.toml"), "{message}");
    }

    /// `daemon_endpoint` is legacy and optional; only `strategy.type` is
    /// required. A config missing the strategy still fails naming it.
    #[test]
    fn load_rejects_a_config_missing_a_required_field() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("partial.toml");
        // Legacy key omitted entirely: loads fine with an empty default.
        std::fs::write(&path, "[strategy]\ntype = \"ema_cross\"\n").expect("write");
        let config = Config::load(&path).expect("daemon_endpoint is optional legacy");
        assert!(config.daemon_endpoint.is_empty());
        assert_eq!(config.strategy.strategy_type, "ema_cross");

        std::fs::write(&path, "daemon_endpoint = \"http://x\"\n").expect("write");
        let err = Config::load(&path).expect_err("missing strategy");
        let chain = format!("{err:?}");
        assert!(chain.contains("strategy"), "{chain}");
    }

    /// An unknown backend is rejected at load time with its name in the error.
    #[test]
    fn load_rejects_an_unknown_backend() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("bad-backend.toml");
        std::fs::write(&path, "backend = \"custom\"\n[strategy]\ntype = \"simple_grid\"\n")
            .expect("write");
        let err = Config::load(&path).expect_err("unknown backend must fail load");
        let chain = format!("{err:?}");
        assert!(chain.contains("custom"), "{chain}");
    }

    // -----------------------------------------------------------------------
    // risk gate
    // -----------------------------------------------------------------------

    /// A config with `[risk]` as a top-level table, before `[strategy]`.
    fn config_with_risk(risk_toml: &str) -> Config {
        let body = format!(
            "daemon_endpoint = \"http://127.0.0.1:8810\"\n{risk_toml}\n\
             [strategy]\ntype = \"simple_grid\"\n"
        );
        toml::from_str(&body).expect("config parses")
    }

    /// The gate is off by default: a config that never mentions `[risk]` must
    /// behave exactly as it did before the gate existed.
    #[test]
    fn an_absent_risk_section_leaves_the_gate_disabled() {
        let config = full_config("");
        assert!(!config.risk.limits().is_enabled());
        assert!(!config.risk.limits().needs_book());
    }

    /// The documented `[risk]` table parses into the limits the gate enforces.
    /// Decimals arrive as strings, so a quantity never passes through `f64`.
    #[test]
    fn a_documented_risk_section_parses_into_limits() {
        let config = config_with_risk(
            "[risk]\nmax_order_qty = \"1\"\nmax_order_notional = \"50000\"\n\
             max_orders_per_minute = 120\nmax_open_orders = 200\n\
             max_net_qty_per_symbol = \"5\"\n",
        );
        let limits = config.risk.limits();
        assert!(limits.is_enabled());
        assert!(limits.needs_book());
        assert_eq!(limits.max_order_qty, Some(dec!(1)));
        assert_eq!(limits.max_order_notional, Some(dec!(50000)));
        assert_eq!(limits.max_orders_per_minute, Some(120));
        assert_eq!(limits.max_open_orders, Some(200));
        assert_eq!(limits.max_net_qty_per_symbol, Some(dec!(5)));
    }

    /// A limit is opt-in per row: setting one must not silently arm the others,
    /// and a local-only section must not make the gate pay for a book read.
    #[test]
    fn unset_risk_limits_stay_unset() {
        let config = config_with_risk("[risk]\nmax_order_qty = \"1\"\n");
        let limits = config.risk.limits();
        assert_eq!(limits.max_order_qty, Some(dec!(1)));
        assert_eq!(limits.max_order_notional, None);
        assert_eq!(limits.max_orders_per_minute, None);
        assert_eq!(limits.max_open_orders, None);
        assert_eq!(limits.max_net_qty_per_symbol, None);
        assert!(limits.is_enabled());
        assert!(!limits.needs_book());
    }

    /// An empty `[risk]` table is a pass-through, not an error: an operator who
    /// adds the header first and fills it in later must not break startup.
    #[test]
    fn an_empty_risk_section_is_a_pass_through() {
        let config = config_with_risk("[risk]\n");
        assert!(!config.risk.limits().is_enabled());
    }

    /// A misspelled limit is a config mistake, not a silently ignored one — the
    /// gate would run with a limit the operator believes is armed.
    #[test]
    fn a_misspelled_risk_limit_is_rejected() {
        let err = toml::from_str::<Config>(
            "daemon_endpoint = \"http://x:1\"\n[risk]\nmax_order_size = \"1\"\n\
             [strategy]\ntype = \"simple_grid\"\n",
        )
        .expect_err("an unknown risk key must be reported");
        assert!(err.to_string().contains("max_order_size"), "{err}");
    }

    // -----------------------------------------------------------------------
    // Decimal rendering and merge precedence
    // -----------------------------------------------------------------------

    /// Decimals are rendered as normalized strings so a price never loses
    /// precision by passing through `f64`.
    #[test]
    fn decimals_are_merged_as_normalized_strings() {
        let cases = [
            (dec!(90000.00), "90000"),
            (dec!(0.00100), "0.001"),
            (dec!(1000), "1000"),
            (dec!(-1.500), "-1.5"),
            (Decimal::ZERO, "0"),
        ];
        for (value, expected) in cases {
            let params = parse(&format!("symbol = \"X\"\nlower_price = \"{value}\"\n"));
            assert_eq!(
                params.table().get("lower_price").and_then(toml::Value::as_str),
                Some(expected),
                "{value}"
            );
        }
    }

    /// An explicit strategy-specific key of the same name is the more specific
    /// source and must win over the merged well-known value.
    #[test]
    fn an_explicit_extra_key_wins_over_the_merged_well_known_key() {
        let params = parse("symbol = \"FROM_WELL_KNOWN\"\n");
        assert_eq!(
            params.table().get("symbol").and_then(toml::Value::as_str),
            Some("FROM_WELL_KNOWN")
        );

        let mut table = params.table().clone();
        table.insert("symbol".into(), toml::Value::String(String::from("OVERRIDDEN")));
        let merged: StrategyParams = toml::Value::Table(table).try_into().expect("re-parses");
        assert_eq!(merged.table().get("symbol").and_then(toml::Value::as_str), Some("OVERRIDDEN"));
    }

    #[test]
    fn venue_label_defaults_to_empty() {
        assert_eq!(parse("symbol = \"X\"\n").venue_label(), "");
        assert_eq!(parse("symbol = \"X\"\nlabel = \"sub\"\n").venue_label(), "sub");
    }

    #[test]
    fn strategy_type_is_read_from_the_type_key() {
        assert_eq!(full_config("").strategy.strategy_type, "simple_grid");
    }

    #[test]
    fn absent_params_deserialize_to_an_empty_table() {
        let config = full_config("");
        assert!(config.strategy.params.table().is_empty());
        assert!(config.strategy.params.symbol.is_none());
    }

    // -----------------------------------------------------------------------
    // Properties
    // -----------------------------------------------------------------------

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        /// Whatever decimal the file declares, the merged table always carries a
        /// string a strategy can re-parse into the same value.
        #[test]
        fn a_merged_decimal_always_round_trips_through_the_table(
            mantissa in -1_000_000_000i64..1_000_000_000,
            scale in 0u32..19,
        ) {
            let Ok(value) = Decimal::try_from_i128_with_scale(i128::from(mantissa), scale) else {
                return Ok(());
            };
            let params = parse(&format!("symbol = \"X\"\nqty_per_level = \"{value}\"\n"));
            let rendered = params
                .table()
                .get("qty_per_level")
                .and_then(toml::Value::as_str)
                .expect("the key is merged as a string");
            prop_assert_eq!(
                rendered.parse::<Decimal>().expect("the rendering re-parses"),
                value.normalize(), "{} rendered as {}", value, rendered );
        }

        /// `num_levels` merges as an integer, never a string or a float.
        #[test]
        fn a_merged_level_count_is_always_an_integer(levels in 0u32..10_000) {
            let params = parse(&format!("symbol = \"X\"\nnum_levels = {levels}\n"));
            prop_assert_eq!(
                params.table().get("num_levels").and_then(toml::Value::as_integer),
                Some(i64::from(levels))
            );
        }

        /// Setting an endpoint never changes which backend runs. There is no
        /// override left to trigger.
        #[test]
        fn an_endpoint_never_selects_a_backend(
            backend in prop::sample::select(&["api", "mock", ""]),
        ) {
            let config =
                full_config(&format!("endpoint = \"http://api:9000\"\nbackend = \"{backend}\"\n"));
            let expected = match backend {
                "" => "api",
                other => other.trim(),
            };
            prop_assert_eq!(config.backend(), if expected.is_empty() { "api" } else { expected });
            prop_assert!(config.validated_backend().is_ok());
        }

        /// Only a blank value falls back to `"api"`; anything else must be one
        /// of the two supported backends to pass validation.
        #[test]
        fn only_a_blank_backend_falls_back(
            backend in prop::sample::select(&["api", "", "  ", "mock"]),
        ) {
            let config = full_config(&format!("backend = \"{backend}\"\n"));
            let trimmed = backend.trim();
            prop_assert_eq!(config.backend(), if trimmed.is_empty() { "api" } else { trimmed });
            prop_assert!(config.validated_backend().is_ok());
        }
    }
}