chapaty 1.0.0

High-performance backtesting and financial simulation framework for trading strategies and reinforcement learning agents. Async-first, Gym-like API in Rust.
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
use std::sync::Arc;

use chrono::Duration;
use itertools::iproduct;
use rand::seq::SliceRandom;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use serde::Serialize;
use serde_with::{DurationSeconds, serde_as};

use crate::{
    agent::{Agent, AgentIdentifier, GridAxis, news::NewsPhase},
    data::{
        domain::{CandleDirection, Price, Quantity, TradeId},
        event::{EconomicCalendarId, MarketId, Ohlcv, OhlcvId},
        view::StreamView,
    },
    error::{AgentError, ChapatyResult},
    gym::trading::{
        action::{Action, Actions, OpenCmd},
        observation::Observation,
        types::TradeType,
    },
};

#[serde_as]
#[derive(Debug, Clone, Copy, Serialize)]
pub struct NewsBreakout {
    #[serde(skip)]
    economic_cal_id: EconomicCalendarId,
    #[serde(skip)]
    ohlcv_id: OhlcvId,
    /// Earliest allowed entry time after the news event.
    #[serde_as(as = "DurationSeconds<i64>")]
    earliest_entry: Duration,
    /// Latest allowed entry time after the news event.
    #[serde_as(as = "DurationSeconds<i64>")]
    latest_entry: Duration,

    /// A factor that defines the portion of the news candle's body to risk before a stop-loss is triggered.
    ///
    /// The calculation starts from the news candle's **close price** and moves towards
    /// (or beyond) its **open price**. A higher value means a wider stop-loss and more risk.
    ///
    /// - **`-0.5`**: Places the stop-loss **beyond the close price**, creating an extra safety margin equal to **50%** of the candle's body size.
    /// - **`0.0`**: Places the stop-loss at the **close price**. This risks **0%** of the candle body.
    /// - **`0.5`**: Places the stop-loss at the **midpoint** of the body. This risks **50%** of the body.
    /// - **`1.0`**: Places the stop-loss at the **open price**. This risks **100%** of the candle body.
    /// - **`1.5`**: Places the stop-loss **beyond the open price**, creating an extra risk margin equal to **50%** of the candle's body size.
    ///
    /// # Formulas
    /// Let `body_size = |news_open - news_close|`.
    /// - For **Long** trades: `StopLoss = news_close - body_size * stop_loss_risk_factor`
    /// - For **Short** trades: `StopLoss = news_close + body_size * stop_loss_risk_factor`
    ///
    /// # Long Trade Example (Bullish News Candle: Open=100, Close=110, Body=10)
    /// - `stop_loss_risk_factor = 0.0` -> SL is `110 - 10 * 0.0 = 110`
    /// - `stop_loss_risk_factor = 1.0` -> SL is `110 - 10 * 1.0 = 100`
    /// - `stop_loss_risk_factor = -0.2` -> SL is `110 - 10 * -0.2 = 112` (Extra safety margin)
    ///
    /// # Short Trade Example (Bearish News Candle: Open=100, Close=90, Body=10)
    /// - `stop_loss_risk_factor = 0.0` -> SL is `90 + 10 * 0.0 = 90`
    /// - `stop_loss_risk_factor = 1.0` -> SL is `90 + 10 * 1.0 = 100`
    /// - `stop_loss_risk_factor = -0.2` -> SL is `90 + 10 * -0.2 = 88` (Extra safety margin)
    stop_loss_risk_factor: f64,

    /// Risk-Reward Ratio (RRR) for the strategy.
    ///
    /// The Risk-Reward Ratio defines the relationship between the potential **loss** (risk) and
    /// the potential **gain** (reward) of a trade. It is used to calculate the **take-profit**
    /// level given a known entry price and stop-loss price.
    ///
    /// # Formula
    /// ```text
    /// RRR = |risk| / |reward|
    ///
    /// where:
    /// - risk = |entry_price - stop_loss_price|
    /// - reward = |take_profit_price - entry_price|
    /// ```
    ///
    /// # Interpretation
    /// - `risk_reward_ratio > 1.0` -> risking more than potential reward (caution)
    /// - `risk_reward_ratio = 1.0` -> risk equals reward
    /// - `risk_reward_ratio < 1.0` -> potential reward exceeds risk (favorable)
    ///
    /// # Valid Values
    /// Must be strictly positive (`risk_reward_ratio > 0.0`), otherwise the trade setup is invalid.
    ///
    /// # Take-Profit Calculation
    /// Given a trade entry and stop-loss (from `stop_loss_risk_factor`):
    ///
    /// - **Long Trade** (bullish entry):
    /// ```text
    /// take_profit = entry_price + (entry_price - stop_loss_price) / risk_reward_ratio
    /// ```
    /// - **Short Trade** (bearish entry):
    /// ```text
    /// take_profit = entry_price - (stop_loss_price - entry_price) / risk_reward_ratio
    /// ```
    ///
    /// # Examples
    /// Long trade: entry = 100, stop-loss = 95, risk_reward_ratio = 0.5
    /// ```text
    /// take_profit = 100 + (100 - 95) / 0.5 = 110
    /// ```
    ///
    /// Short trade: entry = 100, stop-loss = 105, risk_reward_ratio = 2.0
    /// ```text
    /// take_profit = 100 - (100 - 105) / 2.0 = 97.5
    /// ```
    risk_reward_ratio: f64,

