redfolder 1.0.0

Async economic calendar client and automated trading blackout engine for algorithmic traders and prop firms
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
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// Currency code representation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Currency {
    #[serde(alias = "usd")]
    USD,
    #[serde(alias = "eur")]
    EUR,
    #[serde(alias = "gbp")]
    GBP,
    #[serde(alias = "jpy")]
    JPY,
    #[serde(alias = "aud")]
    AUD,
    #[serde(alias = "cad")]
    CAD,
    #[serde(alias = "chf")]
    CHF,
    #[serde(alias = "nzd")]
    NZD,
    #[serde(alias = "cny")]
    CNY,
    #[serde(alias = "all", alias = "ALL", alias = "Global", alias = "global")]
    All,
    #[serde(untagged)]
    Custom(String),
}

impl Currency {
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Currency::USD => "USD",
            Currency::EUR => "EUR",
            Currency::GBP => "GBP",
            Currency::JPY => "JPY",
            Currency::AUD => "AUD",
            Currency::CAD => "CAD",
            Currency::CHF => "CHF",
            Currency::NZD => "NZD",
            Currency::CNY => "CNY",
            Currency::All => "All",
            Currency::Custom(s) => s.as_str(),
        }
    }

    #[must_use]
    pub fn matches_str(&self, text: &str) -> bool {
        match self {
            Currency::All => true,
            Currency::Custom(s) => {
                s.eq_ignore_ascii_case(text)
                    || text.eq_ignore_ascii_case("all")
                    || text.eq_ignore_ascii_case("global")
            }
            standard => {
                standard.as_str().eq_ignore_ascii_case(text)
                    || text.eq_ignore_ascii_case("all")
                    || text.eq_ignore_ascii_case("global")
            }
        }
    }
}

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

impl FromStr for Currency {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        Ok(match trimmed.to_uppercase().as_str() {
            "USD" => Currency::USD,
            "EUR" => Currency::EUR,
            "GBP" => Currency::GBP,
            "JPY" => Currency::JPY,
            "AUD" => Currency::AUD,
            "CAD" => Currency::CAD,
            "CHF" => Currency::CHF,
            "NZD" => Currency::NZD,
            "CNY" => Currency::CNY,
            "ALL" | "GLOBAL" => Currency::All,
            _ => Currency::Custom(trimmed.to_string()),
        })
    }
}

impl From<&str> for Currency {
    fn from(s: &str) -> Self {
        s.parse().unwrap()
    }
}

impl From<String> for Currency {
    fn from(s: String) -> Self {
        s.as_str().into()
    }
}

impl From<Currency> for String {
    fn from(c: Currency) -> Self {
        c.to_string()
    }
}

impl AsRef<str> for Currency {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl PartialEq<&str> for Currency {
    fn eq(&self, other: &&str) -> bool {
        self.matches_str(other)
    }
}

impl PartialEq<Currency> for &str {
    fn eq(&self, other: &Currency) -> bool {
        other.matches_str(self)
    }
}

impl PartialEq<String> for Currency {
    fn eq(&self, other: &String) -> bool {
        self.matches_str(other)
    }
}

impl PartialEq<Currency> for String {
    fn eq(&self, other: &Currency) -> bool {
        other.matches_str(self)
    }
}

/// Impact severity level of an economic event.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Impact {
    #[serde(rename = "Non-Economic", alias = "None", alias = "Holiday")]
    NonEconomic,
    #[serde(rename = "Low", alias = "low")]
    Low,
    #[serde(rename = "Medium", alias = "medium", alias = "Med")]
    Medium,
    #[serde(rename = "High", alias = "high", alias = "Red")]
    High,
    #[serde(untagged)]
    Custom(String),
}

impl Impact {
    #[must_use]
    pub fn is_high(&self) -> bool {
        matches!(self, Impact::High)
    }

    #[must_use]
    pub fn is_red_folder(&self) -> bool {
        self.is_high()
    }

