wickra-backtest-core 0.1.1

Streaming-native backtest engine core (strategy spec, rules, execution, portfolio) built on wickra-core.
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
//! The data-driven strategy specification (`StrategySpec`).
//!
//! A strategy is **data, not code** — a JSON document — so the exact same
//! strategy runs identically across every Wickra language binding and over the
//! C-ABI. This module defines the serde representation of the spec and a
//! structural [`StrategySpec::validate`] that checks every indicator reference
//! is declared.
//!
//! See `schema/strategy_spec.schema.json` (generated) for the canonical schema.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::error::{BacktestError, Result};
use crate::registry::feed_of;

/// Current strategy-spec format version. Bumped on breaking DSL changes.
pub const SPEC_VERSION: u32 = 1;

fn default_spec_version() -> u32 {
    SPEC_VERSION
}

/// A complete strategy specification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct StrategySpec {
    /// Spec format version (defaults to [`SPEC_VERSION`]).
    ///
    /// A spec from an older format still parses -- the DSL only grows within a
    /// version -- but one declaring a newer format is rejected rather than
    /// read with fields this build does not know about.
    #[serde(default = "default_spec_version")]
    pub spec_version: u32,
    /// Primary trading symbol.
    ///
    /// Metadata, not an input: the engine never resolves it and cannot fetch
    /// data. The caller supplies the candles, and this records which instrument
    /// they are expected to be, so a stored spec still says what it was written
    /// for.
    pub symbol: String,
    /// The reference instrument a pairwise indicator is meant to be run against.
    ///
    /// Also metadata. Naming it here does not load anything: the reference series
    /// is passed alongside the candles, through `RunRequest.reference` or
    /// `run_with_ref`. This field records which instrument the caller is expected
    /// to pass, so a spec using a pairwise indicator is not ambiguous about what
    /// it is pairing against.
    #[serde(default)]
    pub ref_symbol: Option<String>,
    /// Bar timeframe (e.g. `"1h"`).
    ///
    /// Metadata, like `symbol`: a free-form label recording the bar size the spec
    /// was written for. The engine reads whatever candles it is given and does not
    /// check them against this.
    pub timeframe: String,
    /// Named indicators available to the rules.
    pub indicators: BTreeMap<String, IndicatorSpec>,
    /// Long-entry condition.
    pub entry: Condition,
    /// Long-exit condition.
    pub exit: Condition,
    /// Optional short-entry condition.
    #[serde(default)]
    pub short_entry: Option<Condition>,
    /// Optional short-exit condition.
    #[serde(default)]
    pub short_exit: Option<Condition>,
    /// Position sizing.
    pub sizing: Sizing,
    /// Trading costs.
    #[serde(default)]
    pub costs: Costs,
    /// Risk controls.
    #[serde(default)]
    pub risk: Risk,
    /// Execution model.
    #[serde(default)]
    pub execution: Execution,
    /// Explicit warmup bars (defaults to the max indicator warmup).
    #[serde(default)]
    pub warmup: Option<u32>,
}

impl StrategySpec {
    /// Parse a spec from JSON and validate it.
    pub fn parse(json: &str) -> Result<Self> {
        let spec: Self =
            serde_json::from_str(json).map_err(|e| BacktestError::InvalidSpec(e.to_string()))?;
        spec.validate()?;
        Ok(spec)
    }

