quantoxide 0.5.4

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
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
use std::{pin::Pin, sync::Arc};

use chrono::Duration;
use futures::TryFutureExt;
use tokio::{
    sync::{broadcast, mpsc},
    time,
};

use lnm_sdk::{api_v2::WebSocketClient, api_v3::RestClient};

use crate::{
    db::{Database, models::PriceTickRow},
    util::{AbortOnDropHandle, Never},
};

use super::{
    config::{SyncConfig, SyncProcessConfig},
    engine::SyncModeInt,
    state::{SyncStatus, SyncStatusManager, SyncStatusNotSynced, SyncTransmitter},
};

pub(crate) mod error;
pub(crate) mod real_time_collection_task;
pub(crate) mod sync_funding_settlements_task;
pub(crate) mod sync_price_history_task;

use error::{Result, SyncProcessError, SyncProcessFatalError, SyncProcessRecoverableError};
use real_time_collection_task::RealTimeCollectionTask;
use sync_funding_settlements_task::{
    FundingSettlementsStateTransmitter, SyncFundingSettlementsTask,
    error::SyncFundingSettlementsError, funding_settlements_state::FundingSettlementsState,
};
use sync_price_history_task::{
    PriceHistoryStateTransmitter, SyncPriceHistoryTask, error::SyncPriceHistoryError,
    price_history_state::PriceHistoryState,
};

pub(super) struct SyncProcess {
    config: SyncProcessConfig,
    db: Arc<Database>,
    mode_int: SyncModeInt,
    shutdown_tx: broadcast::Sender<()>,
    status_manager: Arc<SyncStatusManager>,
    update_tx: SyncTransmitter,
}

impl SyncProcess {
    #[allow(clippy::too_many_arguments)]
    pub fn spawn(
        config: &SyncConfig,
        db: Arc<Database>,
        mode_int: SyncModeInt,
        shutdown_tx: broadcast::Sender<()>,
        status_manager: Arc<SyncStatusManager>,
        update_tx: SyncTransmitter,
    ) -> AbortOnDropHandle<()> {
        let config = config.into();

        tokio::spawn(async move {
            let process = Self {
                config,
                db,
                mode_int,
                shutdown_tx,
                status_manager,
                update_tx,
            };

            process.recovery_loop().await
        })
        .into()
    }

    async fn recovery_loop(self) {
        self.status_manager
            .update(SyncStatusNotSynced::Starting.into());

        let mut shutdown_rx = self.shutdown_tx.subscribe();

        loop {
            let sync_process_error = tokio::select! {
                Err(sync_error) = self.run_mode() => sync_error,
                shutdown_res = shutdown_rx.recv() => {
                    let Err(e) = shutdown_res else {
                        // Shutdown signal received
                        return;
                    };

                    SyncProcessFatalError::ShutdownSignalRecv(e).into()
                }
            };

            match sync_process_error {
                SyncProcessError::Fatal(err) => {
                    self.status_manager.update(err.into());
                    return;
                }
                SyncProcessError::Recoverable(err) => {
                    self.status_manager.update(err.into());
                }
            }

            // Handle shutdown signals while waiting for `restart_interval`

            tokio::select! {
                _ = time::sleep(self.config.restart_interval()) => {} // Loop restarts
                shutdown_res = shutdown_rx.recv() => {
                    if let Err(e) = shutdown_res {
                        let status = SyncProcessFatalError::ShutdownSignalRecv(e).into();
                        self.status_manager.update(status);
                    }
                    return;
                }
            }

            self.status_manager
                .update(SyncStatusNotSynced::Restarting.into());
        }
    }