    // === Internal only ===
    #[serde(skip)]
    phase: NewsPhase,

    #[serde(skip)]
    trade_counter: i64,
}

impl NewsBreakout {
    pub fn baseline(economic_cal_id: EconomicCalendarId, ohlcv_id: OhlcvId) -> Self {
        Self {
            economic_cal_id,
            ohlcv_id,
            earliest_entry: Duration::seconds(480),
            latest_entry: Duration::seconds(3000),
            stop_loss_risk_factor: 0.89,
            risk_reward_ratio: 0.726,
            phase: NewsPhase::default(),
            trade_counter: 0,
        }
    }

    pub fn economic_calendar_id(&self) -> EconomicCalendarId {
        self.economic_cal_id
    }

    pub fn ohlcv_id(&self) -> OhlcvId {
        self.ohlcv_id
    }

    pub fn earliest_entry(&self) -> Duration {
        self.earliest_entry
    }

    pub fn latest_entry(&self) -> Duration {
        self.latest_entry
    }

    pub fn stop_loss_risk_factor(&self) -> f64 {
        self.stop_loss_risk_factor
    }

    pub fn risk_reward_ratio(&self) -> f64 {
        self.risk_reward_ratio
    }

    pub fn with_calendar_id(self, economic_cal_id: EconomicCalendarId) -> Self {
        Self {
            economic_cal_id,
            ..self
        }
    }

    pub fn with_ohlcv_id(self, ohlcv_id: OhlcvId) -> Self {
        Self { ohlcv_id, ..self }
    }

    pub fn with_earliest_entry_candle(self, duration: Duration) -> Self {
        Self {
            earliest_entry: duration,
            ..self
        }
    }

    pub fn with_latest_entry_candle(self, duration: Duration) -> Self {
        Self {
            latest_entry: duration,
            ..self
        }
    }

    pub fn with_stop_loss_risk_factor(self, factor: f64) -> Self {
        Self {
            stop_loss_risk_factor: factor,
            ..self
        }
    }

    pub fn with_risk_reward_ratio(self, ratio: f64) -> ChapatyResult<Self> {
        if ratio <= 0.0 {
            return Err(
                AgentError::InvalidInput("risk_reward_ratio must be > 0.0".to_string()).into(),
            );
        }
        Ok(Self {
            risk_reward_ratio: ratio,
            ..self
        })
    }
}