    /// Validate structural invariants: every indicator referenced by the rules
    /// must be declared in `indicators`.
    pub fn validate(&self) -> Result<()> {
        let declared: BTreeSet<&str> = self.indicators.keys().map(String::as_str).collect();
        check_condition(&self.entry, &declared)?;
        check_condition(&self.exit, &declared)?;
        if let Some(c) = &self.short_entry {
            check_condition(c, &declared)?;
        }
        if let Some(c) = &self.short_exit {
            check_condition(c, &declared)?;
        }
        // Refuse a format this build cannot know how to read. Accepting it would
        // mean silently ignoring whatever the newer version added, which produces
        // a run that looks successful and answers a different question than the
        // spec asked. Older versions stay readable: the DSL only grows within a
        // version, so nothing an old spec says has changed meaning.
        if self.spec_version == 0 || self.spec_version > SPEC_VERSION {
            return Err(BacktestError::InvalidSpec(format!(
                "spec_version {} is not supported; this build reads 1..={SPEC_VERSION}",
                self.spec_version
            )));
        }
        // Risk-per-trade sizes the position from the distance to the stop, so
        // without a stop there is no distance and nothing to size from. The
        // documentation already says the two go together; this makes it true.
        if matches!(self.sizing, Sizing::RiskPerTrade { .. }) && self.risk.stop_loss_pct.is_none() {
            return Err(BacktestError::InvalidSpec(
                "sizing risk_per_trade requires risk.stop_loss_pct: the position size is                  derived from the distance to the stop"
                    .into(),
            ));
        }
        // A declared feed is redundant -- the indicator type already determines it --
        // so the only thing it can do is contradict the indicator, and that is what
        // this catches. An unknown kind is left to `build`, which reports it with a
        // better message than this could.
        for (name, ind) in &self.indicators {
            let (Some(declared), Some(actual)) = (ind.feed, feed_of(&ind.kind)) else {
                continue;
            };
            if declared != actual {
                return Err(BacktestError::InvalidSpec(format!(
                    "indicator '{name}' ({}) declares feed {declared:?} but consumes {actual:?}",
                    ind.kind
                )));
            }
        }
        match self.execution.order_type {
            OrderType::Limit if self.execution.limit_offset_pct.is_none() => {
                return Err(BacktestError::InvalidSpec(
                    "limit order_type requires execution.limit_offset_pct".into(),
                ));
            }
            OrderType::Stop if self.execution.stop_offset_pct.is_none() => {
                return Err(BacktestError::InvalidSpec(
                    "stop order_type requires execution.stop_offset_pct".into(),
                ));
            }
            OrderType::StopLimit
                if self.execution.stop_offset_pct.is_none()
                    || self.execution.limit_offset_pct.is_none() =>
            {
                return Err(BacktestError::InvalidSpec(
                    "stop_limit order_type requires both execution.stop_offset_pct and                      execution.limit_offset_pct"
                        .into(),
                ));
            }
            _ => {}
        }
        if self.execution.partial_fills && self.execution.max_participation.is_none() {
            return Err(BacktestError::InvalidSpec(
                "partial_fills requires execution.max_participation".into(),
            ));
        }
        if matches!(self.execution.fill_timing, FillTiming::Close) {
            // Close fills happen on the signalling bar itself, which the resting
            // limit/stop and latency models (both next-bar) cannot express.
            if !matches!(self.execution.order_type, OrderType::Market) {
                return Err(BacktestError::InvalidSpec(
                    "fill_timing close requires a market order_type".into(),
                ));
            }
            if self.execution.latency_bars != 0 {
                return Err(BacktestError::InvalidSpec(
                    "fill_timing close is incompatible with latency_bars".into(),
                ));
            }
        }
        Ok(())
    }
}

/// One indicator instance: a `wickra-core` type name plus its parameters.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct IndicatorSpec {
    /// The `wickra-core` indicator type name (e.g. `"Ema"`).
    #[serde(rename = "type")]
    pub kind: String,
    /// Constructor parameters.
    #[serde(default)]
    pub params: Vec<f64>,
    /// Which feed drives it. Optional, and redundant when present: the indicator
    /// type already determines its feed. State it and the spec is cross-checked
    /// against the registry, so a rename or a copied block that no longer matches
    /// the indicator fails at parse instead of silently producing no values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feed: Option<Feed>,
}

/// The data feed an indicator is driven by.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Feed {
    /// OHLCV candles (default). Also the feed for pairwise indicators, which are
    /// fed the bar close alongside the reference series' close.
    #[default]
    Kline,
    /// Trade prints.
    Trade,
    /// Order-book snapshots.
    Orderbook,
    /// Trade prints quoted against the book mid.
    TradeQuote,
    /// Perpetual/derivatives ticks — funding, open interest, mark and index.
    Derivatives,
    /// The market cross-section, for breadth indicators.
    CrossSection,
}