    fn run_mode(&self) -> Pin<Box<dyn Future<Output = Result<Never>> + Send + '_>> {
        match &self.mode_int {
            SyncModeInt::Backfill { api_rest } => Box::pin(self.run_backfill(api_rest)),
            SyncModeInt::LiveNoLookback { api_rest, api_ws } => {
                Box::pin(self.run_live_no_lookback(api_rest, api_ws))
            }
            SyncModeInt::LiveWithLookback {
                api_rest,
                api_ws,
                lookback,
            } => Box::pin(self.run_live_with_lookback(api_rest, api_ws, lookback.as_duration())),
            SyncModeInt::Full { api_rest, api_ws } => Box::pin(self.run_full(api_rest, api_ws)),
        }
    }

    async fn run_backfill(&self, api_rest: &Arc<RestClient>) -> Result<Never> {
        let mut flag_gaps_range = self.config.price_history_flag_gap_range();
        let mut flag_missing_range = self.config.funding_settlement_flag_missing_range();

        // Send initial state so both TUI panes can be populated from the start

        self.status_manager
            .update(SyncStatusNotSynced::InProgress.into());

        let initial_fs_state = FundingSettlementsState::evaluate_with_reach(
            &self.db,
            self.config.funding_settlement_reach(),
            flag_missing_range,
            None,
        )
        .await
        .map_err(Self::map_funding_settlements_error)?;

        let _ = self.update_tx.send(initial_fs_state.into());

        loop {
            // Backfill full historical price data

            let (history_state_tx, history_state_rx) = mpsc::channel::<PriceHistoryState>(100);

            self.spawn_history_state_update_handler(history_state_rx);

            self.run_price_history_task_backfill(
                api_rest.clone(),
                history_state_tx,
                flag_gaps_range,
            )
            .await?;

            // Backfill funding settlements

            let (funding_state_tx, funding_state_rx) =
                mpsc::channel::<FundingSettlementsState>(100);

            self.spawn_funding_state_update_handler(funding_state_rx);

            let _ = self
                .run_funding_settlements_task_backfill(
                    api_rest.clone(),
                    funding_state_tx,
                    flag_missing_range,
                )
                .await?;

            // Skip expensive gap-detection on subsequent re-sync cycles. Interior gaps are only
            // scanned on the first pass after process (re)start.
            flag_gaps_range = None;
            flag_missing_range = None;

            self.status_manager.update(SyncStatus::Backfilled);

            time::sleep(self.config.price_history_re_backfill_interval()).await;

            self.status_manager
                .update(SyncStatusNotSynced::InProgress.into());
        }
    }

    async fn run_live_no_lookback(
        &self,
        api_rest: &Arc<RestClient>,
        api_ws: &Arc<WebSocketClient>,
    ) -> Result<Never> {
        self.status_manager
            .update(SyncStatusNotSynced::InProgress.into());

        if self.config.ws_enabled() {
            api_ws.reset().await;

            // Start to collect real-time data

            let (price_tick_tx, _) = broadcast::channel::<PriceTickRow>(1_000);

            let mut real_time_collection_handle =
                self.spawn_real_time_collection_task(api_ws.clone(), price_tick_tx.clone());

            if real_time_collection_handle.is_finished() {
                real_time_collection_handle
                    .await
                    .map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                return Err(
                    SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into(),
                );
            }

            // Handle updates and re-syncs

            let mut is_synced = false;
            let mut price_tick_rx = price_tick_tx.subscribe();

            let new_tick_interval_timer =
                || Box::pin(time::sleep(self.config.live_price_tick_max_interval()));
            let mut tick_interval_timer = new_tick_interval_timer();

            loop {
                tokio::select! {
                    rt_res = &mut real_time_collection_handle => {
                        rt_res.map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                        return Err(SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into());
                    }
                    tick_res = price_tick_rx.recv() => {
                        tick_interval_timer = new_tick_interval_timer();

                        let tick = tick_res.map_err(SyncProcessRecoverableError::PriceTickRecv)?;
                        if !is_synced {
                            self.status_manager.update(SyncStatus::Synced);
                            is_synced = true;
                        }

                        let _ = self.update_tx.send(tick.into());
                    }
                    _ = &mut tick_interval_timer => {
                        // Maximum interval between Price Ticks was exceeded
                        return Err(SyncProcessRecoverableError::MaxPriceTickIntevalExceeded(
                            self.config.live_price_tick_max_interval(),
                        )
                        .into());
                    }
                }
            }
        } else {
            // REST polling only

            let (history_state_tx, history_state_rx) = mpsc::channel::<PriceHistoryState>(100);

            self.spawn_history_state_update_handler(history_state_rx);

            self.run_price_history_task_backfill(api_rest.clone(), history_state_tx.clone(), None)
                .await?;

            self.status_manager.update(SyncStatus::Synced);

            loop {
                time::sleep(self.config.price_history_re_sync_interval()).await;

                self.run_price_history_task_backfill(
                    api_rest.clone(),
                    history_state_tx.clone(),
                    None,
                )
                .await?;
            }
        }
    }

    async fn run_live_with_lookback(
        &self,
        api_rest: &Arc<RestClient>,
        api_ws: &Arc<WebSocketClient>,
        lookback: Duration,
    ) -> Result<Never> {
        self.status_manager
            .update(SyncStatusNotSynced::InProgress.into());

        let (history_state_tx, history_state_rx) = mpsc::channel::<PriceHistoryState>(100);

        self.spawn_history_state_update_handler(history_state_rx);

        self.run_price_history_task_live(api_rest.clone(), history_state_tx.clone(), lookback)
            .await?;

        if self.config.ws_enabled() {
            api_ws.reset().await;

            // Start to collect real-time data

            let (price_tick_tx, _) = broadcast::channel::<PriceTickRow>(10_000);

            let mut real_time_collection_handle =
                self.spawn_real_time_collection_task(api_ws.clone(), price_tick_tx.clone());

            if real_time_collection_handle.is_finished() {
                real_time_collection_handle
                    .await
                    .map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                return Err(
                    SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into(),
                );
            }

            // Handle updates and re-syncs

            let mut is_synced = false;
            let mut price_tick_rx = price_tick_tx.subscribe();

            let new_re_sync_timer =
                || Box::pin(time::sleep(self.config.price_history_re_sync_interval()));
            let mut re_sync_timer = new_re_sync_timer();

            let new_tick_interval_timer =
                || Box::pin(time::sleep(self.config.live_price_tick_max_interval()));
            let mut tick_interval_timer = new_tick_interval_timer();

            loop {
                tokio::select! {
                    rt_res = &mut real_time_collection_handle => {
                        rt_res.map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                        return Err(SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into());
                    }
                    tick_res = price_tick_rx.recv() => {
                        tick_interval_timer = new_tick_interval_timer();

                        let tick = tick_res.map_err(SyncProcessRecoverableError::PriceTickRecv)?;
                        if !is_synced {
                            self.status_manager.update(SyncStatus::Synced);
                            is_synced = true;
                        }

                        let _ = self.update_tx.send(tick.into());
                    }
                    _ = &mut re_sync_timer => {
                        // Ensure the OHLC candles DB remains up-to-date
                        self.run_price_history_task_live(api_rest.clone(), history_state_tx.clone(), lookback).await?;
                        re_sync_timer = new_re_sync_timer();
                    }
                    _ = &mut tick_interval_timer => {
                        // Maximum interval between Price Ticks was exceeded
                        return Err(SyncProcessRecoverableError::MaxPriceTickIntevalExceeded(
                            self.config.live_price_tick_max_interval(),
                        )
                        .into());
                    }
                }
            }
        } else {
            // REST polling only

            self.status_manager.update(SyncStatus::Synced);

            loop {
                time::sleep(self.config.price_history_re_sync_interval()).await;

                self.run_price_history_task_live(
                    api_rest.clone(),
                    history_state_tx.clone(),
                    lookback,
                )
                .await?;
            }
        }
    }

    async fn run_full(
        &self,
        api_rest: &Arc<RestClient>,
        api_ws: &Arc<WebSocketClient>,
    ) -> Result<Never> {
        self.status_manager
            .update(SyncStatusNotSynced::InProgress.into());

        // Send initial state so both TUI panes can be populated from the start

        let initial_fs_state = FundingSettlementsState::evaluate_with_reach(
            &self.db,
            self.config.funding_settlement_reach(),
            self.config.funding_settlement_flag_missing_range(),
            None,
        )
        .await
        .map_err(Self::map_funding_settlements_error)?;

        let _ = self.update_tx.send(initial_fs_state.into());

        // Backfill full historical price data

        let (history_state_tx, history_state_rx) = mpsc::channel::<PriceHistoryState>(100);

        self.spawn_history_state_update_handler(history_state_rx);

        self.run_price_history_task_backfill(
            api_rest.clone(),
            history_state_tx.clone(),
            self.config.price_history_flag_gap_range(),
        )
        .await?;

        // Backfill funding settlements

        let (funding_state_tx, funding_state_rx) = mpsc::channel::<FundingSettlementsState>(100);

        self.spawn_funding_state_update_handler(funding_state_rx);

        let _ = self
            .run_funding_settlements_task_backfill(
                api_rest.clone(),
                funding_state_tx.clone(),
                self.config.funding_settlement_flag_missing_range(),
            )
            .await?;

        let new_re_sync_timer =
            || Box::pin(time::sleep(self.config.price_history_re_sync_interval()));

        let retry_interval = self.config.funding_settlement_retry_interval();
        let new_funding_timer = |synced: bool| -> Pin<Box<time::Sleep>> {
            if synced {
                SyncFundingSettlementsTask::next_funding_timer()
            } else {
                Box::pin(time::sleep(retry_interval))
            }
        };

        if self.config.ws_enabled() {
            api_ws.reset().await;

            // Start to collect real-time data

            let (price_tick_tx, _) = broadcast::channel::<PriceTickRow>(10_000);

            let mut real_time_collection_handle =
                self.spawn_real_time_collection_task(api_ws.clone(), price_tick_tx.clone());

            if real_time_collection_handle.is_finished() {
                real_time_collection_handle
                    .await
                    .map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                return Err(
                    SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into(),
                );
            }

            // Handle updates and re-syncs

            let mut is_synced = false;
            let mut price_tick_rx = price_tick_tx.subscribe();

            let mut re_sync_timer = new_re_sync_timer();

            let new_tick_interval_timer =
                || Box::pin(time::sleep(self.config.live_price_tick_max_interval()));
            let mut tick_interval_timer = new_tick_interval_timer();

            let mut funding_timer = new_funding_timer(true);

            loop {
                tokio::select! {
                    rt_res = &mut real_time_collection_handle => {
                        rt_res.map_err(SyncProcessRecoverableError::RealTimeCollectionTaskJoin)??;

                        return Err(SyncProcessRecoverableError::UnexpectedRealTimeCollectionShutdown.into());
                    }
                    tick_res = price_tick_rx.recv() => {
                        tick_interval_timer = new_tick_interval_timer();

                        let tick = tick_res.map_err(SyncProcessRecoverableError::PriceTickRecv)?;
                        if !is_synced {
                            self.status_manager.update(SyncStatus::Synced);
                            is_synced = true;
                        }

                        let _ = self.update_tx.send(tick.into());
                    }
                    _ = &mut re_sync_timer => {
                        // Ensure the OHLC candles DB remains up-to-date
                        self.run_price_history_task_backfill(api_rest.clone(), history_state_tx.clone(), None).await?;
                        re_sync_timer = new_re_sync_timer();
                    }
                    _ = &mut funding_timer => {
                        let synced = self.run_funding_settlements_task_backfill(api_rest.clone(), funding_state_tx.clone(), None).await?;
                        funding_timer = new_funding_timer(synced);
                    }
                    _ = &mut tick_interval_timer => {
                        // Maximum interval between Price Ticks was exceeded
                        return Err(SyncProcessRecoverableError::MaxPriceTickIntevalExceeded(
                            self.config.live_price_tick_max_interval(),
                        )
                        .into());
                    }
                }
            }
        } else {
            // REST polling only

            self.status_manager.update(SyncStatus::Synced);

            let mut re_sync_timer = new_re_sync_timer();
            let mut funding_timer = new_funding_timer(true);

            loop {
                tokio::select! {
                    _ = &mut re_sync_timer => {
                        self.run_price_history_task_backfill(api_rest.clone(), history_state_tx.clone(), None).await?;
                        re_sync_timer = new_re_sync_timer();
                    }
                    _ = &mut funding_timer => {
                        let synced = self.run_funding_settlements_task_backfill(api_rest.clone(), funding_state_tx.clone(), None).await?;
                        funding_timer = new_funding_timer(synced);
                    }
                }
            }
        }
    }

    async fn run_price_history_task_backfill(
        &self,
        api_rest: Arc<RestClient>,
        history_state_tx: PriceHistoryStateTransmitter,
        flag_gaps_range: Option<Duration>,
    ) -> Result<()> {
        SyncPriceHistoryTask::new(&self.config, self.db.clone(), api_rest, history_state_tx)
            .backfill(flag_gaps_range)
            .await
            .map_err(Self::map_price_history_error)
    }

    async fn run_price_history_task_live(
        &self,
        api_rest: Arc<RestClient>,
        history_state_tx: PriceHistoryStateTransmitter,
        lookback: Duration,
    ) -> Result<()> {
        SyncPriceHistoryTask::new(&self.config, self.db.clone(), api_rest, history_state_tx)
            .live(lookback)
            .await
            .map_err(Self::map_price_history_error)
    }

    fn map_price_history_error(e: SyncPriceHistoryError) -> SyncProcessError {
        match e {
            SyncPriceHistoryError::Recoverable(e) => {
                SyncProcessRecoverableError::SyncPriceHistory(e).into()
            }
            SyncPriceHistoryError::Fatal(e) => SyncProcessFatalError::SyncPriceHistory(e).into(),
        }
    }

    /// Clean up is not needed since the task is terminated when
    /// `history_state_tx` is dropped.
    pub fn spawn_history_state_update_handler(
        &self,
        mut history_state_rx: mpsc::Receiver<PriceHistoryState>,
    ) {
        let update_tx = self.update_tx.clone();
        tokio::spawn(async move {
            while let Some(new_history_state) = history_state_rx.recv().await {
                // Ignore no-receivers errors
                let _ = update_tx.send(new_history_state.into());
            }
        });
    }

    async fn run_funding_settlements_task_backfill(
        &self,
        api_rest: Arc<RestClient>,
        funding_state_tx: FundingSettlementsStateTransmitter,
        flag_missing_range: Option<Duration>,
    ) -> Result<bool> {
        SyncFundingSettlementsTask::new(&self.config, self.db.clone(), api_rest, funding_state_tx)
            .backfill(flag_missing_range)
            .await
            .map_err(Self::map_funding_settlements_error)
    }

    fn map_funding_settlements_error(e: SyncFundingSettlementsError) -> SyncProcessError {
        match e {
            SyncFundingSettlementsError::Recoverable(e) => {
                SyncProcessRecoverableError::SyncFundingSettlements(e).into()
            }
            SyncFundingSettlementsError::Fatal(e) => {
                SyncProcessFatalError::SyncFundingSettlements(e).into()
            }
        }
    }

    fn spawn_funding_state_update_handler(
        &self,
        mut funding_state_rx: mpsc::Receiver<FundingSettlementsState>,
    ) {
        let update_tx = self.update_tx.clone();
        tokio::spawn(async move {
            while let Some(new_state) = funding_state_rx.recv().await {
                let _ = update_tx.send(new_state.into());
            }
        });
    }

    fn spawn_real_time_collection_task(
        &self,
        api_ws: Arc<WebSocketClient>,
        price_tick_tx: broadcast::Sender<PriceTickRow>,
    ) -> AbortOnDropHandle<Result<()>> {
        let task = RealTimeCollectionTask::new(
            self.db.clone(),
            api_ws,
            self.shutdown_tx.clone(),
            price_tick_tx,
        );

        tokio::spawn(
            task.run()
                .map_err(|e| SyncProcessRecoverableError::RealTimeCollection(e).into()),
        )
        .into()
    }
}