chapaty 1.3.0

An event-driven Rust engine for building and evaluating quantitative trading agents. Features a Gym-style API for algorithmic backtesting and reinforcement learning.
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::{
    data::{
        domain::{AggregatedPrice, Price, PriceDelta, SessionDate, SessionWindow, Symbol, Volume},
        event::{MarketEvent, OhlcvId, PriceReachable, StreamId, SymbolProvider, TradesId},
    },
    gym::trading::TradeKind,
    indicator::{
        batch::ohlcv::SessionCfg,
        config::{AtrConfig, EmaWindow, LookbackWindow, RsiWindow, SmaWindow},
    },
};

// ================================================================================================
// EMA
// ================================================================================================

/// Uniquely identifies an Exponential Moving Average (EMA) stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct EmaId {
    pub parent: OhlcvId,
    pub length: EmaWindow,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Ema {
    pub timestamp: DateTime<Utc>,
    pub price: Price,
}

impl PriceReachable for Ema {
    fn price_reached(&self, target_price: Price, direction: TradeKind) -> bool {
        match direction {
            TradeKind::Long => self.price.0 <= target_price.0,
            TradeKind::Short => self.price.0 >= target_price.0,
        }
    }
}

impl MarketEvent for Ema {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for EmaId {
    type Event = Ema;
}

impl SymbolProvider for EmaId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// RSI
// ================================================================================================

/// Uniquely identifies a Relative Strength Index (RSI) stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RsiId {
    pub parent: OhlcvId,
    pub length: RsiWindow,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Rsi {
    pub timestamp: DateTime<Utc>,
    pub price: Price,
}

impl PriceReachable for Rsi {
    fn price_reached(&self, target_price: Price, direction: TradeKind) -> bool {
        match direction {
            TradeKind::Long => self.price.0 <= target_price.0,
            TradeKind::Short => self.price.0 >= target_price.0,
        }
    }
}

impl MarketEvent for Rsi {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for RsiId {
    type Event = Rsi;
}

impl SymbolProvider for RsiId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// SMA
// ================================================================================================

/// Uniquely identifies a Simple Moving Average (SMA) stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SmaId {
    /// The source data stream this indicator is calculated from.
    pub parent: OhlcvId,
    /// The lookback window length (e.g., 14, 200).
    pub length: SmaWindow,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Sma {
    pub timestamp: DateTime<Utc>,
    pub price: Price,
}

impl PriceReachable for Sma {
    fn price_reached(&self, target_price: Price, direction: TradeKind) -> bool {
        match direction {
            TradeKind::Long => self.price.0 <= target_price.0,
            TradeKind::Short => self.price.0 >= target_price.0,
        }
    }
}

impl MarketEvent for Sma {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for SmaId {
    type Event = Sma;
}

impl SymbolProvider for SmaId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// OHLCV VWAP
// ================================================================================================

/// Uniquely identifies a Volume Weighted Average Price (VWAP) stream from OHLCV
/// data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OhlcvVwapId {
    /// The source data stream this indicator is calculated from.
    pub parent: OhlcvId,
    /// The aggregated price to use for calculations.
    pub price_aggregation: AggregatedPrice,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct OhlcvVwap {
    pub timestamp: DateTime<Utc>,
    pub price: Price,
}

impl PriceReachable for OhlcvVwap {
    fn price_reached(&self, target_price: Price, direction: TradeKind) -> bool {
        match direction {
            TradeKind::Long => self.price.0 <= target_price.0,
            TradeKind::Short => self.price.0 >= target_price.0,
        }
    }
}

impl MarketEvent for OhlcvVwap {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for OhlcvVwapId {
    type Event = OhlcvVwap;
}

impl SymbolProvider for OhlcvVwapId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// Trades VWAP
// ================================================================================================

/// Uniquely identifies a Volume Weighted Average Price (VWAP) stream from
/// Trades data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TradesVwapId {
    /// The source data stream this indicator is calculated from.
    pub parent: TradesId,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TradesVwap {
    pub timestamp: DateTime<Utc>,
    pub price: Price,
}

impl PriceReachable for TradesVwap {
    fn price_reached(&self, target_price: Price, direction: TradeKind) -> bool {
        match direction {
            TradeKind::Long => self.price.0 <= target_price.0,
            TradeKind::Short => self.price.0 >= target_price.0,
        }
    }
}

impl MarketEvent for TradesVwap {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for TradesVwapId {
    type Event = TradesVwap;
}

impl SymbolProvider for TradesVwapId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// Ohlcv Session
// ================================================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OhlcvSessionId {
    pub parent: OhlcvId,
    pub cfg: SessionCfg,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct OhlcvSession {
    pub session: SessionDate,
    pub open_timestamp: DateTime<Utc>,
    pub close_timestamp: DateTime<Utc>,
    pub high: Price,
    pub low: Price,
    pub highest_close: Price,
    pub lowest_close: Price,
    pub volume: Volume,
    pub vwap: Price,
}

impl MarketEvent for OhlcvSession {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.close_timestamp
    }
    fn opened_at(&self) -> DateTime<Utc> {
        self.open_timestamp
    }
}

impl StreamId for OhlcvSessionId {
    type Event = OhlcvSession;
}

impl SymbolProvider for OhlcvSessionId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// Trades Session
// ================================================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TradesSessionId {
    pub parent: TradesId,
    pub cfg: SessionWindow,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct TradesSession {
    pub session: SessionDate,
    pub open_timestamp: DateTime<Utc>,
    pub close_timestamp: DateTime<Utc>,
    pub high: Price,
    pub low: Price,
    pub volume: Volume,
    pub vwap: Price,
}

impl MarketEvent for TradesSession {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.close_timestamp
    }
    fn opened_at(&self) -> DateTime<Utc> {
        self.open_timestamp
    }
}

impl StreamId for TradesSessionId {
    type Event = TradesSession;
}

impl SymbolProvider for TradesSessionId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// ATR
// ================================================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AtrId {
    pub parent: OhlcvId,
    pub cfg: AtrConfig,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Atr {
    pub timestamp: DateTime<Utc>,
    pub range: PriceDelta,
}

impl MarketEvent for Atr {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

impl StreamId for AtrId {
    type Event = Atr;
}

impl SymbolProvider for AtrId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

// ================================================================================================
// Rate Of Change
// ================================================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RocId {
    pub parent: OhlcvId,
    pub lookback: LookbackWindow,
}

/// Represents the Rate of Change (ROC) over a specific lookback window.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Roc {
    /// The point in time when this rate of change was recorded (the end of the
    /// window).
    pub timestamp: DateTime<Utc>,