impl NewsBreakout {
    /// Computes the **stop-loss target** for following a news candle.
    ///
    /// This includes both the stop-loss **price** and the **trade type**,
    /// because the trade direction (Long vs Short) is determined by the
    /// candle’s direction:
    ///
    /// - **Bearish candle** -> follow downward -> `Short`
    /// - **Bullish candle** -> follow upward -> `Long`
    ///
    /// Returns `None` if the candle has no clear direction (e.g., a doji).
    fn stop_loss_target(&self, news_candle: &Ohlcv) -> Option<StopLossTarget> {
        let open = news_candle.open.0;
        let close = news_candle.close.0;
        let body_size = (open - close).abs();

        match news_candle.direction() {
            CandleDirection::Bearish => {
                let price = close + body_size * self.stop_loss_risk_factor;
                Some(StopLossTarget {
                    stop_loss_price: Price(price),
                    trade_type: TradeType::Short,
                })
            }
            CandleDirection::Bullish => {
                let price = close - body_size * self.stop_loss_risk_factor;
                Some(StopLossTarget {
                    stop_loss_price: Price(price),
                    trade_type: TradeType::Long,
                })
            }
            CandleDirection::Doji => None,
        }
    }
}
impl Agent for NewsBreakout {
    fn act(&mut self, obs: Observation) -> ChapatyResult<Actions> {
        let economic_cal_id = self.economic_cal_id;
        let ohlcv_id = self.ohlcv_id;

        let current_time = obs.market_view.current_timestamp();

        // === Early return: skip if already in trade ===
        if obs.states.any_active_trade_for_agent(&self.identifier()) {
            return Ok(Actions::no_op());
        }

        // === 1. Update phase ===
        if let NewsPhase::AwaitingNews = self.phase
            && let Some(news_event) = obs.market_view.economic_news().last_event(&economic_cal_id)
        {
            let news_candle_candidate = obs
                .market_view
                .ohlcv()
                .last_event(&ohlcv_id)
                .filter(|candle| candle.open_timestamp == news_event.timestamp)
                .copied();
            self.phase = NewsPhase::PostNews {
                news_time: news_event.timestamp,
                news_candle: news_candle_candidate,
            };
        }

        // === 2. Decide action ==
        let (news_time, candle) = if let NewsPhase::PostNews {
            news_time,
            news_candle: Some(candle),
        } = self.phase
        {
            (news_time, candle)
        } else {
            self.phase = NewsPhase::AwaitingNews;
            return Ok(Actions::no_op());
        };

        let time_since_news = current_time - news_time;

        if time_since_news < self.earliest_entry {
            return Ok(Actions::no_op());
        }
        if time_since_news > self.latest_entry {
            self.phase = NewsPhase::AwaitingNews;
            return Ok(Actions::no_op());
        }

        // 1. Get Current Price (for Breakout Check & Math)
        let entry_price = obs.market_view.try_resolved_close_price(&ohlcv_id.symbol)?;

        let breakout_up = entry_price.0 > candle.high.0;
        let breakout_down = entry_price.0 < candle.low.0;
        if !breakout_up && !breakout_down {
            return Ok(Actions::no_op()); // no breakout
        }

        let sl_target = match self.stop_loss_target(&candle) {
            Some(tp) => tp,
            None => {
                self.phase = NewsPhase::AwaitingNews;
                return Ok(Actions::no_op());
            }
        };

        // 2. Generate Unique ID
        self.trade_counter += 1;
        let trade_id = TradeId(self.trade_counter);

        // 3. Define Quantity
        let quantity = Quantity(1.0);

        // 4. Construct Command (Struct Init)
        let cmd = OpenCmd {
            agent_id: self.identifier(),
            trade_id,
            trade_type: sl_target.trade_type,
            quantity,

            // EXECUTION: Market Order (None)
            // A breakout strategy must enter immediately. Waiting for a limit
            // at the breakout level might miss the momentum.
            entry_price: None,

            // MATH: We use the calculated targets
            stop_loss: Some(sl_target.stop_loss_price),
            // Note: entry_price is passed here purely for the math calculation
            take_profit: Some(sl_target.take_profit_price(entry_price, self.risk_reward_ratio)),
        };

        self.phase = NewsPhase::AwaitingNews;

        let market_id: MarketId = ohlcv_id.into();
        Ok(Actions::from((market_id, Action::Open(cmd))))
    }

    fn identifier(&self) -> AgentIdentifier {
        AgentIdentifier::Named(Arc::new("NewsBreakout".to_string()))
    }

    fn reset(&mut self) {
        self.phase = NewsPhase::AwaitingNews;
        self.trade_counter = 0;
    }
}

// ================================================================================================
// Helper Structs
// ================================================================================================

/// Result of a stop-loss calculation.
///
/// Includes both the target price and the trade direction,
/// since the direction is implied by the news candle.
struct StopLossTarget {
    stop_loss_price: Price,
    trade_type: TradeType,
}

impl StopLossTarget {
    /// Computes the take-profit price for this stop-loss target, given the
    /// trade entry price and a risk-reward ratio (RRR).
    ///
    /// # Formula
    /// - **Long Trade**:
    /// ```text
    /// take_profit = entry_price + (entry_price - stop_loss_price) / risk_reward_ratio
    /// ```
    ///
    /// - **Short Trade**:
    /// ```text
    /// take_profit = entry_price - (stop_loss_price - entry_price) / risk_reward_ratio
    /// ```
    ///
    /// # Panics
    /// - If `risk_reward_ratio <= 0.0`, since a non-positive RRR is invalid.
    fn take_profit_price(&self, entry_price: Price, risk_reward_ratio: f64) -> Price {
        let sl = self.stop_loss_price.0;
        let entry = entry_price.0;

        let sl = match self.trade_type {
            TradeType::Long => entry + (entry - sl) / risk_reward_ratio,
            TradeType::Short => entry - (sl - entry) / risk_reward_ratio,
        };

        Price(sl)
    }
}