    #[must_use]
    pub fn matches_str(&self, text: &str) -> bool {
        match self {
            Impact::High => text.eq_ignore_ascii_case("High") || text.eq_ignore_ascii_case("Red"),
            Impact::Medium => {
                text.eq_ignore_ascii_case("Medium") || text.eq_ignore_ascii_case("Med")
            }
            Impact::Low => text.eq_ignore_ascii_case("Low"),
            Impact::NonEconomic => {
                text.eq_ignore_ascii_case("Non-Economic")
                    || text.eq_ignore_ascii_case("None")
                    || text.eq_ignore_ascii_case("Holiday")
            }
            Impact::Custom(s) => s.eq_ignore_ascii_case(text),
        }
    }
}

impl From<Impact> for String {
    fn from(i: Impact) -> Self {
        i.to_string()
    }
}

impl From<&str> for Impact {
    fn from(s: &str) -> Self {
        s.parse().unwrap()
    }
}

impl From<String> for Impact {
    fn from(s: String) -> Self {
        s.as_str().into()
    }
}

impl fmt::Display for Impact {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Impact::High => write!(f, "High"),
            Impact::Medium => write!(f, "Medium"),
            Impact::Low => write!(f, "Low"),
            Impact::NonEconomic => write!(f, "Non-Economic"),
            Impact::Custom(s) => write!(f, "{}", s),
        }
    }
}

impl AsRef<str> for Impact {
    fn as_ref(&self) -> &str {
        match self {
            Impact::High => "High",
            Impact::Medium => "Medium",
            Impact::Low => "Low",
            Impact::NonEconomic => "Non-Economic",
            Impact::Custom(s) => s.as_str(),
        }
    }
}

impl PartialEq<&str> for Impact {
    fn eq(&self, other: &&str) -> bool {
        self.matches_str(other)
    }
}

impl PartialEq<Impact> for &str {
    fn eq(&self, other: &Impact) -> bool {
        other.matches_str(self)
    }
}

impl PartialEq<String> for Impact {
    fn eq(&self, other: &String) -> bool {
        self.matches_str(other)
    }
}

impl PartialEq<Impact> for String {
    fn eq(&self, other: &Impact) -> bool {
        other.matches_str(self)
    }
}

impl FromStr for Impact {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.trim().to_lowercase().as_str() {
            "high" | "red" => Impact::High,
            "medium" | "med" => Impact::Medium,
            "low" => Impact::Low,
            "non-economic" | "none" | "holiday" => Impact::NonEconomic,
            other => Impact::Custom(other.to_string()),
        })
    }
}

/// Timing precision category for an economic calendar event.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EventTiming {
    /// Exact scheduled release instant.
    Exact(DateTime<Utc>),
    /// Tentative release scheduled on a specific date without a confirmed time.
    TentativeDate(NaiveDate),
    /// All-day event or multi-day summit covering an entire calendar day.
    AllDay(NaiveDate),
}

impl EventTiming {
    /// Returns the exact timestamp if this event has one.
    #[must_use]
    pub fn exact_time(&self) -> Option<DateTime<Utc>> {
        match self {
            EventTiming::Exact(dt) => Some(*dt),
            _ => None,
        }
    }

    /// Whether this event has a precise scheduled release timestamp.
    #[must_use]
    pub fn is_exact(&self) -> bool {
        matches!(self, EventTiming::Exact(_))
    }

    /// Whether this event's timing is tentative.
    #[must_use]
    pub fn is_tentative(&self) -> bool {
        matches!(self, EventTiming::TentativeDate(_))
    }

    /// Whether this is an all-day event.
    #[must_use]
    pub fn is_all_day(&self) -> bool {
        matches!(self, EventTiming::AllDay(_))
    }
}

/// A parsed economic calendar event from the calendar feed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EconomicEvent {
    pub title: String,
    pub country: String,
    pub impact: String,
    pub datetime: DateTime<Utc>,
    #[serde(default = "default_event_timing")]
    pub timing: EventTiming,
}

fn default_event_timing() -> EventTiming {
    EventTiming::Exact(Utc::now())
}

impl EconomicEvent {
    /// Create a new exact economic event.
    pub fn new_exact(
        title: impl Into<String>,
        country: impl Into<String>,
        impact: impl Into<String>,
        datetime: DateTime<Utc>,
    ) -> Self {
        Self {
            title: title.into(),
            country: country.into(),
            impact: impact.into(),
            datetime,
            timing: EventTiming::Exact(datetime),
        }
    }

    /// Returns the exact release timestamp if known.
    #[must_use]
    pub fn exact_time(&self) -> Option<DateTime<Utc>> {
        self.timing.exact_time()
    }
}

