kestrel-chartkit 0.11.3

High-performance Rust technical analysis library for indicator math, market regime classification, composite scoring, and SVG visualization.
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
use std::fmt;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Supported resolution timeframes for market bars.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "lowercase")
)]
pub enum Resolution {
    M1,
    M5,
    M15,
    M30,
    H1,
    H4,
    D1,
    W1,
}

impl Resolution {
    pub fn as_str(&self) -> &'static str {
        match self {
            Resolution::M1 => "1m",
            Resolution::M5 => "5m",
            Resolution::M15 => "15m",
            Resolution::M30 => "30m",
            Resolution::H1 => "1h",
            Resolution::H4 => "4h",
            Resolution::D1 => "1d",
            Resolution::W1 => "1w",
        }
    }
}

impl fmt::Display for Resolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Selectable price/volume data source for indicators and series calculations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "lowercase")
)]
pub enum Source {
    #[default]
    Close,
    Open,
    High,
    Low,
    Hl2,
    Hlc3,
    Ohlc4,
    Volume,
    TypicalPrice,
}

impl Source {
    /// Extracts the scalar price/volume value from an OHLCV bar according to the chosen source.
    pub fn extract(&self, bar: &Bar) -> f64 {
        match self {
            Source::Close => bar.close,
            Source::Open => bar.open,
            Source::High => bar.high,
            Source::Low => bar.low,
            Source::Hl2 => (bar.high + bar.low) / 2.0,
            Source::Hlc3 => (bar.high + bar.low + bar.close) / 3.0,
            Source::Ohlc4 => (bar.open + bar.high + bar.low + bar.close) / 4.0,
            Source::Volume => bar.volume,
            Source::TypicalPrice => bar.typical_price(),
        }
    }
}

/// Provider-neutral instrument metadata.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct InstrumentMeta {
    pub symbol: String,
    pub tick_size: f64,
    pub price_precision: usize,
    pub timezone: String,
}

impl Default for InstrumentMeta {
    fn default() -> Self {
        Self {
            symbol: "GENERIC".to_string(),
            tick_size: 0.01,
            price_precision: 2,
            timezone: "UTC".to_string(),
        }
    }
}

/// Reason why [`InstrumentMeta`] fails the operative validity contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstrumentMetaError {
    NonPositiveTickSize,
    NonFiniteTickSize,
    ExcessivePricePrecision,
    EmptySymbol,
    EmptyTimezone,
}

impl fmt::Display for InstrumentMetaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self {
            Self::NonPositiveTickSize => "tick_size must be greater than zero",
            Self::NonFiniteTickSize => "tick_size must be finite",
            Self::ExcessivePricePrecision => "price_precision must be <= 12",
            Self::EmptySymbol => "symbol must not be empty",
            Self::EmptyTimezone => "timezone must not be empty",
        };
        f.write_str(message)
    }
}

impl std::error::Error for InstrumentMetaError {}

impl InstrumentMeta {
    /// Validates the operative contract required to use this metadata for rounding, risk and
    /// session calculations: a finite positive tick size, a sane price precision, and non-empty
    /// symbol/timezone identifiers.
    pub fn validate(&self) -> Result<(), InstrumentMetaError> {
        if !self.tick_size.is_finite() {
            return Err(InstrumentMetaError::NonFiniteTickSize);
        }
        if self.tick_size <= 0.0 {
            return Err(InstrumentMetaError::NonPositiveTickSize);
        }
        if self.price_precision > 12 {
            return Err(InstrumentMetaError::ExcessivePricePrecision);
        }
        if self.symbol.trim().is_empty() {
            return Err(InstrumentMetaError::EmptySymbol);
        }
        if self.timezone.trim().is_empty() {
            return Err(InstrumentMetaError::EmptyTimezone);
        }
        Ok(())
    }

    /// Rounds `price` to the nearest multiple of [`InstrumentMeta::tick_size`].
    ///
    /// Returns `price` unchanged if `tick_size` is non-finite or non-positive, so this method is
    /// safe to call on unvalidated metadata (see [`InstrumentMeta::validate`] to reject that case
    /// explicitly at ingestion boundaries).
    pub fn round_to_tick(&self, price: f64) -> f64 {
        if !self.tick_size.is_finite() || self.tick_size <= 0.0 || !price.is_finite() {
            return price;
        }
        (price / self.tick_size).round() * self.tick_size
    }
}

