Repository navigation
Expand file tree
/
Copy pathstudies_data.rs
More file actions
1699 lines (1661 loc) · 67 KB
/
Copy pathstudies_data.rs
File metadata and controls
1699 lines (1661 loc) · 67 KB
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Host-fed histories and subscriptions used by studies.
use super::Chart;
use crate::data::inbox::Inbox;
use crate::data::merge::{Origin, merge};
use crate::data::{
Datafeed, FeedError, HistoryPage, HistoryRequest, MetricPage, MetricRequest,
MetricSubscription, Subscription, SubscriptionId,
};
use crate::model::{Bar, BarClock, Instrument, Timeframe};
use crate::studies::{StudyData, StudyDataRequest};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
#[derive(Default)]
pub(super) struct StudyDataCache {
series: Vec<Series>,
}
struct Series {
request: StudyDataRequest,
bars: Vec<Bar>,
instrument: Option<Instrument>,
clock: BarClock,
error: Option<FeedError>,
stream: Option<Stream>,
from_ticks: BTreeMap<chrono::DateTime<chrono::Utc>, Origin>,
}
struct Stream {
feed: Arc<dyn Datafeed>,
inbox: Arc<Inbox>,
subscription: Option<SubscriptionId>,
pending: bool,
next_key: u64,
/// Kept intact until success, including while newer live data arrives.
history: Option<HistoryRequest>,
/// The chart's currency or unit conversion, which `clear_feed` replaces the stream on.
conversion: Option<String>,
/// Where older bars continue after an empty page.
cursor: Option<chrono::DateTime<chrono::Utc>>,
retry_at: Option<f64>,
failures: u32,
end: bool,
wake: Arc<Mutex<Option<egui::ViewportId>>>,
}
impl Stream {
fn request(&mut self, source: &StudyDataRequest) {
self.next_key += 1;
self.pending = true;
if let Some(history) = &self.history {
if let Some(metric) = &source.metric {
self.feed.metric_history(
MetricRequest {
symbol: history.symbol.clone(),
metric: metric.clone(),
before: history.before,
count: history.count,
},
self.inbox.reply(self.next_key),
);
} else {
self.feed
.history(history.clone(), self.inbox.reply(self.next_key));
}
} else {
super::feed::resolve(
&*self.feed,
&source.symbol,
self.conversion.as_deref(),
self.inbox.reply(self.next_key),
);
}
}
fn failed(&mut self, error: &FeedError, now: f64) {
if error.is_recoverable() {
let delay = super::feed::retry_delay(self.failures, error);
self.retry_at = Some(now + delay.as_secs_f64());
self.failures = self.failures.saturating_add(1);
}
}
}
impl Drop for Stream {
fn drop(&mut self) {
*self.wake.lock().unwrap_or_else(|error| error.into_inner()) = None;
if let Some(id) = self.subscription {
self.inbox.unsubscribe(id);
self.feed.unsubscribe(id);
}
}
}
fn resolved(
request: &StudyDataRequest,
symbol: &str,
timeframe: Option<Timeframe>,
) -> StudyDataRequest {
StudyDataRequest {
metric: request.metric.clone(),
symbol: if request.symbol.is_empty() {
symbol.to_owned()
} else {
request.symbol.clone()
},
timeframe: Some(request.timeframe.or(timeframe).unwrap_or_default()),
}
}
fn clock(request: &StudyDataRequest, instrument: Option<&Instrument>, extended: bool) -> BarClock {
if request.metric.is_some() {
return BarClock::new(Timeframe::Ticks(std::num::NonZeroU64::MIN));
}
let timeframe = request.timeframe.unwrap_or_default();
let mut clock = BarClock::new(timeframe);
if let Some(instrument) = instrument {
let zone = instrument
.time_zone
.clone()
.unwrap_or_else(crate::model::TimezoneId::utc);
if timeframe.duration_ms() < Timeframe::Day1.duration_ms() {
clock = clock.with_timezone(zone.clone());
}
if let Some(session) = &instrument.session {
clock = clock.with_session(zone, session.clone(), extended);
}
}
clock
}
impl StudyDataCache {
pub(super) fn snapshot(&self) -> Self {
Self {
series: self
.series
.iter()
.map(|series| Series {
request: series.request.clone(),
bars: series.bars.clone(),
instrument: series.instrument.clone(),
clock: series.clock.clone(),
error: series.error.clone(),
stream: None,
from_ticks: series.from_ticks.clone(),
})
.collect(),
}
}
pub(super) fn clear_feed(&mut self) {
self.series.retain(|series| series.stream.is_none());
}
pub(super) fn pause(&mut self) {
for series in &mut self.series {
if let Some(stream) = &mut series.stream {
stream.pending = false;
stream.retry_at = None;
stream.history = None;
*stream
.wake
.lock()
.unwrap_or_else(|error| error.into_inner()) = None;
if let Some(id) = stream.subscription.take() {
stream.inbox.unsubscribe(id);
stream.feed.unsubscribe(id);
}
}
}
}
pub(super) fn data(
&self,
requests: Vec<StudyDataRequest>,
symbol: &str,
timeframe: Option<Timeframe>,
replay: Option<chrono::DateTime<chrono::Utc>>,
) -> Vec<StudyData<'_>> {
requests
.into_iter()
.filter_map(|request| {
let key = resolved(&request, symbol, timeframe);
let series = self.series.iter().find(|series| series.request == key)?;
Some(StudyData {
request,
bars: match replay {
Some(time) => super::replay::completed(&series.bars, &series.clock, time),
None => &series.bars,
},
clock: series.clock.clone(),
instrument: series.instrument.as_ref(),
timeframe: key.timeframe.unwrap(),
})
})
.collect()
}
}
impl Chart {
/// Histories required by feed-backed series, study inputs and profile drawings, with chart
/// defaults resolved. Hosts without a connected feed supply these through [`Self::set_study_data`]. A connected
/// feed receives resolve, history and subscription calls automatically on the next frame.
pub fn study_data_requests(&self) -> Vec<StudyDataRequest> {
let mut requests = self.fed_requests();
for (_, study) in self.indicators() {
for request in study.data_requests() {
let request = resolved(&request, self.symbol(), self.timeframe());
if !requests.contains(&request) {
requests.push(request);
}
}
}
#[cfg(feature = "drawings")]
for (request, _) in self.profile_histories(&self.drawings) {
let request = resolved(&request, self.symbol(), self.timeframe());
if !requests.contains(&request) {
requests.push(request);
}
}
requests
}
/// Replace a study history with host-owned historical or streaming bars. Bars are sorted,
/// deduplicated and validated like chart data. This takes ownership of this request from
/// the connected feed; the host supplies further replacements. Metadata sets its calendar.
pub fn set_study_data(
&mut self,
request: StudyDataRequest,
bars: Vec<Bar>,
instrument: Option<Instrument>,
) {
let request = resolved(&request, self.symbol(), self.timeframe());
let clock = clock(&request, instrument.as_ref(), self.extended_hours());
let (bars, _) = super::series::clean(bars, &clock);
self.study_data
.series
.retain(|series| series.request != request);
self.study_data.series.push(Series {
request,
bars,
instrument,
clock,
error: None,
stream: None,
from_ticks: BTreeMap::new(),
});
self.invalidate_study_data();
}
/// The last error for a requested study history. Recoverable resolve and page failures retry
/// with exponential backoff, respecting rate limits; success clears the error. An unavailable
/// source leaves gaps.
pub fn study_data_error(&self, request: &StudyDataRequest) -> Option<&FeedError> {
let request = resolved(request, self.symbol(), self.timeframe());
self.study_data
.series
.iter()
.find(|series| series.request == request)?
.error
.as_ref()
}
pub(super) fn invalidate_study_data(&mut self) {
for (at, study) in self.studies.indicators().iter().enumerate() {
if !study.data_requests().is_empty() {
self.pending_from[at] = Some(0);
self.next_refresh[at] = f64::NEG_INFINITY;
}
}
self.element_studies.dirty = true;
self.fill_fed_series();
}
/// [`Self::study_data_requests`], each with how far back the connected feed loads it: to
/// the chart's first bar, or to a later start that every study reading it states through
/// `Indicator::data_start`. `None` while the chart has no bars. Allocates only the requests,
/// since it runs every frame.
fn study_data_reaches(&self) -> Vec<(StudyDataRequest, Option<chrono::DateTime<chrono::Utc>>)> {
// Price-based chart types run their studies on elements; the source studies asked
// here are not given the view, so their histories load in full.
let full = self.chart_type.is_time_independent();
let mut reaches: Vec<(StudyDataRequest, Option<_>)> = self
.fed_requests()
.into_iter()
.map(|request| (request, None))
.collect();
for (_, study) in self.indicators() {
for declared in study.data_requests() {
let start = study.data_start(&declared).filter(|_| !full);
let request = resolved(&declared, self.symbol(), self.timeframe());
match reaches.iter_mut().find(|(known, _)| *known == request) {
// `None` sorts first: a study without a start loads it to the first bar.
Some((_, reach)) => *reach = (*reach).min(start),
None => reaches.push((request, start)),
}
}
}
#[cfg(feature = "drawings")]
for (declared, start) in self.profile_histories(&self.drawings) {
let request = resolved(&declared, self.symbol(), self.timeframe());
match reaches.iter_mut().find(|(known, _)| *known == request) {
Some((_, reach)) => *reach = (*reach).min(Some(start)),
None => reaches.push((request, Some(start))),
}
}
let first = self.state.data().bars.first().map(|bar| bar.time);
for (_, reach) in &mut reaches {
*reach = first.map(|first| reach.map_or(first, |start| start.max(first)));
}
reaches
}
pub(super) fn pump_study_data(&mut self, ctx: &egui::Context, feed: Option<Arc<dyn Datafeed>>) {
let requests = self.study_data_reaches();
let previous = self.study_data.series.len();
self.study_data.series.retain(|series| {
requests
.iter()
.any(|(request, _)| *request == series.request)
&& series.stream.as_ref().is_none_or(|stream| {
feed.as_ref()
.is_some_and(|feed| Arc::ptr_eq(feed, &stream.feed))
})
});
let removed = self.study_data.series.len() != previous;
if let Some(feed) = &feed {
for (request, _) in &requests {
if request.symbol.is_empty() {
continue;
}
if self
.study_data
.series
.iter()
.any(|series| &series.request == request)
{
continue;
}
let inbox = Arc::new(Inbox::default());
let wake = Arc::new(Mutex::new(Some(ctx.viewport_id())));
let repaint = Arc::clone(&wake);
let ctx = ctx.clone();
inbox.set_waker(move || {
let viewport = *repaint.lock().unwrap_or_else(|error| error.into_inner());
if let Some(viewport) = viewport {
ctx.request_repaint_of(viewport);
}
});
super::feed::resolve(
&**feed,
&request.symbol,
self.conversion.as_deref(),
inbox.reply(0),
);
self.study_data.series.push(Series {
request: request.clone(),
bars: Vec::new(),
instrument: None,
clock: clock(request, None, self.extended_hours()),
error: None,
from_ticks: BTreeMap::new(),
stream: Some(Stream {
feed: Arc::clone(feed),
inbox,
subscription: None,
pending: true,
next_key: 0,
history: None,
conversion: self.conversion.clone(),
cursor: None,
retry_at: None,
failures: 0,
end: false,
wake,
}),
});
}
}
let extended = self.extended_hours();
let adjusted = self.dividend_adjusted();
let now = ctx.input(|input| input.time);
let count = self.state.data().bars.len().max(300);
let mut changed = removed || self.study_data.series.len() != previous;
for series in &mut self.study_data.series {
let Some(stream) = &mut series.stream else {
let clock = clock(&series.request, series.instrument.as_ref(), extended);
if clock != series.clock {
series.clock = clock;
changed = true;
}
continue;
};
*stream
.wake
.lock()
.unwrap_or_else(|error| error.into_inner()) = Some(ctx.viewport_id());
let drained = stream.inbox.drain();
for (key, answer) in drained.answers {
if !stream.pending || key != stream.next_key {
continue;
}
stream.pending = false;
if stream.history.is_none() {
let result = answer
.downcast::<Result<Instrument, FeedError>>()
.map(|result| *result)
.unwrap_or(Err(FeedError::NotSupported));
match result {
Ok(instrument) => {
let tf = series.request.timeframe.unwrap();
if series.request.metric.is_none()
&& instrument
.supported_timeframes
.as_ref()
.is_some_and(|intervals| !intervals.contains(&tf))
{
series.error = Some(FeedError::NotSupported);
continue;
}
series.clock = clock(&series.request, Some(&instrument), extended);
series.instrument = Some(instrument);
series.error = None;
stream.failures = 0;
}
Err(error) => {
stream.failed(&error, now);
series.error = Some(error);
}
}
} else {
let result = if series.request.metric.is_some() {
answer
.downcast::<Result<MetricPage, FeedError>>()
.map(|result| {
result.map(|page| {
HistoryPage::new(
page.points.into_iter().map(Bar::from).collect(),
page.end_of_history,
)
})
})
.unwrap_or(Err(FeedError::NotSupported))
} else {
answer
.downcast::<Result<HistoryPage, FeedError>>()
.map(|result| *result)
.unwrap_or(Err(FeedError::NotSupported))
};
match result {
Ok(mut page) => {
let previous = stream.history.take().and_then(|request| request.before);
page.bars.retain(|bar| {
previous
.is_none_or(|before| series.clock.bar_open(bar.time) < before)
});
series.error = None;
stream.failures = 0;
let empty = page.bars.is_empty();
let continuation = page.continue_before.filter(|_| empty);
stream.cursor = continuation;
stream.end =
page.end_of_history || (empty && page.continue_before.is_none());
if continuation.is_some_and(|at| previous.is_some_and(|b| at >= b)) {
stream.cursor = None;
stream.end = true;
series.error = Some(FeedError::InvalidData(
"history continuation does not lie before the request".into(),
));
}
let incoming = page
.bars
.into_iter()
.map(|bar| (bar, Origin::History))
.collect();
merge(
&mut series.bars,
&mut series.from_ticks,
&series.clock,
incoming,
);
if previous.is_some()
&& continuation.is_none()
&& series.bars.first().map(|bar| bar.time) >= previous
{
stream.end = true;
}
changed = true;
}
Err(error) => {
stream.failed(&error, now);
series.error = Some(error);
}
}
}
}
for (_, updates) in drained.updates {
if updates.reset {
series.bars.clear();
series.from_ticks.clear();
series.error = None;
stream.pending = false;
stream.history = None;
stream.retry_at = None;
stream.failures = 0;
stream.end = false;
changed = true;
}
if !updates.bars.is_empty() {
merge(
&mut series.bars,
&mut series.from_ticks,
&series.clock,
updates.bars.into_values().collect(),
);
changed = true;
}
if updates.error.is_some() {
series.error = updates.error;
}
}
if stream.subscription.is_none()
&& series.instrument.is_some()
&& series.error.is_none()
{
let tf = series.request.timeframe.unwrap();
let sink = stream.inbox.subscribe(
series.request.symbol.clone(),
series.clock.clone(),
super::feed::TRADE_CAPACITY,
series.instrument.as_ref().and_then(|i| i.tick_size),
);
stream.subscription = Some(sink.id);
if let Some(metric) = &series.request.metric {
stream.feed.subscribe_metric(MetricSubscription {
id: sink.id,
symbol: series.request.symbol.clone(),
metric: metric.clone(),
sink,
});
} else {
stream.feed.subscribe(Subscription {
id: sink.id,
symbol: series.request.symbol.clone(),
timeframe: tf,
clock: series.clock.clone(),
extended_hours: extended,
conversion: stream.conversion.clone(),
sink,
});
}
}
if let Some(deadline) = stream.retry_at {
if now >= deadline {
stream.retry_at = None;
stream.request(&series.request);
} else {
ctx.request_repaint_after(
std::time::Duration::try_from_secs_f64(deadline - now)
.unwrap_or(std::time::Duration::MAX),
);
}
}
let reach = requests
.iter()
.find(|(request, _)| *request == series.request)
.and_then(|(_, reach)| *reach);
if !stream.pending
&& stream.retry_at.is_none()
&& !stream.end
&& series.error.is_none()
&& series.instrument.is_some()
&& (series.bars.is_empty()
|| reach
.zip(series.bars.first())
.is_some_and(|(reach, bar)| reach < bar.time))
{
stream.history = Some(HistoryRequest {
symbol: series.request.symbol.clone(),
timeframe: series.request.timeframe.unwrap(),
clock: series.clock.clone(),
before: series
.bars
.first()
.map(|bar| bar.time)
.into_iter()
.chain(stream.cursor)
.min(),
since: None,
count,
extended_hours: extended,
adjusted,
conversion: stream.conversion.clone(),
});
stream.request(&series.request);
}
}
if changed {
self.invalidate_study_data();
}
}
}
#[cfg(all(test, feature = "studies"))]
mod tests {
use super::*;
use crate::data::{Reply, Sink};
use crate::studies::{InputValue, SMA};
use crate::widget::{ChartBuilder, test_frames::shapes};
use chrono::{DateTime, Duration};
#[derive(Default)]
struct Feed {
sinks: Mutex<Vec<(String, Sink)>>,
correction: Mutex<f64>,
metrics: Mutex<Vec<MetricSubscription>>,
}
impl Datafeed for Feed {
fn history(&self, request: HistoryRequest, reply: Reply<HistoryPage>) {
let (prices, minutes) = match request.symbol.as_str() {
"REMOTE" => (vec![10.0, 14.0, 20.0], 60),
"OTHER" => (
vec![100.0, 200.0, 300.0 + *self.correction.lock().unwrap()],
60,
),
_ => (vec![1.0; 5], 30),
};
reply.send(Ok(HistoryPage::new(bars(&prices, minutes), true)));
}
fn metric_history(&self, _: MetricRequest, reply: Reply<MetricPage>) {
reply.send(Ok(MetricPage {
points: [(15, 10.0), (75, 20.0)]
.into_iter()
.map(|(minute, value)| crate::data::MetricPoint {
time: DateTime::UNIX_EPOCH + Duration::minutes(minute),
value,
})
.collect(),
end_of_history: true,
}));
}
fn subscribe_metric(&self, subscription: MetricSubscription) {
self.metrics.lock().unwrap().push(subscription);
}
fn subscribe(&self, subscription: Subscription) {
self.sinks
.lock()
.unwrap()
.push((subscription.symbol, subscription.sink));
}
}
fn bars(prices: &[f64], minutes: i64) -> Vec<Bar> {
prices
.iter()
.enumerate()
.map(|(at, &price)| {
Bar::new(
DateTime::UNIX_EPOCH + Duration::minutes(at as i64 * minutes),
price,
price,
price,
price,
1.0,
)
})
.collect()
}
/// Counts the heap allocations of each thread, so a test can bound its own.
struct Counting;
thread_local! {
static ALLOCATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
// SAFETY: every call forwards to `System` with the caller's arguments; the counter only observes.
unsafe impl std::alloc::GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
let _ = ALLOCATIONS.try_with(|count| count.set(count.get() + 1));
// SAFETY: forwarded unchanged.
unsafe { std::alloc::System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
// SAFETY: forwarded unchanged.
unsafe { std::alloc::System.dealloc(ptr, layout) }
}
unsafe fn realloc(
&self,
ptr: *mut u8,
layout: std::alloc::Layout,
new_size: usize,
) -> *mut u8 {
let _ = ALLOCATIONS.try_with(|count| count.set(count.get() + 1));
// SAFETY: forwarded unchanged.
unsafe { std::alloc::System.realloc(ptr, layout, new_size) }
}
}
/// The heap allocations `run` makes on this thread, not counting the drop of its result.
fn allocations<T>(run: impl FnOnce() -> T) -> (usize, T) {
let before = ALLOCATIONS.with(std::cell::Cell::get);
let result = run();
(ALLOCATIONS.with(std::cell::Cell::get) - before, result)
}
#[derive(Default)]
struct RetryFeed {
resolves: Mutex<Vec<crate::data::Reply<Instrument>>>,
histories: Mutex<Vec<(HistoryRequest, crate::data::Reply<HistoryPage>)>>,
metrics: Mutex<Vec<(MetricRequest, crate::data::Reply<MetricPage>)>>,
sinks: Mutex<Vec<Sink>>,
}
impl Datafeed for RetryFeed {
fn resolve(&self, _: &str, reply: Reply<Instrument>) {
self.resolves.lock().unwrap().push(reply);
}
fn history(&self, request: HistoryRequest, reply: Reply<HistoryPage>) {
self.histories.lock().unwrap().push((request, reply));
}
fn metric_history(&self, request: MetricRequest, reply: Reply<MetricPage>) {
self.metrics.lock().unwrap().push((request, reply));
}
fn subscribe(&self, subscription: Subscription) {
self.sinks.lock().unwrap().push(subscription.sink);
}
fn subscribe_metric(&self, subscription: MetricSubscription) {
self.sinks.lock().unwrap().push(subscription.sink);
}
}
impl RetryFeed {
fn pending(&self, metric: bool) -> usize {
if metric {
self.metrics.lock().unwrap().len()
} else {
self.histories.lock().unwrap().len()
}
}
fn answer(
&self,
metric: bool,
result: Result<HistoryPage, FeedError>,
) -> (Option<DateTime<chrono::Utc>>, usize) {
if metric {
let (request, reply) = self.metrics.lock().unwrap().remove(0);
reply.send(result.map(|page| {
MetricPage {
points: page
.bars
.into_iter()
.map(|bar| crate::data::MetricPoint {
time: bar.time,
value: bar.close,
})
.collect(),
end_of_history: page.end_of_history,
}
}));
(request.before, request.count)
} else {
let (request, reply) = self.histories.lock().unwrap().remove(0);
reply.send(result);
(request.before, request.count)
}
}
}
#[test]
fn study_sources_retry_original_requests_and_ignore_superseded_replies() {
for metric in [false, true] {
for (error, delay) in [
(FeedError::Network("offline".into()), 1.0),
(
FeedError::RateLimited {
retry_after: Some(std::time::Duration::from_secs(7)),
},
7.0,
),
(FeedError::Unanswered, 1.0),
(FeedError::NotSupported, 0.0),
] {
let feed = Arc::new(RetryFeed::default());
let mut chart = Chart::new(crate::model::BarData::from_bars(bars(&[1.0; 5], 30)));
chart.set_symbol("REMOTE");
if metric {
chart.add_indicator(Box::new(crate::studies::MetricStudy::new(
crate::data::MetricSeries {
id: "oi".into(),
name: "Open interest".into(),
unit: "contracts".into(),
format: crate::scales::StudyFormat::Volume,
},
)));
} else {
let id = chart.add_indicator(Box::new(SMA::new(1)));
chart
.indicator_mut(id)
.unwrap()
.set_input("calculation_symbol", InputValue::Symbol("REMOTE".into()))
.unwrap();
}
let ctx = egui::Context::default();
let pump = |chart: &mut Chart, time| {
ctx.run_ui(
egui::RawInput {
time: Some(time),
..Default::default()
},
|_| {},
)
.drop_without_applying_deltas();
chart.pump_study_data(&ctx, Some(feed.clone()));
};
pump(&mut chart, 0.0);
feed.resolves
.lock()
.unwrap()
.pop()
.unwrap()
.send(Err(error.clone()));
pump(&mut chart, 0.25);
let request = chart.study_data_requests().pop().unwrap();
assert_eq!(chart.study_data_error(&request), Some(&error));
pump(&mut chart, 0.25 + delay - 0.01);
assert!(feed.resolves.lock().unwrap().is_empty());
pump(&mut chart, 0.25 + delay);
if !error.is_recoverable() {
pump(&mut chart, 120.0);
assert!(feed.resolves.lock().unwrap().is_empty());
continue;
}
assert_eq!(feed.resolves.lock().unwrap().len(), 1, "{error:?}");
feed.resolves
.lock()
.unwrap()
.pop()
.unwrap()
.send(Ok(Instrument::new("REMOTE")));
let now = 0.5 + delay;
pump(&mut chart, now);
assert_eq!(chart.study_data_error(&request), None);
let mut newest = bars(&[20.0], 60);
newest[0].time += Duration::hours(2);
assert_eq!(
feed.answer(metric, Ok(HistoryPage::new(newest, false))).0,
None
);
pump(&mut chart, now + 0.25);
let failed = feed.answer(metric, Err(error.clone()));
pump(&mut chart, now + 0.5);
feed.sinks.lock().unwrap()[0].push_bar(Bar::new(
DateTime::UNIX_EPOCH + Duration::hours(1),
55.0,
55.0,
55.0,
55.0,
1.0,
));
pump(&mut chart, now + 0.5 + delay - 0.01);
assert_eq!(feed.pending(metric), 0);
pump(&mut chart, now + 0.5 + delay);
assert_eq!(feed.pending(metric), 1);
let retried = feed.answer(
metric,
Ok(HistoryPage::new(bars(&[12.0, 55.0, 99.0, 100.0], 60), true)),
);
assert_eq!(
retried, failed,
"retry must keep its boundary and count after a live prepend"
);
assert_eq!(retried.0, Some(DateTime::UNIX_EPOCH + Duration::hours(2)));
pump(&mut chart, now + 0.75 + delay);
assert_eq!(chart.study_data_error(&request), None);
assert_eq!(
chart.study_data.series[0]
.bars
.iter()
.map(|bar| bar.close)
.collect::<Vec<_>>(),
[12.0, 55.0, 20.0]
);
// A page from an earlier seek must not change the current request.
for time in [now + 10.0, now + 11.0] {
feed.sinks.lock().unwrap()[0].reset_replay(DateTime::UNIX_EPOCH);
pump(&mut chart, time);
}
feed.answer(metric, Err(FeedError::Network("old page".into())));
pump(&mut chart, now + 12.0);
assert_eq!(chart.study_data_error(&request), None);
feed.answer(metric, Ok(HistoryPage::new(bars(&[99.0], 60), true)));
pump(&mut chart, now + 13.0);
assert_eq!(chart.study_data_error(&request), None);
assert_eq!(chart.study_data.series[0].bars[0].close, 99.0);
assert_eq!(feed.pending(metric), 0);
}
}
}
#[test]
fn study_retries_back_off_and_cancel_with_their_source() {
for action in ["pause", "host data", "remove", "replace"] {
let feed = Arc::new(RetryFeed::default());
let mut chart = Chart::new(crate::model::BarData::new());
let id = chart.add_indicator(Box::new(SMA::new(1)));
chart
.indicator_mut(id)
.unwrap()
.set_input("calculation_symbol", InputValue::Symbol("REMOTE".into()))
.unwrap();
let ctx = egui::Context::default();
let pump = |chart: &mut Chart, time| {
ctx.run_ui(
egui::RawInput {
time: Some(time),
..Default::default()
},
|_| {},
)
.drop_without_applying_deltas();
chart.pump_study_data(&ctx, Some(feed.clone()));
};
pump(&mut chart, 0.0);
feed.resolves
.lock()
.unwrap()
.pop()
.unwrap()
.send(Err(FeedError::Network("offline".into())));
pump(&mut chart, 0.1);
pump(&mut chart, 1.1);
feed.resolves
.lock()
.unwrap()
.pop()
.unwrap()
.send(Err(FeedError::Network("still offline".into())));
pump(&mut chart, 1.2);
pump(&mut chart, 2.2);
assert!(
feed.resolves.lock().unwrap().is_empty(),
"second failure waits two seconds"
);
match action {
"pause" => {
chart.set_feed_paused(true);
}
"host data" => {
let request = chart.study_data_requests().pop().unwrap();
chart.set_study_data(request, bars(&[99.0], 60), None);
}
"remove" => {
chart.remove_series(id);
}
"replace" => {
chart
.indicator_mut(id)
.unwrap()
.set_input("calculation_symbol", InputValue::Symbol("OTHER".into()))
.unwrap();
}
_ => unreachable!(),
}
pump(&mut chart, 60.0);
assert_eq!(
feed.resolves.lock().unwrap().len(),
usize::from(action == "replace"),
"{action}"
);
}
}
#[test]
fn replay_reset_discards_future_study_bars_and_tick_origins() {
for replacement in [false, true] {
let feed = Arc::new(Feed::default());
let mut chart = ChartBuilder::new()
.with_feed(feed.clone())
.with_symbol("MAIN")
.with_timeframe(Timeframe::Hour1)
.build();
let id = chart.add_indicator(Box::new(SMA::new(1)));
chart
.indicator_mut(id)
.unwrap()
.set_input("calculation_symbol", InputValue::Symbol("REMOTE".into()))
.unwrap();
let ctx = egui::Context::default();
for frame in 0..8 {
shapes(&ctx, &mut chart, frame as f64, Vec::new());
}
let sink = feed
.sinks
.lock()
.unwrap()
.iter()
.find(|(symbol, _)| symbol == "REMOTE")
.unwrap()