/// A price field of the current bar.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PriceField {
    /// Open.
    Open,
    /// High.
    High,
    /// Low.
    Low,
    /// Close.
    Close,
    /// Volume.
    Volume,
    /// `(high + low + close) / 3`.
    Hlc3,
    /// `(open + high + low + close) / 4`.
    Ohlc4,
}

/// A value node — evaluates to a number each bar.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum Operand {
    /// Indicator reference by name, optionally `"name.field"` for multi-output.
    Ref(String),
    /// A literal constant.
    Const(f64),
    /// A compound expression.
    Expr(Box<OperandExpr>),
}

/// The object-shaped operand forms.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OperandExpr {
    /// A price field of the current bar.
    Price(PriceField),
    /// The value of an operand `n` bars ago: `["operand", n]`.
    Prev((Box<Operand>, u32)),
    /// `a + b`.
    Add((Box<Operand>, Box<Operand>)),
    /// `a - b`.
    Sub((Box<Operand>, Box<Operand>)),
    /// `a * b`.
    Mul((Box<Operand>, Box<Operand>)),
    /// `a / b`.
    Div((Box<Operand>, Box<Operand>)),
}

/// A boolean node — evaluates to true/false each bar.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Condition {
    /// `a > b`.
    Gt((Operand, Operand)),
    /// `a < b`.
    Lt((Operand, Operand)),
    /// `a >= b`.
    Ge((Operand, Operand)),
    /// `a <= b`.
    Le((Operand, Operand)),
    /// `a == b`.
    Eq((Operand, Operand)),
    /// `a != b`.
    Ne((Operand, Operand)),
    /// `a` crosses above `b` this bar.
    CrossAbove((Operand, Operand)),
    /// `a` crosses below `b` this bar.
    CrossBelow((Operand, Operand)),
    /// `lo <= a <= hi`: `[a, lo, hi]`.
    Between((Operand, Operand, Operand)),
    /// `a` is greater than its value `n` bars ago: `[a, n]`.
    Rising((Operand, u32)),
    /// `a` is less than its value `n` bars ago: `[a, n]`.
    Falling((Operand, u32)),
    /// All sub-conditions true (AND).
    All(Vec<Condition>),
    /// Any sub-condition true (OR).
    Any(Vec<Condition>),
    /// Negation.
    Not(Box<Condition>),
    /// True iff a position is currently open.
    InPosition(bool),
    /// Predicate on the number of bars since entry.
    BarsSinceEntry(IntPredicate),
}

/// An integer comparison predicate (used by stateful conditions).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IntPredicate {
    /// `> n`.
    Gt(u32),
    /// `< n`.
    Lt(u32),
    /// `>= n`.
    Ge(u32),
    /// `<= n`.
    Le(u32),
    /// `== n`.
    Eq(u32),
}

/// Position sizing model.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Sizing {
    /// A fraction of current equity.
    FixedFraction {
        /// Fraction in `[0, 1]`.
        fraction: f64,
    },
    /// A fixed quantity of the base asset.
    FixedQty {
        /// Quantity.
        qty: f64,
    },
    /// A fixed cash notional.
    FixedCash {
        /// Cash amount.
        cash: f64,
    },
    /// Size to a target volatility: the position notional is scaled so the
    /// position's per-bar return volatility approximates `target_vol`. With
    /// realized per-bar volatility `rv` over `lookback` bars, the notional is
    /// `equity * target_vol / rv` (then capped by the leverage limits). No
    /// position is taken until `lookback` bars of history exist.
    VolTarget {
        /// Target per-bar return volatility, as a fraction (e.g. `0.02` = 2%).
        target_vol: f64,
        /// Lookback bars for the realized-volatility estimate.
        lookback: u32,
    },
    /// Size from the stop-loss distance and a per-trade risk budget.
    RiskPerTrade {
        /// Risk per trade in percent of equity.
        risk_pct: f64,
    },
}

