quantoxide 0.6.2

Rust framework for developing, backtesting, and deploying Bitcoin futures trading strategies.
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
use std::{fmt, result::Result};

use chrono::Duration;

pub mod error;

use error::{LookbackValidationError, MinIterationIntervalValidationError, PeriodValidationError};

/// Supported OHLC resolutions for trading operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OhlcResolution {
    /// One-minute candles.
    OneMinute,
    /// Three-minute candles.
    ThreeMinutes,
    /// Five-minute candles.
    FiveMinutes,
    /// Ten-minute candles.
    TenMinutes,
    /// Fifteen-minute candles.
    FifteenMinutes,
    /// Thirty-minute candles.
    ThirtyMinutes,
    /// Forty-five-minute candles.
    FortyFiveMinutes,
    /// One-hour candles.
    OneHour,
    /// Two-hour candles.
    TwoHours,
    /// Three-hour candles.
    ThreeHours,
    /// Four-hour candles.
    FourHours,
    /// One-day candles.
    OneDay,
}

impl OhlcResolution {
    /// Returns the resolution duration in minutes.
    pub const fn as_minutes(&self) -> u32 {
        match self {
            Self::OneMinute => 1,
            Self::ThreeMinutes => 3,
            Self::FiveMinutes => 5,
            Self::TenMinutes => 10,
            Self::FifteenMinutes => 15,
            Self::ThirtyMinutes => 30,
            Self::FortyFiveMinutes => 45,
            Self::OneHour => 60,
            Self::TwoHours => 120,
            Self::ThreeHours => 180,
            Self::FourHours => 240,
            Self::OneDay => 1440,
        }
    }

    /// Returns the resolution duration in seconds.
    pub const fn as_seconds(&self) -> u32 {
        self.as_minutes() * 60
    }
}

impl fmt::Display for OhlcResolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OneMinute => write!(f, "1m"),
            Self::ThreeMinutes => write!(f, "3m"),
            Self::FiveMinutes => write!(f, "5m"),
            Self::TenMinutes => write!(f, "10m"),
            Self::FifteenMinutes => write!(f, "15m"),
            Self::ThirtyMinutes => write!(f, "30m"),
            Self::FortyFiveMinutes => write!(f, "45m"),
            Self::OneHour => write!(f, "1h"),
            Self::TwoHours => write!(f, "2h"),
            Self::ThreeHours => write!(f, "3h"),
            Self::FourHours => write!(f, "4h"),
            Self::OneDay => write!(f, "1d"),
        }
    }
}

/// Validated period specifying how many candles of historical data to provide for analysis.
///
/// Represents a number of candles with enforced minimum and maximum bounds. The actual time span
/// depends on the candle resolution being used. For example, a period of 10 candles at 1-minute
/// resolution covers 10 minutes, while at 1-hour resolution it covers 10 hours.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub struct Period(u32);

impl Period {
    /// Minimum period: 1 candle.
    pub const MIN: Self = Self(1);

    /// Maximum period: 720,000 candles.
    ///
    /// This is derived from [`Lookback::MAX`] at 1-minute resolution and is the theoretical
    /// `Period` upper bound for the finest resolution. The effective `Period` limit depends on the
    /// candle resolution adopted since [`Lookback::MAX`] cannot be exceeded.
    pub const MAX: Self = Self(Lookback::MAX.num_minutes() as u32);

    /// Returns the period as a [`Duration`] for the given resolution.
    ///
    /// This calculates the time span by multiplying the number of candles by the resolution's
    /// duration in minutes.
    ///
    /// # Examples
    ///
    /// ```
    /// use quantoxide::models::{Period, OhlcResolution};
    ///
    /// let period = Period::try_from(10).unwrap();
    ///
    /// // Duration is candles * resolution in minutes
    /// let duration = period.as_duration(OhlcResolution::FiveMinutes);
    /// assert_eq!(duration.num_minutes(), 50);
    /// ```
    pub fn as_duration(&self, resolution: OhlcResolution) -> Duration {
        Duration::minutes(self.0 as i64 * resolution.as_minutes() as i64)
    }

    /// Returns the number of candles as a `u32`.
    pub const fn as_u32(&self) -> u32 {
        self.0
    }

    /// Returns the number of candles as a `u64`.
    pub const fn as_u64(&self) -> u64 {
        self.0 as u64
    }

    /// Returns the number of candles as a `usize`.
    pub const fn as_usize(&self) -> usize {
        self.0 as usize
    }

    /// Returns the number of candles as an `i32`.
    pub const fn as_i32(&self) -> i32 {
        self.0 as i32
    }

    /// Returns the number of candles as an `i64`.
    pub const fn as_i64(&self) -> i64 {
        self.0 as i64
    }

    /// Returns the number of candles as an `f64`.
    pub const fn as_f64(&self) -> f64 {
        self.0 as f64
    }
}

impl From<Period> for u32 {
    fn from(value: Period) -> Self {
        value.0
    }
}

impl From<Period> for u64 {
    fn from(value: Period) -> Self {
        value.0 as u64
    }
}

impl From<Period> for u128 {
    fn from(value: Period) -> Self {
        value.0 as u128
    }
}

impl From<Period> for usize {
    fn from(value: Period) -> Self {
        value.0 as usize
    }
}

impl From<Period> for i32 {
    fn from(value: Period) -> Self {
        value.0 as i32
    }
}

impl From<Period> for i64 {
    fn from(value: Period) -> Self {
        value.0 as i64
    }
}

impl From<Period> for i128 {
    fn from(value: Period) -> Self {
        value.0 as i128
    }
}