/// Classification discriminant for synthetic or custom-generated blackout events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CustomEventKind {
    /// Synthetic weekend market close curfew.
    WeekendCurfew,
    /// Synthetic safety blackout injected during calendar data outage or staleness under FailClosed policy.
    FailClosedSafety,
}

/// An individual event recorded within a merged blackout window.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WindowEvent {
    /// True if generated by a weekend curfew or custom rule rather than external calendar API.
    pub is_custom: bool,
    /// Typed classification for custom/synthetic events, if applicable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_kind: Option<CustomEventKind>,
    pub event_time: DateTime<Utc>,
    pub country: String,
    pub impact: String,
    pub title: String,
}

impl WindowEvent {
    /// Checks whether this event represents a weekend curfew blackout.
    #[must_use]
    pub fn is_weekend_curfew(&self) -> bool {
        self.custom_kind == Some(CustomEventKind::WeekendCurfew)
            || (self.is_custom && self.custom_kind.is_none() && !self.title.contains("Fail-Closed"))
    }

    /// Checks whether this event represents a synthetic fail-closed safety blackout.
    #[must_use]
    pub fn is_fail_closed_safety(&self) -> bool {
        self.custom_kind == Some(CustomEventKind::FailClosedSafety)
            || (self.is_custom && self.custom_kind.is_none() && self.title.contains("Fail-Closed"))
    }
}

/// A merged blackout window containing one or more events.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BlackoutWindow {
    pub start: DateTime<Utc>,
    pub end: DateTime<Utc>,
    pub events: Vec<WindowEvent>,
}

impl BlackoutWindow {
    /// Returns the minutes remaining until this blackout window ends.
    /// If the window has already passed, returns 0.
    #[must_use]
    pub fn remaining_minutes(&self) -> i64 {
        (self.end - Utc::now()).num_seconds().max(0) / 60
    }

    /// Total duration of the window in minutes.
    #[must_use]
    pub fn duration_minutes(&self) -> i64 {
        (self.end - self.start).num_seconds() / 60
    }

    /// Whether this window is currently active at the specified timestamp.
    /// Uses standard half-open interval semantics: `[start, end)`.
    #[must_use]
    pub fn is_active_at(&self, time: DateTime<Utc>) -> bool {
        self.start <= time && time < self.end
    }

    /// Whether this window is currently active right now.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.is_active_at(Utc::now())
    }

    /// Primary event title in this window (or summary if multiple).
    #[must_use]
    pub fn summary_title(&self) -> String {
        if self.events.is_empty() {
            "Blackout Window".to_string()
        } else if self.events.len() == 1 {
            self.events[0].title.clone()
        } else {
            format!(
                "{} (+{} events)",
                self.events[0].title,
                self.events.len() - 1
            )
        }
    }
}

/// Event sent to workers or subscribers when blackout status changes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BlackoutNotification {
    pub active: bool,
    pub window: Option<BlackoutWindow>,
}

/// Policy governing trading blackout behavior when calendar data is unavailable, empty, or stale.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FailSafeMode {
    /// Permissive mode: if calendar data is unavailable or stale, assume no economic blackout is active (fail open).
    #[default]
    #[serde(rename = "fail_open", alias = "open", alias = "permissive")]
    FailOpen,

    /// Defensive mode: if calendar data is unavailable or stale, assume blackout is active (fail closed).
    /// Halts automated trading during data feed outages to protect prop firm accounts from disqualification.
    #[serde(rename = "fail_closed", alias = "closed", alias = "strict")]
    FailClosed,
}

impl FailSafeMode {
    /// Returns true if this policy dictates failing closed (blackout on data loss).
    #[must_use]
    pub fn is_fail_closed(&self) -> bool {
        matches!(self, FailSafeMode::FailClosed)
    }

    /// Returns true if this policy dictates failing open (allow trading on data loss).
    #[must_use]
    pub fn is_fail_open(&self) -> bool {
        matches!(self, FailSafeMode::FailOpen)
    }
}