/// Trading costs.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
pub struct Costs {
    /// Maker fee in basis points.
    #[serde(default)]
    pub maker_bps: f64,
    /// Taker fee in basis points.
    #[serde(default)]
    pub taker_bps: f64,
    /// Slippage model.
    #[serde(default)]
    pub slippage: Slippage,
    /// Charge perpetual funding each bar to an open position, using the
    /// derivatives feed's funding rate and mark price (longs pay when the rate
    /// is positive, shorts receive). Requires a derivatives feed; default off.
    #[serde(default)]
    pub funding: bool,
}

/// Slippage model.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Slippage {
    /// A fixed number of basis points.
    FixedBps {
        /// Basis points.
        bps: f64,
    },
    /// Slippage equal to the bid/ask spread (needs an order-book feed).
    Spread,
    /// Linear price impact in the traded volume.
    VolumeImpact {
        /// Impact coefficient.
        coef: f64,
    },
}

impl Default for Slippage {
    fn default() -> Self {
        Self::FixedBps { bps: 0.0 }
    }
}

/// Risk controls (all optional).
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
pub struct Risk {
    /// Stop-loss as a percent move against the position.
    #[serde(default)]
    pub stop_loss_pct: Option<f64>,
    /// Take-profit as a percent move in favour.
    #[serde(default)]
    pub take_profit_pct: Option<f64>,
    /// Trailing-stop as a percent retrace from the peak.
    #[serde(default)]
    pub trailing_stop_pct: Option<f64>,
    /// Maximum leverage.
    #[serde(default)]
    pub max_leverage: Option<f64>,
    /// Maximum position as a percent of equity.
    #[serde(default)]
    pub max_position_pct: Option<f64>,
    /// Liquidate a leveraged position intrabar at its bankruptcy price (where
    /// account equity reaches zero). Only bites above 1x leverage; default off.
    #[serde(default)]
    pub liquidation: bool,
}

/// Execution model.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
pub struct Execution {
    /// Order type.
    #[serde(default)]
    pub order_type: OrderType,
    /// When a signalled order fills.
    #[serde(default)]
    pub fill_timing: FillTiming,
    /// Limit-order trigger as a percent offset from the signal bar's close
    /// (required for `order_type = "limit"`). Negative places a long limit
    /// below the market (buy the dip); positive places a short limit above it.
    #[serde(default)]
    pub limit_offset_pct: Option<f64>,
    /// Stop-order trigger as a percent offset from the signal bar's close
    /// (required for `order_type = "stop"`). Positive places a long stop above
    /// the market (breakout); negative places a short stop below it.
    #[serde(default)]
    pub stop_offset_pct: Option<f64>,
    /// Simulated latency in bars before a fill.
    #[serde(default)]
    pub latency_bars: u32,
    /// Whether partial fills are modelled. When set, an entry fills at most
    /// `max_participation * bar_volume` and the unfilled remainder is cancelled.
    #[serde(default)]
    pub partial_fills: bool,
    /// Maximum fraction of a bar's volume a single entry may consume (required
    /// when `partial_fills` is set).
    #[serde(default)]
    pub max_participation: Option<f64>,
}

/// Order type.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum OrderType {
    /// Market order (default).
    #[default]
    Market,
    /// Limit order.
    Limit,
    /// Stop order.
    Stop,
    /// Stop-limit order.
    StopLimit,
}

/// When a signalled order fills.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum FillTiming {
    /// On the next bar's open — the look-ahead-bias-free default.
    #[default]
    NextOpen,
    /// On the signalling bar's own close (close-to-close execution). An opt-in,
    /// deliberately optimistic mode: the fill uses the very close that produced
    /// the signal, which is not actually tradeable in live execution. Market
    /// orders only, and incompatible with `latency_bars`.
    Close,
}

// --- validation helpers ------------------------------------------------------