// ================================================================================================
// Grid Generator
// ================================================================================================

pub struct NewsBreakoutGrid {
    cal_id: EconomicCalendarId,
    market_id: OhlcvId,
    earliest_entry: (Duration, Duration),
    latest_entry: (Duration, Duration),
    stop_loss_risk_factor: GridAxis,
    risk_reward_ratio: GridAxis,
}

impl NewsBreakoutGrid {
    /// Creates a grid generator with a default "Baseline" search space.
    pub fn baseline(cal_id: EconomicCalendarId, market_id: OhlcvId) -> ChapatyResult<Self> {
        Ok(Self {
            cal_id,
            market_id,
            earliest_entry: (Duration::minutes(1), Duration::minutes(6)),
            latest_entry: (Duration::minutes(20), Duration::minutes(28)),
            stop_loss_risk_factor: GridAxis::new("0.5", "1.5", "0.01")?,
            risk_reward_ratio: GridAxis::new("0.1", "2.6", "0.01")?,
        })
    }

    /// Overrides the range of earliest entry times. Range is `[start, end)`.
    pub fn with_earliest_entry_range(self, start: Duration, end: Duration) -> Self {
        Self {
            earliest_entry: (start, end),
            ..self
        }
    }

    /// Overrides the range of latest entry times. Range is `[start, end)`.
    pub fn with_latest_entry_range(self, start: Duration, end: Duration) -> Self {
        Self {
            latest_entry: (start, end),
            ..self
        }
    }

    /// Overrides the stop-loss risk factor range. Range is `[start, end)`.
    pub fn with_stop_loss_risk_factor(self, axis: GridAxis) -> Self {
        Self {
            stop_loss_risk_factor: axis,
            ..self
        }
    }

    /// Overrides the risk reward ratio range. Range is `[start, end)`.
    pub fn with_risk_reward_ratio(self, axis: GridAxis) -> Self {
        Self {
            risk_reward_ratio: axis,
            ..self
        }
    }

    pub fn build(self) -> (usize, impl ParallelIterator<Item = (usize, NewsBreakout)>) {
        let (start_earliest, end_earliest) = self.earliest_entry;
        let (start_latest, end_latest) = self.latest_entry;

        // === 1. Generate Axes ===
        let stop_loss_risk_factors = self.stop_loss_risk_factor.generate();
        let risk_reward_ratios = self.risk_reward_ratio.generate();

        let earliest_entries = (start_earliest.num_minutes()..end_earliest.num_minutes())
            .map(Duration::minutes)
            .collect::<Vec<_>>();

        let latest_entries = (start_latest.num_minutes()..end_latest.num_minutes())
            .map(Duration::minutes)
            .collect::<Vec<_>>();

        // === 2. Eagerly Collect Valid Args (The "Fat" Vector) ===
        let mut args = iproduct!(
            risk_reward_ratios,
            stop_loss_risk_factors,
            latest_entries,
            earliest_entries
        )
        .filter(|(_, _, latest, earliest)| earliest < latest)
        .enumerate()
        .map(|(uid, (rrr, slrf, latest, earliest))| NewsBreakoutArgs {
            uid,
            rrr,
            slrf,
            latest,
            earliest,
        })
        .collect::<Vec<_>>();

        let mut rng = rand::rng();
        args.shuffle(&mut rng);

        let total_combinations = args.len();
        let cal_id = self.cal_id;
        let market_id = self.market_id;

        // === 3. Simple Parallel Iterator ===
        let iterator = args.into_par_iter().map(move |arg| {
            (
                arg.uid,
                NewsBreakout::baseline(cal_id, market_id)
                    .with_earliest_entry_candle(arg.earliest)
                    .with_latest_entry_candle(arg.latest)
                    .with_stop_loss_risk_factor(arg.slrf)
                    .with_risk_reward_ratio(arg.rrr)
                    .expect("Valid grid parameters"),
            )
        });

        (total_combinations, iterator)
    }
}

#[derive(Debug, Clone, Copy)]
struct NewsBreakoutArgs {
    uid: usize,
    rrr: f64,
    slrf: f64,
    latest: Duration,
    earliest: Duration,
}