    /// The point in time of the historical reference price (the start of the
    /// window).
    pub window_start: DateTime<Utc>,

    /// The raw price difference between the current close and the historical
    /// close.
    pub absolute_change: PriceDelta,

    /// The relative rate of change expressed as a ratio.
    pub percentage: f64,
}

impl MarketEvent for Roc {
    fn point_in_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
    fn opened_at(&self) -> DateTime<Utc> {
        self.window_start
    }
}

impl StreamId for RocId {
    type Event = Roc;
}

impl SymbolProvider for RocId {
    fn symbol(&self) -> Symbol {
        self.parent.symbol()
    }
}

#[cfg(test)]
mod test {
    #![expect(
        clippy::unwrap_used,
        reason = "tests assert against known-valid fixtures; unwrap surfaces failures as panics that fail the test"
    )]
    use super::*;

    /// Parse RFC3339 timestamp string to `DateTime`<Utc>.
    fn ts(s: &str) -> DateTime<Utc> {
        DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
    }

    // ============================================================================
    // Price Reachability Tests
    // ============================================================================

    fn mock_sma(price: f64) -> Sma {
        Sma {
            timestamp: ts("2026-05-01T00:00:00Z"),
            price: Price(price),
        }
    }

    fn mock_ema(price: f64) -> Ema {
        Ema {
            timestamp: ts("2026-05-01T00:00:00Z"),
            price: Price(price),
        }
    }