fn check_operand(op: &Operand, declared: &BTreeSet<&str>) -> Result<()> {
    match op {
        Operand::Ref(name) => {
            let base = name.split('.').next().unwrap_or(name.as_str());
            if !declared.contains(base) {
                return Err(BacktestError::UndeclaredRef(name.clone()));
            }
        }
        Operand::Const(_) => {}
        Operand::Expr(expr) => match expr.as_ref() {
            OperandExpr::Price(_) => {}
            OperandExpr::Prev((a, _)) => check_operand(a, declared)?,
            OperandExpr::Add((a, b))
            | OperandExpr::Sub((a, b))
            | OperandExpr::Mul((a, b))
            | OperandExpr::Div((a, b)) => {
                check_operand(a, declared)?;
                check_operand(b, declared)?;
            }
        },
    }
    Ok(())
}

fn check_condition(cond: &Condition, declared: &BTreeSet<&str>) -> Result<()> {
    match cond {
        Condition::Gt((a, b))
        | Condition::Lt((a, b))
        | Condition::Ge((a, b))
        | Condition::Le((a, b))
        | Condition::Eq((a, b))
        | Condition::Ne((a, b))
        | Condition::CrossAbove((a, b))
        | Condition::CrossBelow((a, b)) => {
            check_operand(a, declared)?;
            check_operand(b, declared)?;
        }
        Condition::Between((a, lo, hi)) => {
            check_operand(a, declared)?;
            check_operand(lo, declared)?;
            check_operand(hi, declared)?;
        }
        Condition::Rising((a, _)) | Condition::Falling((a, _)) => check_operand(a, declared)?,
        Condition::All(cs) | Condition::Any(cs) => {
            for c in cs {
                check_condition(c, declared)?;
            }
        }
        Condition::Not(c) => check_condition(c, declared)?,
        Condition::InPosition(_) | Condition::BarsSinceEntry(_) => {}
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    const EXAMPLE: &str = r#"{
      "spec_version": 1, "symbol": "BTCUSDT", "timeframe": "1h",
      "indicators": {
        "ema_fast": {"type": "Ema", "params": [20]},
        "ema_slow": {"type": "Ema", "params": [50]},
        "rsi": {"type": "Rsi", "params": [14]}
      },
      "entry": {"all": [{"cross_above": ["ema_fast", "ema_slow"]}, {"lt": ["rsi", 70]}]},
      "exit": {"any": [{"cross_below": ["ema_fast", "ema_slow"]}, {"gt": ["rsi", 80]}]},
      "sizing": {"type": "fixed_fraction", "fraction": 0.95},
      "costs": {"maker_bps": 2, "taker_bps": 5, "slippage": {"type": "fixed_bps", "bps": 2}},
      "risk": {"stop_loss_pct": 2.0, "take_profit_pct": 5.0},
      "execution": {"order_type": "market", "fill_timing": "next_open"}
    }"#;

    #[test]
    fn parses_and_validates_example() {
        let spec = StrategySpec::parse(EXAMPLE).unwrap();
        assert_eq!(spec.spec_version, 1);
        assert_eq!(spec.symbol, "BTCUSDT");
        assert_eq!(spec.indicators.len(), 3);
        assert!(matches!(spec.sizing, Sizing::FixedFraction { .. }));
        assert!(matches!(spec.execution.fill_timing, FillTiming::NextOpen));
    }

    #[test]
    fn roundtrips_losslessly() {
        let spec = StrategySpec::parse(EXAMPLE).unwrap();
        let json = serde_json::to_string(&spec).unwrap();
        let again: StrategySpec = serde_json::from_str(&json).unwrap();
        assert_eq!(spec, again);
    }

    #[test]
    fn defaults_fill_in() {
        let json = r#"{
          "symbol": "ETHUSDT", "timeframe": "5m",
          "indicators": {"sma": {"type": "Sma", "params": [10]}},
          "entry": {"gt": ["sma", {"price": "close"}]},
          "exit": {"lt": ["sma", {"price": "close"}]},
          "sizing": {"type": "fixed_qty", "qty": 1.0}
        }"#;
        let spec = StrategySpec::parse(json).unwrap();
        assert_eq!(spec.spec_version, SPEC_VERSION);
        assert_eq!(spec.execution.fill_timing, FillTiming::NextOpen);
        // Not stated, so nothing to cross-check; the indicator's own family
        // decides, and `feed_of` reports it.
        assert_eq!(spec.indicators["sma"].feed, None);
        assert_eq!(crate::registry::feed_of("Sma"), Some(Feed::Kline));
        assert!(spec.risk.stop_loss_pct.is_none());
        assert!((spec.costs.maker_bps).abs() < f64::EPSILON);
    }

    #[test]
    fn rejects_undeclared_reference() {
        let json = r#"{
          "symbol": "X", "timeframe": "1h",
          "indicators": {"a": {"type": "Sma", "params": [5]}},
          "entry": {"gt": ["a", "b"]},
          "exit": {"in_position": true},
          "sizing": {"type": "fixed_qty", "qty": 1.0}
        }"#;
        let err = StrategySpec::parse(json).unwrap_err();
        assert!(matches!(err, BacktestError::UndeclaredRef(r) if r == "b"));
    }

    #[test]
    fn a_spec_version_this_build_cannot_read_is_rejected() {
        let spec = |version: &str| {
            format!(
                r#"{{
                  {version}
                  "symbol": "X", "timeframe": "1h",
                  "indicators": {{"a": {{"type": "Sma", "params": [5]}}}},
                  "entry": {{"gt": ["a", "a"]}},
                  "exit": {{"in_position": true}},
                  "sizing": {{"type": "fixed_qty", "qty": 1.0}}
                }}"#
            )
        };
        // Omitted defaults to the current version.
        assert!(StrategySpec::parse(&spec("")).is_ok());
        assert!(StrategySpec::parse(&spec(r#""spec_version": 1,"#)).is_ok());
        // A newer format would carry fields this build does not know, and reading
        // it while ignoring them answers a different question than the spec asked.
        let err = StrategySpec::parse(&spec(r#""spec_version": 999,"#)).unwrap_err();
        let BacktestError::InvalidSpec(msg) = err else {
            panic!("expected InvalidSpec");
        };
        assert!(
            msg.contains("999"),
            "message should name the version: {msg}"
        );
        // Zero is not a format anyone wrote; it is a missing value that survived
        // serialisation somewhere.
        assert!(StrategySpec::parse(&spec(r#""spec_version": 0,"#)).is_err());
    }

    #[test]
    fn a_declared_feed_must_match_the_indicator_that_declares_it() {
        let spec = |feed: &str| {
            format!(
                r#"{{
                  "symbol": "X", "timeframe": "1h",
                  "indicators": {{"a": {{"type": "Sma", "params": [5]{feed}}}}},
                  "entry": {{"gt": ["a", "a"]}},
                  "exit": {{"in_position": true}},
                  "sizing": {{"type": "fixed_qty", "qty": 1.0}}
                }}"#
            )
        };
        // Omitted: the indicator's own family decides, and nothing to contradict.
        assert!(StrategySpec::parse(&spec("")).is_ok());
        // Declared and correct: Sma is fed the bar close.
        assert!(StrategySpec::parse(&spec(r#", "feed": "kline""#)).is_ok());
        // Declared and wrong. This is the case that used to be accepted in silence:
        // the field was never read, so the spec ran and the indicator quietly
        // consumed candles regardless of what it claimed.
        let err = StrategySpec::parse(&spec(r#", "feed": "trade""#)).unwrap_err();
        let BacktestError::InvalidSpec(msg) = err else {
            panic!("expected InvalidSpec");
        };
        assert!(
            msg.contains("'a'"),
            "message should name the indicator: {msg}"
        );
        assert!(
            msg.contains("Trade") && msg.contains("Kline"),
            "both feeds: {msg}"
        );
    }

    #[test]
    fn every_feed_family_is_reachable_from_the_registry() {
        use crate::registry::feed_of;
        // One indicator per family, so a family losing its mapping is caught here
        // rather than by a spec that silently stops being checked.
        assert_eq!(feed_of("Sma"), Some(Feed::Kline));
        assert_eq!(feed_of("Atr"), Some(Feed::Kline));
        assert_eq!(feed_of("Beta"), Some(Feed::Kline));
        assert_eq!(feed_of("FundingRate"), Some(Feed::Derivatives));
        assert_eq!(feed_of("Nope"), None);
    }

    #[test]
    fn execution_validation_rejections() {
        // Each invalid execution config is rejected at parse (which validates).
        let base = |exec: &str| {
            format!(
                r#"{{"symbol":"x","timeframe":"1h","indicators":{{}},
                    "entry":{{"gt":[{{"price":"close"}},0]}},
                    "exit":{{"in_position":true}},
                    "sizing":{{"type":"fixed_qty","qty":1}},
                    "execution":{exec}}}"#
            )
        };
        let rejects = |exec: &str| {
            matches!(
                StrategySpec::parse(&base(exec)),
                Err(BacktestError::InvalidSpec(_))
            )
        };
        let accepts = |exec: &str| StrategySpec::parse(&base(exec)).is_ok();
        // A stop-limit carrying both offsets is a valid spec. Without this the
        // rejection tests below would still pass if the order type were rejected
        // outright, which is what it used to be.
        assert!(accepts(
            r#"{"order_type":"stop_limit","stop_offset_pct":0.5,"limit_offset_pct":0.6}"#
        ));
        // An order type whose trigger offset is missing. A stop-limit needs both:
        // the stop that arms it and the limit it arms.
        assert!(rejects(r#"{"order_type":"limit"}"#));
        assert!(rejects(r#"{"order_type":"stop"}"#));
        assert!(rejects(r#"{"order_type":"stop_limit"}"#));
        assert!(rejects(
            r#"{"order_type":"stop_limit","stop_offset_pct":0.5}"#
        ));
        assert!(rejects(
            r#"{"order_type":"stop_limit","limit_offset_pct":0.2}"#
        ));
        // Partial fills without a participation cap.
        assert!(rejects(r#"{"partial_fills":true}"#));
        // Close fill timing is market-only and latency-free.
        assert!(rejects(
            r#"{"fill_timing":"close","order_type":"limit","limit_offset_pct":-0.5}"#
        ));
        assert!(rejects(r#"{"fill_timing":"close","latency_bars":1}"#));

        // The valid counterparts pass.
        assert!(
            StrategySpec::parse(&base(r#"{"order_type":"limit","limit_offset_pct":-0.5}"#)).is_ok()
        );
        assert!(
            StrategySpec::parse(&base(r#"{"order_type":"stop","stop_offset_pct":0.5}"#)).is_ok()
        );
        assert!(
            StrategySpec::parse(&base(r#"{"partial_fills":true,"max_participation":0.1}"#)).is_ok()
        );
        assert!(StrategySpec::parse(&base(r#"{"fill_timing":"close"}"#)).is_ok());
    }

    #[test]
    fn operand_forms_parse() {
        let op: Operand = serde_json::from_str(r#""ema_fast""#).unwrap();
        assert!(matches!(op, Operand::Ref(_)));
        let op: Operand = serde_json::from_str("70").unwrap();
        assert!(matches!(op, Operand::Const(_)));
        let op: Operand = serde_json::from_str(r#"{"price": "close"}"#).unwrap();
        assert!(matches!(op, Operand::Expr(_)));
        let op: Operand = serde_json::from_str(r#"{"prev": ["ema_fast", 1]}"#).unwrap();
        assert!(matches!(op, Operand::Expr(_)));
        let op: Operand = serde_json::from_str(r#"{"add": [1, 2]}"#).unwrap();
        assert!(matches!(op, Operand::Expr(_)));
    }

    #[test]
    fn multi_output_ref_is_allowed_when_base_declared() {
        let json = r#"{
          "symbol": "X", "timeframe": "1h",
          "indicators": {"macd": {"type": "Macd", "params": [12, 26, 9]}},
          "entry": {"cross_above": ["macd.macd", "macd.signal"]},
          "exit": {"in_position": true},
          "sizing": {"type": "fixed_qty", "qty": 1.0}
        }"#;
        assert!(StrategySpec::parse(json).is_ok());
    }
}