impl fmt::Display for FailSafeMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FailSafeMode::FailOpen => write!(f, "fail_open"),
            FailSafeMode::FailClosed => write!(f, "fail_closed"),
        }
    }
}

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

    #[test]
    fn test_impact_parsing_and_matching() {
        assert_eq!("High".parse::<Impact>().unwrap(), Impact::High);
        assert_eq!("red".parse::<Impact>().unwrap(), Impact::High);
        assert_eq!("Medium".parse::<Impact>().unwrap(), Impact::Medium);
        assert_eq!("low".parse::<Impact>().unwrap(), Impact::Low);

        let high = Impact::High;
        assert!(high.is_high());
        assert!(high.matches_str("high"));
        assert!(high.matches_str("red"));
        assert!(!high.matches_str("medium"));
    }

    #[test]
    fn test_blackout_window_methods() {
        let now = Utc::now();
        let window = BlackoutWindow {
            start: now - Duration::minutes(10),
            end: now + Duration::minutes(20),
            events: vec![WindowEvent {
                is_custom: false,
                custom_kind: None,
                event_time: now,
                country: "USD".to_string(),
                impact: "High".to_string(),
                title: "US CPI Release".to_string(),
            }],
        };

        assert!(window.is_active());
        assert_eq!(window.duration_minutes(), 30);
        assert!(window.remaining_minutes() >= 19 && window.remaining_minutes() <= 20);
        assert_eq!(window.summary_title(), "US CPI Release");
    }

    #[test]
    fn test_currency_parsing_and_matching() {
        assert_eq!("USD".parse::<Currency>().unwrap(), Currency::USD);
        assert_eq!("usd".parse::<Currency>().unwrap(), Currency::USD);
        assert_eq!("eur".parse::<Currency>().unwrap(), Currency::EUR);
        assert_eq!("ALL".parse::<Currency>().unwrap(), Currency::All);
        assert_eq!(
            "XAU".parse::<Currency>().unwrap(),
            Currency::Custom("XAU".into())
        );

        let usd = Currency::USD;
        assert!(usd.matches_str("USD"));
        assert!(usd.matches_str("usd"));
        assert!(usd.matches_str("all"));
        assert!(!usd.matches_str("EUR"));

        let all = Currency::All;
        assert!(all.matches_str("USD"));
        assert!(all.matches_str("JPY"));

        assert_eq!(String::from(Currency::EUR), "EUR");
        assert_eq!(Currency::from("GBP"), Currency::GBP);
    }

    #[test]
    fn test_fail_safe_mode() {
        assert_eq!(FailSafeMode::default(), FailSafeMode::FailOpen);
        assert!(FailSafeMode::FailClosed.is_fail_closed());
        assert!(!FailSafeMode::FailClosed.is_fail_open());
        assert!(FailSafeMode::FailOpen.is_fail_open());
        assert!(!FailSafeMode::FailOpen.is_fail_closed());
        assert_eq!(FailSafeMode::FailOpen.to_string(), "fail_open");
        assert_eq!(FailSafeMode::FailClosed.to_string(), "fail_closed");
    }

    #[test]
    fn test_custom_event_kind_and_window_event_methods() {
        let now = Utc::now();
        let curfew_ev = WindowEvent {
            is_custom: true,
            custom_kind: Some(CustomEventKind::WeekendCurfew),
            event_time: now,
            country: "Global".into(),
            impact: "High".into(),
            title: "Weekend Market Close Curfew (Friday 20:30 UTC -> Monday 00:00 UTC)".into(),
        };
        assert!(curfew_ev.is_weekend_curfew());
        assert!(!curfew_ev.is_fail_closed_safety());

        let safety_ev = WindowEvent {
            is_custom: true,
            custom_kind: Some(CustomEventKind::FailClosedSafety),
            event_time: now,
            country: "Global".into(),
            impact: "High".into(),
            title: "Calendar Data Unavailable (Fail-Closed Safety Blackout)".into(),
        };
        assert!(safety_ev.is_fail_closed_safety());
        assert!(!safety_ev.is_weekend_curfew());

        // Legacy backwards compatibility check when custom_kind is None
        let legacy_safety = WindowEvent {
            is_custom: true,
            custom_kind: None,
            event_time: now,
            country: "Global".into(),
            impact: "High".into(),
            title: "Calendar Data Stale (Fail-Closed Safety Blackout)".into(),
        };
        assert!(legacy_safety.is_fail_closed_safety());
        assert!(!legacy_safety.is_weekend_curfew());
    }
}