-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
IndicatorData.mqh
968 lines (844 loc) · 29.3 KB
/
IndicatorData.mqh
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
//+------------------------------------------------------------------+
//| EA31337 framework |
//| Copyright 2016-2023, EA31337 Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
/*
* This file is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Includes.
#include "IndicatorBase.h"
#include "IndicatorData.enum.h"
#include "IndicatorData.struct.h"
#include "IndicatorData.struct.serialize.h"
#include "IndicatorData.struct.signal.h"
#include "Storage/ValueStorage.h"
#include "Storage/ValueStorage.indicator.h"
#include "Storage/ValueStorage.native.h"
/**
* Implements class to store indicator data.
*/
class IndicatorData : public IndicatorBase {
protected:
// Class variables.
ARRAY(ValueStorage<double>*, value_storages);
ARRAY(WeakRef<IndicatorData>, listeners); // List of indicators that listens for events from this one.
BufferStruct<IndicatorDataEntry> idata;
DictStruct<int, Ref<IndicatorData>> indicators; // Indicators list keyed by id.
IndicatorCalculateCache<double> cache;
IndicatorDataParams idparams; // Indicator data params.
Ref<IndicatorData> indi_src; // Indicator used as data source.
protected:
/* Protected methods */
bool Init() {
ArrayResize(value_storages, idparams.Get<unsigned int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES)));
if (indi_src.IsSet()) {
// SetDataSource(_indi_src, _indi_mode);
idparams.Set<ENUM_IDATA_SOURCE_TYPE>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IDSTYPE), IDATA_INDICATOR);
}
switch (idparams.Get<ENUM_IDATA_SOURCE_TYPE>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IDSTYPE))) {
case IDATA_BUILTIN:
break;
case IDATA_ICUSTOM:
break;
case IDATA_INDICATOR:
if (indi_src.IsSet() == NULL) {
// Indi_Price* _indi_price = Indi_Price::GetCached(GetSymbol(), GetTf(), iparams.GetShift());
// SetDataSource(_indi_price, true, PRICE_OPEN);
}
break;
}
return true;
}
public:
/* Special methods */
/**
* Class constructor.
*/
IndicatorData(const IndicatorDataParams& _idparams, IndicatorData* _indi_src = NULL, int _indi_mode = 0)
: idparams(_idparams), indi_src(_indi_src) {}
IndicatorData(const IndicatorDataParams& _idparams, ENUM_TIMEFRAMES _tf, string _symbol = NULL)
: idparams(_idparams), IndicatorBase(_tf, _symbol) {}
/**
* Class deconstructor.
*/
virtual ~IndicatorData() {
for (int i = 0; i < ArraySize(value_storages); ++i) {
if (value_storages[i] != NULL) {
delete value_storages[i];
}
}
}
/* Operator overloading methods */
/**
* Access indicator entry data using [] operator via shift.
*/
IndicatorDataEntry operator[](int _index) {
if (!bool(flags | INDI_FLAG_INDEXABLE_BY_SHIFT)) {
Print(GetFullName(), " is not indexable by shift!");
DebugBreak();
IndicatorDataEntry _default;
return _default;
}
return GetEntry(_index);
}
/**
* Access indicator entry data using [] operator via datetime.
*/
IndicatorDataEntry operator[](datetime _dt) {
if (!bool(flags | INDI_FLAG_INDEXABLE_BY_TIMESTAMP)) {
Print(GetFullName(), " is not indexable by timestamp!");
DebugBreak();
IndicatorDataEntry _default;
return _default;
}
return GetEntry(_dt);
}
IndicatorDataEntry operator[](ENUM_INDICATOR_INDEX _index) { return GetEntry((int)_index); }
/* Getters */
/**
* Gets a value from IndicatorDataParams struct.
*/
template <typename T>
T Get(STRUCT_ENUM_IDATA_PARAM _param) {
return idparams.Get<T>(_param);
}
/**
* Gets an indicator's state property value.
*/
template <typename T>
T Get(STRUCT_ENUM_INDICATOR_STATE_PROP _prop) {
return istate.Get<T>(_prop);
}
/**
* Gets an indicator property flag.
*/
bool GetFlag(INDICATOR_ENTRY_FLAGS _prop, int _shift = 0) {
IndicatorDataEntry _entry = GetEntry(_shift);
return _entry.CheckFlag(_prop);
}
/**
* Returns price corresponding to indicator value for a given shift and mode.
*
* Can be useful for calculating trailing stops based on the indicator.
*
* @return
* Returns price value of the corresponding indicator values.
*/
template <typename T>
float GetValuePrice(int _shift = 0, int _mode = 0, ENUM_APPLIED_PRICE _ap = PRICE_TYPICAL) {
float _price = 0;
ENUM_IDATA_VALUE_RANGE _idvrange =
Get<ENUM_IDATA_VALUE_RANGE>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IDVRANGE));
if (_idvrange != IDATA_RANGE_PRICE) {
_price = (float)GetPrice(_ap, _shift);
} else if (_idvrange == IDATA_RANGE_PRICE) {
// When indicator values are the actual prices.
T _values[4];
if (!CopyValues(_values, 4, _shift, _mode)) {
// When values aren't valid, return 0.
return _price;
}
datetime _bar_time = GetBarTime(_shift);
float _value = 0;
BarOHLC _ohlc(_values, _bar_time);
_price = _ohlc.GetAppliedPrice(_ap);
}
return _price;
}
/* Setters */
/**
* Sets a value in IndicatorDataParams struct.
*/
template <typename T>
void Set(STRUCT_ENUM_IDATA_PARAM _param, T _value) {
idparams.Set<T>(_param, _value);
}
/* State methods */
/**
* Checks for crossover.
*
* @return
* Returns true when values are crossing over, otherwise false.
*/
bool IsCrossover(int _shift1 = 0, int _shift2 = 1, int _mode1 = 0, int _mode2 = 0) {
double _curr_value1 = GetEntry(_shift1)[_mode1];
double _prev_value1 = GetEntry(_shift2)[_mode1];
double _curr_value2 = GetEntry(_shift1)[_mode2];
double _prev_value2 = GetEntry(_shift2)[_mode2];
return ((_curr_value1 > _prev_value1 && _curr_value2 < _prev_value2) ||
(_prev_value1 > _curr_value1 && _prev_value2 < _curr_value2));
}
/**
* Checks if values are decreasing.
*
* @param int _rows
* Numbers of rows to check.
* @param int _mode
* Indicator index mode to check.
* @param int _shift
* Shift which is the final value to take into the account.
*
* @return
* Returns true when values are increasing.
*/
bool IsDecreasing(int _rows = 1, int _mode = 0, int _shift = 0) {
bool _result = true;
for (int i = _shift + _rows - 1; i >= _shift && _result; i--) {
IndicatorDataEntry _entry_curr = GetEntry(i);
IndicatorDataEntry _entry_prev = GetEntry(i + 1);
_result &= _entry_curr.IsValid() && _entry_prev.IsValid() && _entry_curr[_mode] < _entry_prev[_mode];
if (!_result) {
break;
}
}
return _result;
}
/**
* Checks if value decreased by the given percentage value.
*
* @param int _pct
* Percentage value to use for comparison.
* @param int _mode
* Indicator index mode to use.
* @param int _shift
* Indicator value shift to use.
* @param int _count
* Count of bars to compare change backward.
* @param int _hundreds
* When true, use percentage in hundreds, otherwise 1 is 100%.
*
* @return
* Returns true when value increased.
*/
bool IsDecByPct(float _pct, int _mode = 0, int _shift = 0, int _count = 1, bool _hundreds = true) {
bool _result = true;
IndicatorDataEntry _v0 = GetEntry(_shift);
IndicatorDataEntry _v1 = GetEntry(_shift + _count);
_result &= _v0.IsValid() && _v1.IsValid();
_result &= _result && Math::ChangeInPct(_v1[_mode], _v0[_mode], _hundreds) < _pct;
return _result;
}
/**
* Checks if values are increasing.
*
* @param int _rows
* Numbers of rows to check.
* @param int _mode
* Indicator index mode to check.
* @param int _shift
* Shift which is the final value to take into the account.
*
* @return
* Returns true when values are increasing.
*/
bool IsIncreasing(int _rows = 1, int _mode = 0, int _shift = 0) {
bool _result = true;
for (int i = _shift + _rows - 1; i >= _shift && _result; i--) {
IndicatorDataEntry _entry_curr = GetEntry(i);
IndicatorDataEntry _entry_prev = GetEntry(i + 1);
_result &= _entry_curr.IsValid() && _entry_prev.IsValid() && _entry_curr[_mode] > _entry_prev[_mode];
if (!_result) {
break;
}
}
return _result;
}
/**
* Checks if value increased by the given percentage value.
*
* @param int _pct
* Percentage value to use for comparison.
* @param int _mode
* Indicator index mode to use.
* @param int _shift
* Indicator value shift to use.
* @param int _count
* Count of bars to compare change backward.
* @param int _hundreds
* When true, use percentage in hundreds, otherwise 1 is 100%.
*
* @return
* Returns true when value increased.
*/
bool IsIncByPct(float _pct, int _mode = 0, int _shift = 0, int _count = 1, bool _hundreds = true) {
bool _result = true;
IndicatorDataEntry _v0 = GetEntry(_shift);
IndicatorDataEntry _v1 = GetEntry(_shift + _count);
_result &= _v0.IsValid() && _v1.IsValid();
_result &= _result && Math::ChangeInPct(_v1[_mode], _v0[_mode], _hundreds) > _pct;
return _result;
}
/* Getters */
/**
* Returns the highest bar's index (shift).
*/
template <typename T>
int GetHighest(int count = WHOLE_ARRAY, int start_bar = 0) {
int max_idx = -1;
double max = -DBL_MAX;
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMax<T>(GetModeCount());
if (value > max) {
max = value;
max_idx = shift;
}
}
return max_idx;
}
/**
* Returns the lowest bar's index (shift).
*/
template <typename T>
int GetLowest(int count = WHOLE_ARRAY, int start_bar = 0) {
int min_idx = -1;
double min = DBL_MAX;
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMin<T>(GetModeCount());
if (value < min) {
min = value;
min_idx = shift;
}
}
return min_idx;
}
/**
* Returns the highest value.
*/
template <typename T>
double GetMax(int start_bar = 0, int count = WHOLE_ARRAY) {
double max = NULL;
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
int _max_modes = Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES));
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMax<T>(_max_modes);
if (max == NULL || value > max) {
max = value;
}
}
return max;
}
/**
* Returns the lowest value.
*/
template <typename T>
double GetMin(int start_bar, int count = WHOLE_ARRAY) {
double min = NULL;
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
int _max_modes = Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES));
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMin<T>(_max_modes);
if (min == NULL || value < min) {
min = value;
}
}
return min;
}
/**
* Returns average value.
*/
template <typename T>
double GetAvg(int start_bar, int count = WHOLE_ARRAY) {
int num_values = 0;
double sum = 0;
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
int _max_modes = Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES));
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value_min = GetEntry(shift).GetMin<T>(_max_modes);
double value_max = GetEntry(shift).GetMax<T>(_max_modes);
sum += value_min + value_max;
num_values += 2;
}
return sum / num_values;
}
/**
* Returns median of values.
*/
template <typename T>
double GetMed(int start_bar, int count = WHOLE_ARRAY) {
double array[];
int last_bar = count == WHOLE_ARRAY ? (int)(GetBarShift(GetLastBarTime())) : (start_bar + count - 1);
int num_bars = last_bar - start_bar + 1;
int index = 0;
int _max_modes = Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES));
ArrayResize(array, num_bars);
for (int shift = start_bar; shift <= last_bar; ++shift) {
array[index++] = GetEntry(shift).GetAvg<T>(_max_modes);
}
ArraySort(array);
double median;
int len = ArraySize(array);
if (len % 2 == 0) {
median = (array[len / 2] + array[(len / 2) - 1]) / 2;
} else {
median = array[len / 2];
}
return median;
}
/* Data methods */
/**
* Gets indicator data from a buffer and copy into struct array.
*
* @return
* Returns true of successful copy.
* Returns false on invalid values.
*/
bool CopyEntries(IndicatorDataEntry& _data[], int _count, int _start_shift = 0) {
bool _is_valid = true;
if (ArraySize(_data) < _count) {
_is_valid &= ArrayResize(_data, _count) > 0;
}
for (int i = 0; i < _count; i++) {
IndicatorDataEntry _entry = GetEntry(_start_shift + i);
_is_valid &= _entry.IsValid();
_data[i] = _entry;
}
return _is_valid;
}
/**
* Gets indicator data from a buffer and copy into array of values.
*
* @return
* Returns true of successful copy.
* Returns false on invalid values.
*/
template <typename T>
bool CopyValues(T& _data[], int _count, int _start_shift = 0, int _mode = 0) {
bool _is_valid = true;
if (ArraySize(_data) < _count) {
_count = ArrayResize(_data, _count);
_count = _count > 0 ? _count : ArraySize(_data);
}
for (int i = 0; i < _count; i++) {
IndicatorDataEntry _entry = GetEntry(_start_shift + i);
_is_valid &= _entry.IsValid();
_data[i] = (T)_entry[_mode];
}
return _is_valid;
}
/* Getters */
int GetBarsCalculated(ENUM_TIMEFRAMES _tf = NULL) {
int _bars = Bars(GetSymbol(), _tf);
if (!idparams.Get<bool>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IS_FED))) {
// Calculating start_bar.
for (; calc_start_bar < _bars; ++calc_start_bar) {
// Iterating from the oldest or previously iterated.
IndicatorDataEntry _entry = GetEntry(_bars - calc_start_bar - 1);
if (_entry.IsValid()) {
// From this point we assume that future entries will be all valid.
idparams.Set(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IS_FED), true);
return _bars - calc_start_bar;
}
}
}
if (!idparams.Get<bool>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_IS_FED))) {
Print("Can't find valid bars for ", GetFullName());
return 0;
}
// Assuming all entries are calculated (even if have invalid values).
return _bars;
}
/**
* Returns buffers' cache.
*/
IndicatorCalculateCache<double>* GetCache() { return &cache; }
/**
* Get pointer to data of indicator.
*/
BufferStruct<IndicatorDataEntry>* GetData() { return GET_PTR(idata); }
/**
* Returns given data source type. Used by i*OnIndicator methods if indicator's Calculate() uses other indicators.
*/
IndicatorData* GetDataSource(ENUM_INDICATOR_TYPE _type) {
IndicatorData* _result = NULL;
if (indicators.KeyExists((int)_type)) {
_result = indicators[(int)_type].Ptr();
} else {
Ref<IndicatorData> _indi = FetchDataSource(_type);
if (!_indi.IsSet()) {
Alert(GetFullName(), " does not define required indicator type ", EnumToString(_type), " for symbol ",
GetSymbol(), "!");
DebugBreak();
} else {
indicators.Set((int)_type, _indi);
_result = _indi.Ptr();
}
}
return _result;
}
// int GetDataSourceMode() { return indi_src_mode; }
/**
* Returns currently selected data source without any validation.
*/
IndicatorBase* GetDataSourceRaw() { return indi_src.Ptr(); }
/**
* Returns values for a given shift.
*
* Note: Remember to check if shift exists by HasValidEntry(shift).
*/
template <typename T>
bool GetValues(int _index, T& _out1, T& _out2) {
IndicatorDataEntry _entry = GetEntry(_index);
_out1 = _entry.values[0];
_out2 = _entry.values[1];
bool _result = GetLastError() != 4401;
ResetLastError();
return _result;
}
template <typename T>
bool GetValues(int _index, T& _out1, T& _out2, T& _out3) {
IndicatorDataEntry _entry = GetEntry(_index);
_out1 = _entry.values[0];
_out2 = _entry.values[1];
_out3 = _entry.values[2];
bool _result = GetLastError() != 4401;
ResetLastError();
return _result;
}
template <typename T>
bool GetValues(int _index, T& _out1, T& _out2, T& _out3, T& _out4) {
IndicatorDataEntry _entry = GetEntry(_index);
_out1 = _entry.values[0];
_out2 = _entry.values[1];
_out3 = _entry.values[2];
_out4 = _entry.values[3];
bool _result = GetLastError() != 4401;
ResetLastError();
return _result;
}
/**
* Provides built-in indicators whose can be used as data source.
*/
virtual IndicatorBase* FetchDataSource(ENUM_INDICATOR_TYPE _id) { return NULL; }
/* Checkers */
/**
* Whether we can and have to select mode when specifying data source.
*/
virtual bool IsDataSourceModeSelectable() { return true; }
/* Setters */
/**
* Adds event listener.
*/
void AddListener(IndicatorData* _indi) {
WeakRef<IndicatorData> _ref = _indi;
ArrayPushObject(listeners, _ref);
}
/**
* Removes event listener.
*/
void RemoveListener(IndicatorData* _indi) {
WeakRef<IndicatorData> _ref = _indi;
Util::ArrayRemoveFirst(listeners, _ref);
}
/**
* Sets data source's input mode.
*/
// void SetDataSourceMode(int _mode) { indi_src_mode = _mode; }
/* Storage methods */
ValueStorage<double>* GetValueStorage(int _mode = 0) {
if (_mode >= ArraySize(value_storages)) {
ArrayResize(value_storages, _mode + 1);
}
if (value_storages[_mode] == NULL) {
value_storages[_mode] = new IndicatorBufferValueStorage<double>(THIS_PTR, _mode);
}
return value_storages[_mode];
}
/**
* Returns value storage of given kind.
*/
virtual IValueStorage* GetSpecificValueStorage(ENUM_INDI_VS_TYPE _type) {
Print("Error: ", GetFullName(), " indicator has no storage type ", EnumToString(_type), "!");
DebugBreak();
return NULL;
}
virtual IValueStorage* GetSpecificAppliedPriceValueStorage(ENUM_APPLIED_PRICE _ap) {
switch (_ap) {
case PRICE_ASK:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_ASK);
case PRICE_BID:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_BID);
case PRICE_OPEN:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_OPEN);
case PRICE_HIGH:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_HIGH);
case PRICE_LOW:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_LOW);
case PRICE_CLOSE:
return GetSpecificValueStorage(INDI_VS_TYPE_PRICE_CLOSE);
case PRICE_MEDIAN:
case PRICE_TYPICAL:
case PRICE_WEIGHTED:
default:
Print("Error: Invalid applied price " + EnumToString(_ap) +
", only PRICE_(OPEN|HIGH|LOW|CLOSE) are currently supported by "
"IndicatorBase::GetSpecificAppliedPriceValueStorage()!");
DebugBreak();
return NULL;
}
}
virtual bool HasSpecificAppliedPriceValueStorage(ENUM_APPLIED_PRICE _ap) {
switch (_ap) {
case PRICE_ASK:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_ASK);
case PRICE_BID:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_BID);
case PRICE_OPEN:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_OPEN);
case PRICE_HIGH:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_HIGH);
case PRICE_LOW:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_LOW);
case PRICE_CLOSE:
return HasSpecificValueStorage(INDI_VS_TYPE_PRICE_CLOSE);
case PRICE_MEDIAN:
case PRICE_TYPICAL:
case PRICE_WEIGHTED:
default:
Print("Error: Invalid applied price " + EnumToString(_ap) +
", only PRICE_(OPEN|HIGH|LOW|CLOSE) are currently supported by "
"IndicatorBase::HasSpecificAppliedPriceValueStorage()!");
DebugBreak();
return false;
}
}
/**
* Checks whether indicator support given value storage type.
*/
virtual bool HasSpecificValueStorage(ENUM_INDI_VS_TYPE _type) { return false; }
/* Tick methods */
void Tick() {
long _current_time = TimeCurrent();
if (last_tick_time == _current_time) {
// We've already ticked.
return;
}
last_tick_time = _current_time;
// Checking and potentially initializing new data source.
if (HasDataSource(true) != NULL) {
// Ticking data source if not yet ticked.
GetDataSource().Tick();
}
// Also ticking all used indicators if they've not yet ticked.
for (DictStructIterator<int, Ref<IndicatorData>> iter = indicators.Begin(); iter.IsValid(); ++iter) {
iter.Value().Ptr().Tick();
}
// Overridable OnTick() method.
OnTick();
}
/* Validate methods */
/**
* Loads and validates built-in indicators whose can be used as data source.
*/
void ValidateDataSource(IndicatorData* _target, IndicatorData* _source) {
if (_target == NULL) {
Alert("Internal Error! _target is NULL in ", __FUNCTION_LINE__, ".");
DebugBreak();
return;
}
if (_source == NULL) {
Alert("Error! You have to select source indicator's via SetDataSource().");
DebugBreak();
return;
}
if (!_target.IsDataSourceModeSelectable()) {
// We don't validate source mode as it will use all modes.
return;
}
if (_source.GetModeCount() > 1 &&
_target.idparams.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE)) == -1) {
// Mode must be selected if source indicator has more that one mode.
Alert("Warning! ", GetName(),
" must select source indicator's mode via SetDataSourceMode(int). Defaulting to mode 0.");
_target.idparams.Set(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE), 0);
DebugBreak();
} else if (_source.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE)) == 1 &&
_target.idparams.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE)) == -1) {
_target.idparams.Set(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE), 0);
} else if (_target.idparams.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE)) < 0 ||
_target.idparams.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_DATA_SRC_MODE)) >
_source.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES))) {
Alert("Error! ", _target.GetName(),
" must select valid source indicator's mode via SetDataSourceMode(int) between 0 and ",
_source.Get<int>(STRUCT_ENUM(IndicatorDataParams, IDATA_PARAM_MAX_MODES)), ".");
DebugBreak();
}
}
/**
* Validates currently selected indicator used as data source.
*/
void ValidateSelectedDataSource() {
if (HasDataSource()) {
ValidateDataSource(THIS_PTR, GetDataSourceRaw());
}
}
/* Printers */
/**
* Returns the indicator's value in plain format.
*/
virtual string ToString(int _index = 0) {
IndicatorDataEntry _entry = GetEntry(_index);
int _serializer_flags = SERIALIZER_FLAG_SKIP_HIDDEN | SERIALIZER_FLAG_INCLUDE_DEFAULT |
SERIALIZER_FLAG_INCLUDE_DYNAMIC | SERIALIZER_FLAG_INCLUDE_FEATURE;
IndicatorDataEntry _stub_entry;
_stub_entry.AddFlags(_entry.GetFlags());
SerializerConverter _stub = SerializerConverter::MakeStubObject(_stub_entry, _serializer_flags, _entry.GetSize());
return SerializerConverter::FromObject(_entry, _serializer_flags).ToString<SerializerCsv>(0, &_stub);
}
template <typename T>
T GetValue(int _mode = 0, int _index = 0) {
T _out;
GetEntryValue(_mode, _index).Get(_out);
return _out;
}
/* Virtual methods */
/**
* Returns currently selected data source doing validation.
*/
virtual IndicatorData* GetDataSource() { return NULL; }
/**
* Returns the indicator's struct value.
*/
virtual IndicatorDataEntry GetEntry(datetime _dt) {
Print(GetFullName(),
" must implement IndicatorDataEntry IndicatorBase::GetEntry(datetime _dt) in order to use GetEntry(datetime "
"_dt) or _indi[datetime] subscript operator!");
DebugBreak();
IndicatorDataEntry _default;
return _default;
}
/**
* Returns the indicator's struct value.
*/
virtual IndicatorDataEntry GetEntry(int _index = 0) = NULL;
/**
* Alters indicator's struct value.
*
* This method allows user to modify the struct entry before it's added to cache.
* This method is called on GetEntry() right after values are set.
*/
virtual void GetEntryAlter(IndicatorDataEntry& _entry, int _index = -1) = NULL;
// virtual ENUM_IDATA_VALUE_RANGE GetIDataValueRange() = NULL;
/**
* Returns the indicator's entry value.
*/
virtual IndicatorDataEntryValue GetEntryValue(int _mode = 0, int _shift = 0) = NULL;
/**
* Gets indicator's signals.
*
* When indicator values are not valid, returns empty signals.
*/
virtual IndicatorSignal GetSignals(int _count = 3, int _shift = 0, int _mode1 = 0, int _mode2 = 0) = NULL;
/**
* Sends entry to listening indicators.
*/
void EmitEntry(IndicatorDataEntry& entry) {
for (int i = 0; i < ArraySize(listeners); ++i) {
if (listeners[i].ObjectExists()) {
listeners[i].Ptr().OnDataSourceEntry(entry);
}
}
}
/**
* Sends historic entries to listening indicators. May be overriden.
*/
virtual void EmitHistory() {}
/**
* Called when indicator became a data source for other indicator.
*/
virtual void OnBecomeDataSourceFor(IndicatorData* _base_indi){};
/**
* Called when data source emits new entry (historic or future one).
*/
virtual void OnDataSourceEntry(IndicatorDataEntry& entry){};
virtual void OnTick() {}
/**
* Called if data source is requested, but wasn't yet set. May be used to initialize indicators that must operate on
* some data source.
*/
virtual IndicatorData* OnDataSourceRequest() {
Print("In order to use IDATA_INDICATOR mode for indicator ", GetFullName(),
" without explicitly selecting an indicator, ", GetFullName(),
" must override OnDataSourceRequest() method and return new instance of data source to be used by default.");
DebugBreak();
return NULL;
}
/**
* Creates default, tick based indicator for given applied price.
*/
virtual IndicatorData* DataSourceRequestReturnDefault(int _applied_price) {
DebugBreak();
return NULL;
}
/**
* Called when user tries to set given data source. Could be used to check if indicator implements all required value
* storages.
*/
virtual bool OnValidateDataSource(IndicatorData* _ds, string& _reason) {
_reason = "Indicator " + GetName() + " does not implement OnValidateDataSource()";
return false;
}
/**
* Sets indicator data source.
*/
virtual void SetDataSource(IndicatorData* _indi, int _input_mode = -1) = NULL;
/**
* Update indicator.
*/
virtual bool Update() {
// @todo
return false;
};
/**
* Loads and validates built-in indicators whose can be used as data source.
*/
// virtual void ValidateDataSource(IndicatorData* _target, IndicatorData* _source) {}
/**
* Checks whether indicator have given mode index.
*
* If given mode is -1 (default one) and indicator has exactly one mode, then mode index will be replaced by 0.
*/
virtual void ValidateDataSourceMode(int& _out_mode) {}
};
/**
* BarsCalculated()-compatible method to be used on Indicator instance.
*/
int BarsCalculated(IndicatorData* _indi) { return _indi.GetBarsCalculated(); }
/**
* CopyBuffer() method to be used on Indicator instance with ValueStorage buffer.
*
* Note that data will be copied so that the oldest element will be located at the start of the physical memory
* allocated for the array
*/
template <typename T>
int CopyBuffer(IndicatorData* _indi, int _mode, int _start, int _count, ValueStorage<T>& _buffer, int _rates_total) {
int _num_copied = 0;
int _buffer_size = ArraySize(_buffer);
if (_buffer_size < _rates_total) {
_buffer_size = ArrayResize(_buffer, _rates_total);
}
for (int i = _start; i < _count; ++i) {
IndicatorDataEntry _entry = _indi.GetEntry(i);
if (!_entry.IsValid()) {
break;
}
T _value = _entry.GetValue<T>(_mode);
_buffer[_buffer_size - i - 1] = _value;
++_num_copied;
}
return _num_copied;
}