/// Explicit availability/quality metadata for an OHLCV bar, replacing implicit `f64`
/// conventions (e.g. `volume == 0.0` meaning "unknown" versus "genuinely zero").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BarQuality {
    /// False when the feed cannot report volume for this bar (as opposed to a true zero-volume
    /// bar). Consumers should fall back to equal-weight/price-based heuristics when false.
    pub volume_available: bool,
    /// True when the bar was synthesized (e.g. holiday padding, session stitching) rather than
    /// observed directly from the feed.
    pub is_synthetic: bool,
    /// True when the bar's price/volume was forward-filled from a prior bar rather than observed.
    pub is_forward_filled: bool,
    /// True when a time gap precedes this bar (missing bar(s) between it and the prior bar).
    pub has_gap: bool,
}

impl BarQuality {
    /// Quality flags for a directly observed, complete bar: volume available, no synthetic or
    /// forward-filled data, no gap.
    pub fn observed() -> Self {
        Self {
            volume_available: true,
            is_synthetic: false,
            is_forward_filled: false,
            has_gap: false,
        }
    }
}

/// An OHLCV [`Bar`] paired with explicit [`BarQuality`] metadata.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct QualifiedBar {
    pub bar: Bar,
    pub quality: BarQuality,
}

impl QualifiedBar {
    pub fn new(bar: Bar, quality: BarQuality) -> Self {
        Self { bar, quality }
    }

    /// Wraps a bar with [`BarQuality::observed`] flags.
    pub fn observed(bar: Bar) -> Self {
        Self {
            bar,
            quality: BarQuality::observed(),
        }
    }
}

/// What a bar's `volume` field actually measures.
///
/// Volume-based indicators (VWAP, volume profile, CVD, ...) assume traded turnover. Many feeds
/// cannot provide that: a CFD/FX broker's `volume` is typically tick/update count (activity, not
/// turnover), and a cash index has no volume at all (it is a computed value, not a traded
/// instrument). Declaring which kind a series has lets [`crate::applicability`] tell these cases
/// apart instead of silently computing a profile/VWAP over the wrong quantity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum VolumeKind {
    /// No volume data at all (e.g. a cash index).
    None,
    /// Update/tick count, not traded turnover (typical of CFD/FX broker feeds).
    Tick,
    /// Real traded turnover (shares, contracts, lots) as reported by an exchange.
    RealTurnover,
}

/// Which part of the trading day a bar series covers.
///
/// Session-anchored indicators (VWAP anchors, opening-range pivots, ...) need to know whether a
/// series is cut to the regular session, includes extended hours, or is a continuous (e.g. 24h
/// FX/crypto) feed — anchors and session extremes land in different places depending on this.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum SessionKind {
    /// Regular trading hours only.
    Regular,
    /// Includes pre-/post-market or overnight extensions.
    Extended,
    /// No session boundary at all (continuous trading, e.g. FX/crypto).
    Continuous,
}

/// How a bar series was assembled across instrument/contract boundaries.
///
/// Futures contracts expire; a "continuous" series is stitched from consecutive contracts. Roll-
/// sensitive indicators (structure/extreme detectors, seasonality) behave differently depending
/// on whether the series is a single, never-rolled contract, or stitched — and if stitched,
/// whether historical prices were shifted (back-adjusted) to remove roll gaps or left as-traded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum ContinuityKind {
    /// A cash/spot instrument with no contract expiry at all.
    Spot,
    /// A single futures contract, never rolled.
    SingleContract,
    /// Stitched across contract rolls, left as-traded (roll gaps visible in the series).
    StitchedUnadjusted,
    /// Stitched across contract rolls, back-adjusted to remove roll gaps — historical price
    /// levels are shifted and no longer the levels that were actually traded.
    StitchedBackAdjusted,
}

/// Whether and how a price series was adjusted for corporate actions.
///
/// Structure/extreme detectors that reference historical price levels (pivots, Elliott rule
/// checks, ...) assume those levels are the ones that were actually traded. Split/dividend
/// adjustment shifts historical marks to different numbers than what traded at the time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum PriceAdjustment {
    /// As-traded, unadjusted prices.
    Raw,
    /// Adjusted for stock splits only.
    Split,
    /// Adjusted for both splits and dividends.
    SplitAndDividend,
}

