-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathIndicator.mqh
1300 lines (1159 loc) · 39.6 KB
/
Indicator.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
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
//+------------------------------------------------------------------+
//| EA31337 framework |
//| Copyright 2016-2021, 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/>.
*
*/
// Ignore processing of this file if already included.
#ifndef INDICATOR_MQH
#define INDICATOR_MQH
// Forward declaration.
class Chart;
// Includes.
#include "Array.mqh"
#include "BufferStruct.mqh"
#include "Chart.mqh"
#include "DateTime.mqh"
#include "DrawIndicator.mqh"
#include "Indicator.define.h"
#include "Indicator.enum.h"
#include "Indicator.struct.cache.h"
#include "Indicator.struct.h"
#include "Indicator.struct.serialize.h"
#include "Indicator.struct.signal.h"
#include "IndicatorBase.h"
#include "Math.h"
#include "Object.mqh"
#include "Refs.mqh"
#include "Serializer.mqh"
#include "SerializerCsv.mqh"
#include "SerializerJson.mqh"
#include "Storage/ValueStorage.h"
#include "Storage/ValueStorage.indicator.h"
#include "Storage/ValueStorage.native.h"
#ifndef __MQL4__
// Defines global functions (for MQL4 backward compatibility).
bool IndicatorBuffers(int _count) { return Indicator<IndicatorParams>::SetIndicatorBuffers(_count); }
int IndicatorCounted(int _value = 0) {
static int prev_calculated = 0;
// https://docs.mql4.com/customind/indicatorcounted
prev_calculated = _value > 0 ? _value : prev_calculated;
return prev_calculated;
}
#endif
#ifdef __MQL5__
// Defines global functions (for MQL5 forward compatibility).
template <typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I,
typename J>
double iCustom5(string _symbol, ENUM_TIMEFRAMES _tf, string _name, A _a, B _b, C _c, D _d, E _e, F _f, G _g, H _h, I _i,
J _j, int _mode, int _shift) {
ResetLastError();
static Dict<string, int> _handlers;
string _key = Util::MakeKey(_symbol, (string)_tf, _name, _a, _b, _c, _d, _e, _f, _g, _h, _i, _j);
int _handle = _handlers.GetByKey(_key);
ICUSTOM_DEF(_handlers.Set(_key, _handle),
COMMA _a COMMA _b COMMA _c COMMA _d COMMA _e COMMA _f COMMA _g COMMA _h COMMA _i COMMA _j);
}
#endif
/**
* Class to deal with indicators.
*/
template <typename TS>
class Indicator : public IndicatorBase {
protected:
DrawIndicator* draw;
BufferStruct<IndicatorDataEntry> idata;
TS iparams;
protected:
/* Protected methods */
bool Init() {
ArrayResize(value_storages, iparams.GetMaxModes());
switch (iparams.GetDataSourceType()) {
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 InitDraw();
}
/**
* Initialize indicator data drawing on custom data.
*/
bool InitDraw() {
if (iparams.is_draw && !Object::IsValid(draw)) {
draw = new DrawIndicator(THIS_PTR);
draw.SetColorLine(iparams.indi_color);
}
return iparams.is_draw;
}
/**
* Deinitialize drawing.
*/
void DeinitDraw() {
if (draw) {
delete draw;
}
}
public:
/* Indicator enumerations */
/*
* Default enumerations:
*
* ENUM_MA_METHOD values:
* 0: MODE_SMA (Simple averaging)
* 1: MODE_EMA (Exponential averaging)
* 2: MODE_SMMA (Smoothed averaging)
* 3: MODE_LWMA (Linear-weighted averaging)
*/
/* Special methods */
/**
* Class constructor.
*/
Indicator(const TS& _iparams, IndicatorBase* _indi_src = NULL, int _indi_mode = 0) : IndicatorBase(_indi_src) {
iparams = _iparams;
SetName(_iparams.name != "" ? _iparams.name : EnumToString(iparams.itype));
if (_indi_src != NULL) {
SetDataSource(_indi_src, _indi_mode);
}
Init();
}
Indicator(ENUM_INDICATOR_TYPE _itype, int _shift = 0, string _name = "") {
iparams.SetIndicatorType(_itype);
iparams.SetShift(_shift);
SetName(_name != "" ? _name : EnumToString(iparams.itype));
Init();
}
/**
* Class deconstructor.
*/
~Indicator() { DeinitDraw(); }
/* Getters */
/**
* Gets an indicator's property value.
*/
template <typename T>
T Get(STRUCT_ENUM(IndicatorParams, ENUM_INDI_PARAMS_PROP) _param) const {
return iparams.Get<T>(_param);
}
/**
* Gets an indicator property flag.
*/
bool GetFlag(INDICATOR_ENTRY_FLAGS _prop, datetime _bar_time) {
IndicatorDataEntry _entry = GetEntry(_bar_time);
return _entry.CheckFlag(_prop);
}
/* Buffer methods */
virtual string CacheKey() { return GetName(); }
/**
* Initializes a cached proxy between i*OnArray() methods and OnCalculate()
* used by custom indicators.
*
* Note that OnCalculateProxy() method sets incoming price array as not
* series. It will be reverted back by SetPrevCalculated(). It is because
* OnCalculate() methods assumes that prices are set as not series.
*
* For real example how you can use this method, look at
* Indi_MA::iMAOnArray() method.
*
* Usage:
*
* static double iFooOnArray(double &price[], int total, int period,
* int foo_shift, int foo_method, int shift, string cache_name = "")
* {
* if (cache_name != "") {
* String cache_key;
* cache_key.Add(cache_name);
* cache_key.Add(period);
* cache_key.Add(foo_method);
*
* Ref<IndicatorCalculateCache> cache = Indicator::OnCalculateProxy(cache_key.ToString(), price, total);
*
* int prev_calculated =
* Indi_Foo::Calculate(total, cache.Ptr().prev_calculated, 0, price, cache.Ptr().buffer1, ma_method, period);
*
* cache.Ptr().SetPrevCalculated(price, prev_calculated);
*
* return cache.Ptr().GetValue(1, shift + ma_shift);
* }
* else {
* // Default iFooOnArray.
* }
*
* WARNING: Do not use shifts when creating cache_key, as this will create many invalid buffers.
*/
/*
static IndicatorCalculateCache OnCalculateProxy(string key, double& price[], int& total) {
if (total == 0) {
total = ArraySize(price);
}
// Stores previously calculated value.
static DictStruct<string, IndicatorCalculateCache> cache;
unsigned int position;
IndicatorCalculateCache cache_item;
if (cache.KeyExists(key, position)) {
cache_item = cache.GetByKey(key);
} else {
IndicatorCalculateCache cache_item_new(1, ArraySize(price));
cache_item = cache_item_new;
cache.Set(key, cache_item);
}
// Number of bars available in the chart. Same as length of the input `array`.
int rates_total = ArraySize(price);
int begin = 0;
cache_item.Resize(rates_total);
cache_item.price_was_as_series = ArrayGetAsSeries(price);
ArraySetAsSeries(price, false);
return cache_item;
}
*/
/**
* Allocates memory for buffers used for custom indicator calculations.
*/
static int IndicatorBuffers(int _count = 0) {
static int indi_buffers = 1;
indi_buffers = _count > 0 ? _count : indi_buffers;
return indi_buffers;
}
static int GetIndicatorBuffers() { return Indicator::IndicatorBuffers(); }
static bool SetIndicatorBuffers(int _count) {
Indicator::IndicatorBuffers(_count);
return GetIndicatorBuffers() > 0 && GetIndicatorBuffers() <= 512;
}
/**
* Gets indicator data from a buffer and copy into struct array.
*
* @return
* Returns true of successful copy.
* Returns false on invalid values.
*/
/* @todo
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;
}
/**
* 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
*/
/*
static int CopyBuffer(IndicatorBase * _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;
}
*/
/**
* Validates currently selected indicator used as data source.
*/
void ValidateSelectedDataSource() {
if (HasDataSource()) {
ValidateDataSource(THIS_PTR, GetDataSourceRaw());
}
}
/**
* Loads and validates built-in indicators whose can be used as data source.
*/
void ValidateDataSource(IndicatorBase* _target, IndicatorBase* _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.GetDataSourceMode() == -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.SetDataSourceMode(0);
DebugBreak();
} else if (_source.GetModeCount() == 1 && _target.GetDataSourceMode() == -1) {
_target.SetDataSourceMode(0);
} else if (_target.GetDataSourceMode() < 0 || _target.GetDataSourceMode() > _source.GetModeCount()) {
Alert("Error! ", _target.GetName(),
" must select valid source indicator's mode via SetDataSourceMode(int) between 0 and ",
_source.GetModeCount(), ".");
DebugBreak();
}
}
/**
* 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.
*/
void ValidateDataSourceMode(int& _out_mode) {
if (_out_mode == -1) {
// First mode will be used by default, or, if selected indicator has more than one mode, error will happen.
if (iparams.GetMaxModes() != 1) {
Alert("Error: ", GetName(), " must have exactly one possible mode in order to skip using SetDataSourceMode()!");
DebugBreak();
}
_out_mode = 0;
} else if (_out_mode + 1 > (int)iparams.GetMaxModes()) {
Alert("Error: ", GetName(), " have ", iparams.GetMaxModes(),
" mode(s) buy you tried to reference mode with index ", _out_mode,
"! Ensure that you properly set mode via SetDataSourceMode().");
DebugBreak();
}
}
/**
* Provides built-in indicators whose can be used as data source.
*/
virtual IndicatorBase* FetchDataSource(ENUM_INDICATOR_TYPE _id) { return NULL; }
/* 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 */
/**
* Get pointer to data of indicator.
*/
BufferStruct<IndicatorDataEntry>* GetData() { return GetPointer(idata); }
/**
* 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);
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMax<T>(iparams.GetMaxModes());
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);
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value = GetEntry(shift).GetMin<T>(iparams.GetMaxModes());
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);
for (int shift = start_bar; shift <= last_bar; ++shift) {
double value_min = GetEntry(shift).GetMin<T>(iparams.GetMaxModes());
double value_max = GetEntry(shift).GetMax<T>(iparams.GetMaxModes());
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;
ArrayResize(array, num_bars);
for (int shift = start_bar; shift <= last_bar; ++shift) {
array[index++] = GetEntry(shift).GetAvg<T>(iparams.GetMaxModes());
}
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;
}
/**
* 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;
if (GetIDataValueRange() != IDATA_RANGE_PRICE) {
_price = (float)GetPrice(_ap, _shift);
} else if (GetIDataValueRange() == 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;
}
/**
* Returns currently selected data source doing validation.
*/
IndicatorBase* GetDataSource() {
IndicatorBase* _result = NULL;
if (GetDataSourceRaw() != NULL) {
_result = GetDataSourceRaw();
} else if (iparams.GetDataSourceId() != -1) {
int _source_id = iparams.GetDataSourceId();
if (indicators.KeyExists(_source_id)) {
_result = indicators[_source_id].Ptr();
} else {
Ref<IndicatorBase> _source = FetchDataSource((ENUM_INDICATOR_TYPE)_source_id);
if (!_source.IsSet()) {
Alert(GetName(), " has no built-in source indicator ", _source_id);
DebugBreak();
} else {
indicators.Set(_source_id, _source);
_result = _source.Ptr();
}
}
}
ValidateDataSource(&this, _result);
return _result;
}
/**
* Gets number of modes available to retrieve by GetValue().
*/
virtual int GetModeCount() { return 0; }
/**
* Gets indicator's timeframe.
*/
ENUM_TIMEFRAMES GetTf() {
return ChartTf::SecsToTf(iparams.Get<uint>(STRUCT_ENUM(IndicatorParams, INDI_PARAMS_PROP_BPS)));
}
/**
* Whether data source is selected.
*/
virtual bool HasDataSource() { return GetDataSourceRaw() != NULL || iparams.GetDataSourceId() != -1; }
/**
* Gets indicator's params.
*/
IndicatorParams GetParams() { return iparams; }
/**
* Gets indicator's signals.
*
* When indicator values are not valid, returns empty signals.
*/
/* @todo
IndicatorSignal GetSignals(int _count = 3, int _shift = 0, int _mode1 = 0, int _mode2 = 0) {
bool _is_valid = true;
IndicatorDataEntry _data[];
if (!CopyEntries(_data, _count, _shift)) {
// Some copied data is invalid, so returns empty signals.
IndicatorSignal _signals(0);
return _signals;
}
// Returns signals.
IndicatorSignal _signals(_data, iparams, cparams, _mode1, _mode2);
return _signals;
}
*/
/**
* Get name of the indicator.
*/
string GetName() { return iparams.name; }
/**
* Get full name of the indicator (with "over ..." part).
*/
string GetFullName() {
return iparams.name + "[" + IntegerToString(iparams.GetMaxModes()) + "]" +
(HasDataSource() ? (" (over " + GetDataSource().GetFullName() + ")") : "");
}
/**
* Get more descriptive name of the indicator.
*/
string GetDescriptiveName() {
string name = iparams.name + " (";
switch (iparams.GetDataSourceType()) {
case IDATA_BUILTIN:
name += "built-in, ";
break;
case IDATA_ICUSTOM:
name += "custom, ";
break;
case IDATA_INDICATOR:
name += "over " + GetDataSource().GetDescriptiveName() + ", ";
break;
}
name += IntegerToString(iparams.GetMaxModes()) + (iparams.GetMaxModes() == 1 ? " mode" : " modes");
return name + ")";
}
/* Setters */
/**
* Sets an indicator's chart parameter value.
*/
template <typename T>
void Set(STRUCT_ENUM(IndicatorParams, ENUM_INDI_PARAMS_PROP) _param, T _value) {
iparams.Set<T>(_param, _value);
}
/**
* Sets indicator data source.
*/
void SetDataSource(IndicatorBase* _indi, int _input_mode = 0) {
if (indi_src.IsSet() && indi_src.Ptr() != _indi) {
indi_src.Ptr().RemoveListener(THIS_PTR);
}
indi_src = _indi;
indi_src.Ptr().AddListener(THIS_PTR);
iparams.SetDataSource(-1, _input_mode);
indi_src.Ptr().OnBecomeDataSourceFor(THIS_PTR);
}
/**
* Sets name of the indicator.
*/
void SetName(string _name) { iparams.SetName(_name); }
/**
* Sets indicator's handle.
*
* Note: Not supported in MT4.
*/
void SetHandle(int _handle) {
istate.handle = _handle;
istate.is_changed = true;
}
/**
* Sets indicator's params.
*/
void SetParams(IndicatorParams& _iparams) { iparams = _iparams; }
/* Conditions */
/**
* Checks for indicator condition.
*
* @param ENUM_INDICATOR_CONDITION _cond
* Indicator condition.
* @param MqlParam[] _args
* Condition arguments.
* @return
* Returns true when the condition is met.
*/
bool CheckCondition(ENUM_INDICATOR_CONDITION _cond, DataParamEntry& _args[]) {
switch (_cond) {
case INDI_COND_ENTRY_IS_MAX:
// @todo: Add arguments, check if the entry value is max.
return false;
case INDI_COND_ENTRY_IS_MIN:
// @todo: Add arguments, check if the entry value is min.
return false;
case INDI_COND_ENTRY_GT_AVG:
// @todo: Add arguments, check if...
// Indicator entry value is greater than average.
return false;
case INDI_COND_ENTRY_GT_MED:
// @todo: Add arguments, check if...
// Indicator entry value is greater than median.
return false;
case INDI_COND_ENTRY_LT_AVG:
// @todo: Add arguments, check if...
// Indicator entry value is lesser than average.
return false;
case INDI_COND_ENTRY_LT_MED:
// @todo: Add arguments, check if...
// Indicator entry value is lesser than median.
return false;
default:
SetUserError(ERR_INVALID_PARAMETER);
return false;
}
}
bool CheckCondition(ENUM_INDICATOR_CONDITION _cond) {
ARRAY(DataParamEntry, _args);
return Indicator::CheckCondition(_cond, _args);
}
/**
* Execute Indicator action.
*
* @param ENUM_INDICATOR_ACTION _action
* Indicator action to execute.
* @param MqlParam _args
* Indicator action arguments.
* @return
* Returns true when the action has been executed successfully.
*/
virtual bool ExecuteAction(ENUM_INDICATOR_ACTION _action, DataParamEntry& _args[]) {
bool _result = true;
long _arg1 = ArraySize(_args) > 0 ? DataParamEntry::ToInteger(_args[0]) : WRONG_VALUE;
switch (_action) {
case INDI_ACTION_CLEAR_CACHE:
_arg1 = _arg1 > 0 ? _arg1 : TimeCurrent();
idata.Clear(_arg1);
return true;
default:
SetUserError(ERR_INVALID_PARAMETER);
return false;
}
return _result;
}
bool ExecuteAction(ENUM_INDICATOR_ACTION _action) {
ARRAY(DataParamEntry, _args);
return ExecuteAction(_action, _args);
}
bool ExecuteAction(ENUM_INDICATOR_ACTION _action, long _arg1) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
ArrayPushObject(_args, _param1);
_args[0].integer_value = _arg1;
return ExecuteAction(_action, _args);
}
/* Other methods */
/**
* Releases indicator's handle.
*
* Note: Not supported in MT4.
*/
void ReleaseHandle() {
#ifdef __MQL5__
if (istate.handle != INVALID_HANDLE) {
IndicatorRelease(istate.handle);
}
#endif
istate.handle = INVALID_HANDLE;
istate.is_changed = true;
}
/**
* Adds entry to the indicator's buffer. Invalid entry won't be added.
*/
bool AddEntry(IndicatorDataEntry& entry, datetime _timestamp = 0) {
if (entry.IsValid()) {
entry.timestamp = _timestamp;
idata.Add(entry, _timestamp);
return true;
}
return false;
}
/**
* Returns shift at which the last known valid entry exists for a given
* period (or from the start, when period is not specified).
*/
/*
bool GetLastValidEntryShift(int& out_shift, int period = 0) {
out_shift = 0;
while (true) {
if ((period != 0 && out_shift >= period) || !HasValidEntry(out_shift + 1))
return out_shift > 0; // Current shift is always invalid.
++out_shift;
}
return out_shift > 0;
}*/
/**
* Returns shift at which the oldest known valid entry exists for a given
* period (or from the start, when period is not specified).
*/
/*
bool GetOldestValidEntryShift(int& out_shift, int& out_num_valid, int shift = 0, int period = 0) {
bool found = false;
// Counting from previous up to previous - period.
for (out_shift = shift + 1; out_shift < shift + period + 1; ++out_shift) {
if (!HasValidEntry(out_shift)) {
--out_shift;
out_num_valid = out_shift - shift;
return found;
} else
found = true;
}
--out_shift;