impl From<Period> for f64 {
    fn from(value: Period) -> Self {
        value.as_f64()
    }
}

impl TryFrom<u8> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as u128)
    }
}

impl TryFrom<u16> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: u16) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as u128)
    }
}

impl TryFrom<u32> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as u128)
    }
}

impl TryFrom<u64> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: u64) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as u128)
    }
}

impl TryFrom<u128> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: u128) -> std::result::Result<Self, Self::Error> {
        if value < Self::MIN.0 as u128 {
            return Err(PeriodValidationError::TooShort {
                value: value as i128,
            });
        }

        if value > Self::MAX.0 as u128 {
            return Err(PeriodValidationError::TooLong { value });
        }

        Ok(Self(value as u32))
    }
}

impl TryFrom<usize> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: usize) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as u128)
    }
}

impl TryFrom<i8> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: i8) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as i128)
    }
}

impl TryFrom<i16> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: i16) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as i128)
    }
}

impl TryFrom<i32> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: i32) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as i128)
    }
}

impl TryFrom<i64> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: i64) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as i128)
    }
}

impl TryFrom<i128> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: i128) -> std::result::Result<Self, Self::Error> {
        if value < Self::MIN.0 as i128 {
            return Err(PeriodValidationError::TooShort { value });
        }

        if value > Self::MAX.0 as i128 {
            return Err(PeriodValidationError::TooLong {
                value: value as u128,
            });
        }

        Ok(Self(value as u32))
    }
}

impl TryFrom<isize> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: isize) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as i128)
    }
}

impl TryFrom<f32> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: f32) -> std::result::Result<Self, Self::Error> {
        Self::try_from(value as f64)
    }
}

impl TryFrom<f64> for Period {
    type Error = PeriodValidationError;

    fn try_from(value: f64) -> std::result::Result<Self, Self::Error> {
        if value.fract() != 0.0 {
            return Err(PeriodValidationError::NotAnInteger { value });
        }

        Self::try_from(value as i128)
    }
}

impl fmt::Display for Period {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Validated minimum interval between successive iterations.
///
/// Represents a duration with enforced bounds to prevent iterations from running too frequently or
/// too infrequently.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub struct MinIterationInterval(Duration);

impl MinIterationInterval {
    /// Minimum supported interval between successive iterations: 5 seconds.
    pub const MIN: Self = Self(Duration::seconds(5));

    /// Maximum supported interval between successive iterations: 1 hour.
    pub const MAX: Self = Self(Duration::hours(1));

    /// Creates a minimum iteration interval from a number of seconds.
    ///
    /// Returns [`MinIterationIntervalValidationError`] when `secs` is outside the supported
    /// interval bounds.
    pub fn seconds(secs: u64) -> Result<Self, MinIterationIntervalValidationError> {
        Self::try_from(Duration::seconds(secs as i64))
    }

    /// Creates a minimum iteration interval from a number of minutes.
    ///
    /// Returns [`MinIterationIntervalValidationError`] when `mins` is outside the supported
    /// interval bounds.
    pub fn minutes(mins: u64) -> Result<Self, MinIterationIntervalValidationError> {
        Self::try_from(Duration::minutes(mins as i64))
    }

    /// Returns the minimum iteration interval as a [`Duration`].
    pub fn as_duration(&self) -> Duration {
        self.0
    }
}

impl TryFrom<Duration> for MinIterationInterval {
    type Error = MinIterationIntervalValidationError;

    fn try_from(value: Duration) -> Result<Self, Self::Error> {
        if value < Self::MIN.0 {
            return Err(MinIterationIntervalValidationError::TooShort { value });
        }

        if value > Self::MAX.0 {
            return Err(MinIterationIntervalValidationError::TooLong { value });
        }

        Ok(Self(value))
    }
}

impl fmt::Display for MinIterationInterval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Historical candle data configuration specifying resolution and period.
///
/// Combines resolution (candle size) and period (number of candles) into a single configuration.
/// When an operator or evaluator needs historical candle data, both values are required together.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Lookback {
    resolution: OhlcResolution,
    period: Period,
}

impl Lookback {
    /// Maximum lookback duration: 500 days.
    ///
    /// This caps the total time span a lookback can cover, regardless of resolution. For example,
    /// 500 candles at daily resolution (500 days) or 720,000 candles at 1-minute resolution
    /// (also 500 days) both reach this limit.
    pub const MAX: Duration = Duration::days(500);

    /// Creates a new lookback configuration with the specified resolution and period.
    ///
    /// Returns an error if the period is invalid or if the resulting lookback duration exceeds
    /// [`Self::MAX`].
    pub fn new<P>(resolution: OhlcResolution, period: P) -> Result<Self, LookbackValidationError>
    where
        P: TryInto<Period>,
        P::Error: Into<LookbackValidationError>,
    {
        let period = period.try_into().map_err(Into::into)?;
        let duration = period.as_duration(resolution);

        if duration > Self::MAX {
            return Err(LookbackValidationError::ExceedsMaxLookback { duration });
        }

        Ok(Self { resolution, period })
    }

    /// Returns the candle resolution.
    pub fn resolution(&self) -> OhlcResolution {
        self.resolution
    }

    /// Returns the lookback period (number of candles).
    pub fn period(&self) -> Period {
        self.period
    }

    /// Returns the lookback as a duration.
    pub fn as_duration(&self) -> Duration {
        self.period.as_duration(self.resolution)
    }
}

impl Default for Lookback {
    fn default() -> Self {
        Self {
            resolution: OhlcResolution::FiveMinutes,
            period: Period(20),
        }
    }
}

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