/// Where a bar series originates.
///
/// `Synthetic` is a deliberate, distinct origin (not lumped in with `Broker`) so
/// deterministically generated series (e.g. this crate's own synthetic-bar generator, or a public
/// learning-path project built entirely on synthetic data) are recognizable as such rather than
/// mistaken for a real feed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum Provenance {
    /// Directly from an exchange feed.
    Exchange,
    /// From a broker (e.g. CFD/FX market maker) rather than the exchange itself.
    Broker,
    /// Deterministically generated, not observed from any real market.
    Synthetic,
}

/// Coarse liquidity classification of a series.
///
/// Indicators that need market depth to be meaningful (e.g. liquidity-pool detection) degrade on
/// thin markets: the same calculation runs, but the result carries less information.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum LiquidityTier {
    Deep,
    Normal,
    Thin,
    /// Not classified/estimated.
    Unknown,
}

/// Describes what a bar series *is* and where it came from, for the plausibility check in
/// [`crate::applicability`]. Accompanies a series as metadata (not per-[`Bar`], to avoid
/// per-bar storage/cache cost) — see that module's `check_applicability` for how this is matched
/// against an indicator's [`crate::applicability::DataRequirements`].
///
/// Deliberately has no `Default` impl: every field materially changes the applicability verdict,
/// and there is no single "neutral" combination that would not silently misrepresent a real
/// series. Construct it explicitly for the series at hand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SeriesCapabilities {
    pub volume: VolumeKind,
    /// Whether classified individual trades (buy/sell direction) are available, as opposed to
    /// only aggregate OHLCV bars.
    pub trade_direction: bool,
    pub session: SessionKind,
    pub continuity: ContinuityKind,
    pub price_adjustment: PriceAdjustment,
    pub provenance: Provenance,
    pub liquidity_tier: LiquidityTier,
}

/// Comprehensive, provider-neutral provenance and identity specification for a time series.
///
/// Ties together instrument symbol, timeframe, session type, contract continuity, and price adjustment.
/// Can be attached to stored artifacts or downstream results to ensure that price-level findings
/// (e.g. Elliott Waves, pivots, S/R zones) are never evaluated against mismatched data feeds.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SeriesIdentity {
    pub symbol: String,
    pub timeframe: String,
    pub session: SessionKind,
    pub continuity: ContinuityKind,
    pub price_adjustment: PriceAdjustment,
    pub provenance: Provenance,
    pub contract_code: Option<String>,
}

impl SeriesIdentity {
    pub fn new(symbol: impl Into<String>, timeframe: impl Into<String>) -> Self {
        Self {
            symbol: symbol.into(),
            timeframe: timeframe.into(),
            session: SessionKind::Regular,
            continuity: ContinuityKind::Spot,
            price_adjustment: PriceAdjustment::Raw,
            provenance: Provenance::Exchange,
            contract_code: None,
        }
    }

    pub fn with_session(mut self, session: SessionKind) -> Self {
        self.session = session;
        self
    }

    pub fn with_continuity(mut self, continuity: ContinuityKind) -> Self {
        self.continuity = continuity;
        self
    }

    pub fn with_price_adjustment(mut self, adj: PriceAdjustment) -> Self {
        self.price_adjustment = adj;
        self
    }

    pub fn with_provenance(mut self, prov: Provenance) -> Self {
        self.provenance = prov;
        self
    }

    pub fn with_contract_code(mut self, code: impl Into<String>) -> Self {
        self.contract_code = Some(code.into());
        self
    }

    /// Returns true if this series is compatible with another series in terms of symbol,
    /// session boundaries, contract continuity, and price adjustment.
    pub fn is_compatible(&self, other: &Self) -> bool {
        self.symbol == other.symbol
            && self.session == other.session
            && self.continuity == other.continuity
            && self.price_adjustment == other.price_adjustment
            && self.contract_code == other.contract_code
    }
}

/// Generic OHLCV Bar data point.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Bar {
    pub timestamp: i64,
    pub open: f64,
    pub high: f64,
    pub low: f64,
    pub close: f64,
    pub volume: f64,
}

/// Reason why an OHLCV bar violates the public input contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BarValidationError {
    NonFiniteValue,
    NonPositivePrice,
    NegativeVolume,
    InvalidPriceRange,
}