    fn mock_rsi(value: f64) -> Rsi {
        Rsi {
            timestamp: ts("2026-05-01T00:00:00Z"),
            price: Price(value),
        }
    }

    #[test]
    fn test_sma_long_reachability() {
        // We want to trigger a Long when SMA drops to 50000.0 or below
        let target = Price(50000.0);

        // 1. Undershoot (Miss): SMA is at 50000.1, hasn't dropped enough.
        assert!(!mock_sma(50000.1).price_reached(target, TradeKind::Long));

        // 2. Exact Touch: SMA hits exactly 50000.0.
        assert!(mock_sma(50000.0).price_reached(target, TradeKind::Long));

        // 3. Overshoot (Gap down): SMA gaps down to 49000.0, completely skipping
        //    50000.0.
        assert!(mock_sma(49000.0).price_reached(target, TradeKind::Long));
    }

    #[test]
    fn test_sma_short_reachability() {
        // We want to trigger a Short when SMA rises to 50000.0 or above
        let target = Price(50000.0);

        // 1. Undershoot (Miss): SMA is at 49999.9, hasn't risen enough.
        assert!(!mock_sma(49999.9).price_reached(target, TradeKind::Short));

        // 2. Exact Touch: SMA hits exactly 50000.0.
        assert!(mock_sma(50000.0).price_reached(target, TradeKind::Short));

        // 3. Overshoot (Gap up): SMA gaps up to 51000.0, completely skipping 50000.0.
        assert!(mock_sma(51000.0).price_reached(target, TradeKind::Short));
    }

    #[test]
    fn test_ema_long_reachability() {
        let target = Price(100.5);

        // Test precision boundaries often encountered in floating-point math
        assert!(!mock_ema(100.500_000_01).price_reached(target, TradeKind::Long));
        assert!(mock_ema(100.5).price_reached(target, TradeKind::Long));
        assert!(mock_ema(100.499_999_99).price_reached(target, TradeKind::Long));
    }

    #[test]
    fn test_ema_short_reachability() {
        let target = Price(100.5);

        assert!(
            !mock_ema(100.499_999_99).price_reached(target, TradeKind::Short),
            "EMA is just below target"
        );
        assert!(
            mock_ema(100.5).price_reached(target, TradeKind::Short),
            "EMA exactly hits target"
        );
        assert!(
            mock_ema(100.500_000_01).price_reached(target, TradeKind::Short),
            "EMA spikes just above target"
        );
    }

    #[test]
    fn test_rsi_oversold_long() {
        // Classic strategy: Buy when RSI drops below 30
        let target = Price(30.0);

        // RSI is 31 (Not oversold enough)
        assert!(!mock_rsi(31.0).price_reached(target, TradeKind::Long));

        // RSI is exactly 30 (Trigger)
        assert!(mock_rsi(30.0).price_reached(target, TradeKind::Long));

        // RSI plummets to 15 (Trigger)
        assert!(mock_rsi(15.0).price_reached(target, TradeKind::Long));
    }

    #[test]
    fn test_rsi_overbought_short() {
        // Classic strategy: Sell when RSI spikes above 70
        let target = Price(70.0);

        // RSI is 69.9 (Not overbought enough)
        assert!(!mock_rsi(69.9).price_reached(target, TradeKind::Short));

        // RSI is exactly 70.0 (Trigger)
        assert!(mock_rsi(70.0).price_reached(target, TradeKind::Short));

        // RSI rockets to 85.5 (Trigger)
        assert!(mock_rsi(85.5).price_reached(target, TradeKind::Short));
    }
}