impl fmt::Display for BarValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self {
            Self::NonFiniteValue => "OHLCV values must be finite",
            Self::NonPositivePrice => "OHLC prices must be greater than zero",
            Self::NegativeVolume => "volume must be non-negative",
            Self::InvalidPriceRange => "low/high must contain open and close",
        };
        f.write_str(message)
    }
}

impl std::error::Error for BarValidationError {}

impl Bar {
    /// Creates a bar without validation.
    ///
    /// Use [`Bar::try_new`] at data-ingestion boundaries. This unchecked constructor is retained
    /// for trusted feeds and compatibility with existing consumers.
    pub fn new(timestamp: i64, open: f64, high: f64, low: f64, close: f64, volume: f64) -> Self {
        Self {
            timestamp,
            open,
            high,
            low,
            close,
            volume,
        }
    }

    /// Creates a bar after validating the OHLCV input contract.
    pub fn try_new(
        timestamp: i64,
        open: f64,
        high: f64,
        low: f64,
        close: f64,
        volume: f64,
    ) -> Result<Self, BarValidationError> {
        let bar = Self::new(timestamp, open, high, low, close, volume);
        bar.validate()?;
        Ok(bar)
    }

    pub fn typical_price(&self) -> f64 {
        (self.high + self.low + self.close) / 3.0
    }

    /// Verifies that OHLCV prices and volumes satisfy mathematical and physical domain requirements:
    /// - All price values are finite and strictly positive (> 0.0)
    /// - Volume is finite and non-negative (>= 0.0)
    /// - Structural inequality holds: `low <= min(open, close)` and `high >= max(open, close)`
    pub fn validate(&self) -> Result<(), BarValidationError> {
        if !self.open.is_finite()
            || !self.high.is_finite()
            || !self.low.is_finite()
            || !self.close.is_finite()
            || !self.volume.is_finite()
        {
            return Err(BarValidationError::NonFiniteValue);
        }

        if self.open <= 0.0 || self.high <= 0.0 || self.low <= 0.0 || self.close <= 0.0 {
            return Err(BarValidationError::NonPositivePrice);
        }
        if self.volume < 0.0 {
            return Err(BarValidationError::NegativeVolume);
        }

        let min_oc = self.open.min(self.close);
        let max_oc = self.open.max(self.close);

        if self.low > min_oc || self.high < max_oc || self.low > self.high {
            return Err(BarValidationError::InvalidPriceRange);
        }

        Ok(())
    }

    /// Returns whether the bar satisfies [`Bar::validate`].
    pub fn is_valid(&self) -> bool {
        self.validate().is_ok()
    }
}

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

    #[test]
    fn test_bar_validation_contract() {
        let valid = Bar::new(1000, 100.0, 105.0, 95.0, 104.0, 1000.0);
        assert!(valid.is_valid());
        assert_eq!(
            Bar::try_new(1000, 100.0, 105.0, 95.0, 104.0, 1000.0),
            Ok(valid)
        );

        // Negative price
        let neg_price = Bar::new(1000, -100.0, 105.0, 95.0, 104.0, 1000.0);
        assert!(!neg_price.is_valid());

        // Negative volume
        let neg_vol = Bar::new(1000, 100.0, 105.0, 95.0, 104.0, -10.0);
        assert!(!neg_vol.is_valid());

        // High lower than open/close
        let bad_high = Bar::new(1000, 100.0, 90.0, 80.0, 95.0, 1000.0);
        assert!(!bad_high.is_valid());

        // NaN price
        let nan_price = Bar::new(1000, f64::NAN, 105.0, 95.0, 104.0, 1000.0);
        assert!(!nan_price.is_valid());
        assert_eq!(
            nan_price.validate(),
            Err(BarValidationError::NonFiniteValue)
        );
    }

    #[test]
    fn test_instrument_meta_validate() {
        assert_eq!(InstrumentMeta::default().validate(), Ok(()));

        let bad_tick = InstrumentMeta {
            tick_size: 0.0,
            ..InstrumentMeta::default()
        };
        assert_eq!(
            bad_tick.validate(),
            Err(InstrumentMetaError::NonPositiveTickSize)
        );

        let bad_precision = InstrumentMeta {
            price_precision: 13,
            ..InstrumentMeta::default()
        };
        assert_eq!(
            bad_precision.validate(),
            Err(InstrumentMetaError::ExcessivePricePrecision)
        );

        let empty_symbol = InstrumentMeta {
            symbol: "".to_string(),
            ..InstrumentMeta::default()
        };
        assert_eq!(
            empty_symbol.validate(),
            Err(InstrumentMetaError::EmptySymbol)
        );
    }

    #[test]
    fn test_instrument_meta_round_to_tick() {
        let meta = InstrumentMeta {
            tick_size: 0.25,
            ..InstrumentMeta::default()
        };
        assert_eq!(meta.round_to_tick(100.10), 100.0);
        assert_eq!(meta.round_to_tick(100.13), 100.25);
        assert_eq!(meta.round_to_tick(100.125), 100.25);

        let invalid_tick = InstrumentMeta {
            tick_size: 0.0,
            ..InstrumentMeta::default()
        };
        // Falls back to the unrounded price rather than dividing by zero.
        assert_eq!(invalid_tick.round_to_tick(100.10), 100.10);
    }

    #[test]
    fn test_bar_quality_defaults() {
        let default_quality = BarQuality::default();
        assert!(!default_quality.volume_available);
        assert!(!default_quality.is_synthetic);

        let observed = BarQuality::observed();
        assert!(observed.volume_available);
        assert!(!observed.is_synthetic);
        assert!(!observed.is_forward_filled);
        assert!(!observed.has_gap);

        let bar = Bar::new(1000, 100.0, 105.0, 95.0, 104.0, 1000.0);
        let qualified = QualifiedBar::observed(bar.clone());
        assert_eq!(qualified.bar, bar);
        assert_eq!(qualified.quality, BarQuality::observed());
    }
}

/// Classification of current market regime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum MarketRegime {
    BullishExpansion,
    BearishExpansion,
    #[default]
    Consolidation,
    Transition,
}

impl fmt::Display for MarketRegime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MarketRegime::BullishExpansion => write!(f, "Bullish Expansion"),
            MarketRegime::BearishExpansion => write!(f, "Bearish Expansion"),
            MarketRegime::Consolidation => write!(f, "Consolidation / Range"),
            MarketRegime::Transition => write!(f, "Regime Transition"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum ZoneKind {
    Support,
    Resistance,
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SupportResistanceZone {
    pub kind: ZoneKind,
    pub price: f64,
    pub price_top: f64,
    pub price_bottom: f64,
    pub strength: f64, // 0.0 ..= 1.0
    pub distance_pct: f64,
    pub touches: u32,
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RiskPlan {
    pub entry: f64,
    pub stop_loss: f64,
    pub target_1: f64,
    pub target_2: f64,
    pub risk_reward_ratio: f64,
}

impl RiskPlan {
    /// Rounds `entry`/`stop_loss`/`target_1`/`target_2` to `instrument`'s tick size and
    /// recomputes `risk_reward_ratio` from the rounded prices, so a plan built from raw
    /// ATR-derived math becomes tradable at the instrument's actual price granularity.
    pub fn rounded_to(&self, instrument: &InstrumentMeta) -> Self {
        let entry = instrument.round_to_tick(self.entry);
        let stop_loss = instrument.round_to_tick(self.stop_loss);
        let target_1 = instrument.round_to_tick(self.target_1);
        let target_2 = instrument.round_to_tick(self.target_2);

        let risk = (entry - stop_loss).abs();
        let reward = (target_2 - entry).abs();
        let risk_reward_ratio = if risk > 0.0 {
            reward / risk
        } else {
            self.risk_reward_ratio
        };

        Self {
            entry,
            stop_loss,
            target_1,
            target_2,
            risk_reward_ratio,
        }
    }
}

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

    #[test]
    fn test_risk_plan_rounded_to_tick() {
        let plan = RiskPlan {
            entry: 100.13,
            stop_loss: 98.77,
            target_1: 101.5,
            target_2: 103.02,
            risk_reward_ratio: 2.11,
        };
        let instrument = InstrumentMeta {
            tick_size: 0.25,
            ..InstrumentMeta::default()
        };
        let rounded = plan.rounded_to(&instrument);

        assert_eq!(rounded.entry, 100.25);
        assert_eq!(rounded.stop_loss, 98.75);
        assert_eq!(rounded.target_1, 101.5);
        assert_eq!(rounded.target_2, 103.0);

        let expected_rrr = (103.0f64 - 100.25).abs() / (100.25f64 - 98.75).abs();
        assert!((rounded.risk_reward_ratio - expected_rrr).abs() < 1e-9);
    }
}