-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathStrategy.mqh
1266 lines (1159 loc) · 37.7 KB
/
Strategy.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/>.
*
*/
// Prevents processing this includes file for the second time.
#ifndef STRATEGY_MQH
#define STRATEGY_MQH
// Forward declaration.
class Trade;
// Includes.
#include "Data.struct.h"
#include "Dict.mqh"
#include "Indicator.mqh"
#include "Market.mqh"
#include "Object.mqh"
#include "Strategy.enum.h"
#include "Strategy.struct.h"
#include "String.mqh"
#include "Task.mqh"
#include "Trade.mqh"
// Defines.
// Primary inputs.
#ifdef __input__
#define INPUT input
#ifndef __MQL4__
#define INPUT_GROUP(name) input group #name
#else
#define INPUT_GROUP(name) static input string; // #name
#endif
#else
#define INPUT static
#define INPUT_GROUP(name) static string
#endif
// Secondary inputs.
#ifdef __input2__
#define INPUT2 input
#ifndef __MQL4__
#define INPUT2_GROUP(name) input group #name
#else
#define INPUT2_GROUP(name) static input string; // #name
#endif
#else
#define INPUT2 static
#define INPUT2_GROUP(name) static string
#endif
// Tertiary inputs.
#ifdef __input3__
#define INPUT3 input
#ifndef __MQL4__
#define INPUT3_GROUP(name) input group #name
#else
#define INPUT3_GROUP(name) static input string; // #name
#endif
#else
#define INPUT3 static
#define INPUT3_GROUP(name) static string
#endif
#ifdef __optimize__
#define OINPUT input
#else
#define OINPUT static
#endif
/**
* Implements strategy class.
*/
class Strategy : public Object {
public:
StgParams sparams;
protected:
Dict<int, double> ddata;
Dict<int, float> fdata;
Dict<int, int> idata;
DictStruct<int, Ref<IndicatorBase>> indicators; // Indicators list.
DictStruct<short, TaskEntry> tasks;
Log logger; // Log instance.
MqlTick last_tick;
StgProcessResult sresult;
Strategy *strat_sl, *strat_tp; // Strategy pointers for stop-loss and profit-take.
Trade trade; // Trade instance.
// TradeSignalEntry last_signal; // Last signals.
private:
// Strategy statistics.
StgStats stats;
StgStatsPeriod stats_period[FINAL_ENUM_STRATEGY_STATS_PERIOD];
protected:
// Base variables.
string name;
// Other variables.
int filter_method[]; // Filter method to consider the trade.
int open_condition[]; // Open conditions.
int close_condition[]; // Close conditions.
public:
/* Special methods */
/**
* Class constructor.
*/
Strategy(StgParams &_sparams, TradeParams &_tparams, ChartParams &_cparams, string _name = "")
: sparams(_sparams), trade(_tparams, _cparams), Object(GetPointer(this), __LINE__) {
// Initialize variables.
name = _name;
MqlTick _tick = {0};
last_tick = _tick;
// Link log instances.
logger.Link(trade.GetLogger());
// Statistics variables.
// UpdateOrderStats(EA_STATS_DAILY);
// UpdateOrderStats(EA_STATS_WEEKLY);
// UpdateOrderStats(EA_STATS_MONTHLY);
// UpdateOrderStats(EA_STATS_TOTAL);
// Call strategy's OnInit method.
Strategy::OnInit();
}
Log *GetLogger() { return GetPointer(logger); }
/**
* Class deconstructor.
*/
~Strategy() {}
/* Processing methods */
/**
* Process strategy's signals and orders.
*
* @param ushort _periods_started
* Periods which started.
*
* @return
* Returns StgProcessResult struct.
*/
StgProcessResult Process(unsigned short _periods_started = DATETIME_NONE) {
sresult.last_error = ERR_NO_ERROR;
if (_periods_started > 0) {
ProcessTasks();
}
return sresult;
}
/* Tasks */
/**
* Add task.
*/
void AddTask(TaskEntry &_entry) {
if (_entry.IsValid()) {
if (_entry.GetAction().GetType() == ACTION_TYPE_STRATEGY) {
_entry.SetActionObject(GetPointer(this));
}
if (_entry.GetCondition().GetType() == COND_TYPE_STRATEGY) {
_entry.SetConditionObject(GetPointer(this));
}
tasks.Push(_entry);
}
}
/**
* Process strategy's tasks.
*
* @return
* Returns StgProcessResult struct.
*/
void ProcessTasks() {
for (DictStructIterator<short, TaskEntry> iter = tasks.Begin(); iter.IsValid(); ++iter) {
bool _is_processed = false;
TaskEntry _entry = iter.Value();
_is_processed = Task::Process(_entry);
sresult.tasks_processed += (unsigned short)_is_processed;
sresult.tasks_processed_not += (unsigned short)!_is_processed;
}
}
/* State checkers */
/**
* Check state of the strategy.
*/
bool IsEnabled() { return sparams.IsEnabled(); }
/**
* Check suspension status of the strategy.
*/
bool IsSuspended() { return sparams.IsSuspended(); }
/**
* Checks if the current price is in trend given the order type.
*/
bool IsTrend(ENUM_ORDER_TYPE _cmd) {
bool _result = false;
double _tvalue = TrendStrength();
switch (_cmd) {
case ORDER_TYPE_BUY:
_result = _tvalue > sparams.trend_threshold;
break;
case ORDER_TYPE_SELL:
_result = _tvalue < -sparams.trend_threshold;
break;
}
return _result;
}
/**
* Check state of the strategy.
*/
bool IsBoostEnabled() { return sparams.IsBoosted(); }
/* Class getters */
/**
* Returns handler to the strategy's indicator class.
*/
IndicatorBase *GetIndicator(int _id = 0) {
if (indicators.KeyExists(_id)) {
return indicators[_id].Ptr();
}
Alert("Missing indicator id ", _id);
return NULL;
}
/**
* Returns strategy's indicators.
*/
DictStruct<int, Ref<IndicatorBase>> GetIndicators() { return indicators; }
/* Struct getters */
/**
* Gets result of the last signal processing.
*/
StgProcessResult GetProcessResult() { return sresult; }
/* Getters */
/**
* Gets a strategy parameter value.
*/
template <typename T>
T Get(ENUM_STRATEGY_PARAM _param) {
return sparams.Get<T>(_param);
}
/**
* Gets a trade parameter value.
*/
template <typename T>
T Get(ENUM_TRADE_PARAM _param) {
return trade.Get<T>(_param);
}
/**
* Gets a trade state value.
*/
template <typename T>
T Get(ENUM_TRADE_STATE _prop) {
return trade.Get<T>(_prop);
}
/**
* Gets strategy entry.
*/
StgEntry GetEntry() {
StgEntry _entry = {};
for (ENUM_STRATEGY_STATS_PERIOD _p = EA_STATS_DAILY; _p < FINAL_ENUM_STRATEGY_STATS_PERIOD; _p++) {
_entry.SetStats(stats_period[_p], _p);
}
return _entry;
}
/**
* Gets pointer to strategy's stop-loss strategy.
*/
Strategy *GetStratSl() { return strat_sl; }
/**
* Gets pointer to strategy's take-profit strategy.
*/
Strategy *GetStratTp() { return strat_tp; }
/**
* Get strategy's name.
*/
string GetName() { return name; }
/**
* Get strategy's ID.
*/
virtual long GetId() { return sparams.id; }
/**
* Get strategy's signal open method.
*/
int GetSignalOpenMethod() { return sparams.signal_open_method; }
/**
* Get strategy's signal open level.
*/
double GetSignalOpenLevel() { return sparams.signal_open_level; }
/**
* Get strategy's signal close method.
*/
int GetSignalCloseMethod() { return sparams.signal_close_method; }
/**
* Get strategy's signal close level.
*/
double GetSignalCloseLevel() { return sparams.signal_close_level; }
/**
* Get strategy's price stop method.
*/
int GetPriceStopMethod() { return sparams.signal_close_method; }
/**
* Get strategy's price stop level.
*/
double GetPriceStopLevel() { return sparams.signal_close_level; }
/**
* Get strategy's order open comment.
*/
string GetOrderOpenComment(string _prefix = "", string _suffix = "") {
// @todo: Add spread.
// return StringFormat("%s%s[%s];s:%gp%s", _prefix != "" ? _prefix + ": " : "", name, trade.chart.TfToString(),
// GetCurrSpread(), _suffix != "" ? "| " + _suffix : "");
return StringFormat("%s%s[%s]%s", _prefix, name, ChartTf::TfToString(trade.Get<ENUM_TIMEFRAMES>(CHART_PARAM_TF)),
_suffix);
}
/**
* Get strategy's order close comment.
*/
string GetOrderCloseComment(string _prefix = "", string _suffix = "") {
// @todo: Add spread.
return StringFormat("%s%s[%s]%s", _prefix, name, ChartTf::TfToString(trade.Get<ENUM_TIMEFRAMES>(CHART_PARAM_TF)),
_suffix);
}
/**
* Get strategy orders currently open.
*/
uint GetOrdersOpen() {
// UpdateOrderStats(EA_STATS_TOTAL);
// @todo
return stats.orders_open;
}
/**
* Get strategy's params.
*/
StgParams GetParams() const { return sparams; }
/**
* Gets custom data.
*/
Dict<int, double> *GetDataD() { return &ddata; }
Dict<int, float> *GetDataF() { return &fdata; }
Dict<int, int> *GetDataI() { return &idata; }
/* Statistics */
/**
* Gets strategy orders total opened.
*/
uint GetOrdersTotal(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].orders_total;
}
/**
* Gets strategy orders won.
*/
uint GetOrdersWon(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].orders_won;
}
/**
* Gets strategy orders lost.
*/
uint GetOrdersLost(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].orders_lost;
}
/**
* Gets strategy net profit.
*/
double GetNetProfit(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].net_profit;
}
/**
* Gets strategy gross profit.
*/
double GetGrossProfit(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].gross_profit;
}
/**
* Gets strategy gross loss.
*/
double GetGrossLoss(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].gross_loss;
}
/**
* Gets the average spread of the strategy (in pips).
*/
double GetAvgSpread(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
// UpdateOrderStats(_period);
return stats_period[_period].avg_spread;
}
/* Setters */
/**
* Sets a strategy parameter value.
*/
template <typename T>
void Set(ENUM_STRATEGY_PARAM _param, T _value) {
sparams.Set<T>(_param, _value);
}
/**
* Sets a trade parameter value.
*/
template <typename T>
void Set(ENUM_TRADE_PARAM _param, T _value) {
trade.Set<T>(_param, _value);
}
/**
* Sets strategy's name.
*/
void SetName(string _name) { name = _name; }
/**
* Sets strategy's ID.
*/
void SetId(long _id) {
sparams.id = _id;
((Object *)GetPointer(this)).SetId(_id);
}
/**
* Sets strategy's stops.
*/
void SetStops(Strategy *_strat_sl = NULL, Strategy *_strat_tp = NULL) {
strat_sl = _strat_sl != NULL ? _strat_sl : strat_sl;
strat_tp = _strat_tp != NULL ? _strat_tp : strat_tp;
}
/**
* Enable/disable the strategy.
*/
void Enabled(bool _enable = true) { sparams.Enabled(_enable); }
/**
* Suspend the strategy.
*/
void Suspended(bool _suspended = true) { sparams.Suspended(_suspended); }
/**
* Sets custom data.
*/
void SetData(Dict<int, double> *_ddata) { ddata = _ddata; }
void SetData(Dict<int, float> *_fdata) { fdata = _fdata; }
void SetData(Dict<int, int> *_idata) { idata = _idata; }
/**
* Sets reference to indicator.
*/
void SetIndicator(IndicatorBase *_indi, int _id = 0) {
Ref<IndicatorBase> _ref = _indi;
indicators.Set(_id, _ref);
}
/* Static setters */
/**
* Sets initial params based on the timeframe.
*/
template <typename T>
static void SetParamsByTf(T &_result, ENUM_TIMEFRAMES _tf, T &_m1, T &_m5, T &_m15, T &_m30, T &_h1, T &_h4, T &_h8) {
switch (_tf) {
case PERIOD_M1: {
_result = _m1;
break;
}
case PERIOD_M5: {
_result = _m5;
break;
}
case PERIOD_M15: {
_result = _m15;
break;
}
case PERIOD_M30: {
_result = _m30;
break;
}
case PERIOD_H1: {
_result = _h1;
break;
}
case PERIOD_H4: {
_result = _h4;
break;
}
case PERIOD_H8: {
_result = _h8;
break;
}
}
}
/* Calculation methods */
/**
* Get lot size factor.
*/
double UpdateLotSizeFactor() { return 1.0; }
/**
* Update order stat variables.
*/
/* @todo: Refactor.
void UpdateOrderStats(ENUM_STRATEGY_STATS_PERIOD _period) {
// @todo: Implement support for _period.
static datetime _last_update = TimeCurrent();
if (_last_update > TimeCurrent() - sparams.refresh_time) {
return; // Do not update too often.
}
unsigned int _total = 0, _won = 0, _lost = 0, _open = 0;
int i;
double _gross_profit = 0, _gross_loss = 0, _net_profit = 0, _order_profit = 0;
datetime _order_datetime;
for (i = 0; i < Trade::OrdersTotal(); i++) {
// @todo: Select order.
if (GetMarket().GetSymbol() == Order::OrderSymbol() && trade.tparams.GetMagicNo() == Order::OrderMagicNumber()) {
_total++;
_order_profit = Order::OrderProfit() - Order::OrderCommission() - Order::OrderSwap();
_net_profit += _order_profit;
if (Order::OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
_open++;
} else {
_order_datetime = (datetime)OrderGetInteger(ORDER_TIME_DONE);
// s_daily_net_profit += @todo;
// s_weekly_net_profit += @todo;
// s_monhtly_net_profit += @todo;
if (_order_profit > 0) {
_won++;
_gross_profit += _order_profit;
} else {
_lost++;
_gross_loss += _order_profit;
}
}
}
}
// stats.orders_open = _open;
stats_period[_period].orders_won = _won;
stats_period[_period].orders_lost = _lost;
stats_period[_period].orders_total = _total;
stats_period[_period].net_profit = _net_profit;
stats_period[_period].gross_profit = _gross_loss;
stats_period[_period].gross_loss = _gross_profit;
// stats_period[_period].profit_factor = _profit_factor;
_last_update = TimeCurrent();
}
*/
/**
* Get profit factor of the strategy.
*/
double GetProfitFactor() {
// @todo
return 0.0;
}
/**
* Get current spread (in pips).
*/
// double GetCurrSpread() { return trade.chart.GetSpreadInPips(); }
/**
* Convert timeframe constant to index value.
*/
uint TfToIndex(ENUM_TIMEFRAMES _tf) { return ChartTf::TfToIndex(_tf); }
/**
* Class constructor.
*/
/*
bool Strategy() {
// Trading variables.
s_lot_size = si_lot_size;
s_lot_factor = GetLotSizeFactor();
s_avg_spread = GetCurrSpread();
s_tp_max = 0;
s_sl_max = 0;
// Statistics variables.
s_orders_open = GetOrdersOpen();
s_orders_total = GetOrdersTotal();
s_orders_won = GetOrdersWon();
s_orders_lost = GetOrdersLost();
s_profit_factor = GetProfitFactor();
s_avg_spread = GetAvgSpread();
s_total_net_profit = GetTotalNetProfit();
s_total_gross_profit = GetTotalGrossProfit();
s_total_gross_loss = GetTotalGrossLoss();
s_daily_net_profit = GetDailyNetProfit();
s_weekly_net_profit = GetWeeklyNetProfit();
s_monhtly_net_profit = GetMonthlyNetProfit();
// Other variables.
s_refresh_time = 10;
}
*/
/**
* Initialize strategy.
*/
bool Init() {
if (!trade.IsValid()) {
/* @fixme
logger.Warning(StringFormat("Could not initialize %s on %s timeframe!", GetName(),
trade.GetChart().TfToString()),
__FUNCTION__ + ": ");
*/
return false;
}
return true;
}
/* Conditions and actions */
/**
* Checks for Strategy condition.
*
* @param ENUM_STRATEGY_CONDITION _cond
* Strategy condition.
* @return
* Returns true when the condition is met.
*/
bool CheckCondition(ENUM_STRATEGY_CONDITION _cond, DataParamEntry &_args[]) {
bool _result = true;
long arg_size = ArraySize(_args);
long _arg1l = ArraySize(_args) > 0 ? DataParamEntry::ToInteger(_args[0]) : WRONG_VALUE;
long _arg2l = ArraySize(_args) > 1 ? DataParamEntry::ToInteger(_args[1]) : WRONG_VALUE;
long _arg3l = ArraySize(_args) > 2 ? DataParamEntry::ToInteger(_args[2]) : WRONG_VALUE;
switch (_cond) {
case STRAT_COND_IS_ENABLED:
return sparams.IsEnabled();
case STRAT_COND_IS_SUSPENDED:
return sparams.IsSuspended();
case STRAT_COND_IS_TREND:
_arg1l = _arg1l != WRONG_VALUE ? _arg1l : 0;
return IsTrend((ENUM_ORDER_TYPE)_arg1l);
case STRAT_COND_SIGNALOPEN: {
ENUM_ORDER_TYPE _cmd = ArraySize(_args) > 1 ? (ENUM_ORDER_TYPE)_args[0].integer_value : ORDER_TYPE_BUY;
int _method = ArraySize(_args) > 1 ? (int)_args[1].integer_value : 0;
float _level = ArraySize(_args) > 2 ? (float)_args[2].double_value : 0;
return SignalOpen(_cmd, _method, _level);
}
case STRAT_COND_TRADE_COND:
// Args:
// 1st (i:0) - Trade's enum condition to check.
// 2rd... (i:1) - Optionally trade's arguments to pass.
if (arg_size > 0) {
DataParamEntry _sargs[];
ArrayResize(_sargs, ArraySize(_args) - 1);
for (int i = 0; i < ArraySize(_sargs); i++) {
_sargs[i] = _args[i + 1];
}
_result = trade.CheckCondition((ENUM_TRADE_CONDITION)_arg1l, _sargs);
}
return _result;
default:
GetLogger().Error(StringFormat("Invalid EA condition: %s!", EnumToString(_cond), __FUNCTION_LINE__));
return false;
}
}
bool CheckCondition(ENUM_STRATEGY_CONDITION _cond, long _arg1) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
ArrayPushObject(_args, _param1);
return Strategy::CheckCondition(_cond, _args);
}
bool CheckCondition(ENUM_STRATEGY_CONDITION _cond, long _arg1, long _arg2) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
DataParamEntry _param2 = _arg2;
ArrayPushObject(_args, _param1);
ArrayPushObject(_args, _param2);
return Strategy::CheckCondition(_cond, _args);
}
bool CheckCondition(ENUM_STRATEGY_CONDITION _cond) {
ARRAY(DataParamEntry, _args);
return CheckCondition(_cond, _args);
}
/**
* Execute Strategy action.
*
* @param ENUM_STRATEGY_ACTION _action
* Strategy action to execute.
* @param MqlParam _args
* Strategy action arguments.
* @return
* Returns true when the action has been executed successfully.
*/
bool ExecuteAction(ENUM_STRATEGY_ACTION _action, DataParamEntry &_args[]) {
bool _result = true;
double arg1d = EMPTY_VALUE;
double arg2d = EMPTY_VALUE;
double arg3d = EMPTY_VALUE;
long arg1i = EMPTY;
long arg2i = EMPTY;
long arg3i = EMPTY;
long arg_size = ArraySize(_args);
if (arg_size > 0) {
arg1d = _args[0].type == TYPE_DOUBLE ? _args[0].double_value : EMPTY_VALUE;
arg1i = _args[0].type == TYPE_INT ? _args[0].integer_value : EMPTY;
if (arg_size > 1) {
arg2d = _args[1].type == TYPE_DOUBLE ? _args[1].double_value : EMPTY_VALUE;
arg2i = _args[1].type == TYPE_INT ? _args[1].integer_value : EMPTY;
}
if (arg_size > 2) {
arg3d = _args[2].type == TYPE_DOUBLE ? _args[2].double_value : EMPTY_VALUE;
arg3i = _args[2].type == TYPE_INT ? _args[2].integer_value : EMPTY;
}
}
switch (_action) {
case STRAT_ACTION_DISABLE:
sparams.Enabled(false);
return true;
case STRAT_ACTION_ENABLE:
sparams.Enabled(true);
return true;
case STRAT_ACTION_SUSPEND:
sparams.Suspended(true);
return true;
case STRAT_ACTION_TRADE_EXE:
// Args:
// 1st (i:0) - Trade's enum action to execute.
// 2rd (i:1) - Trade's argument to pass.
if (arg_size > 0) {
DataParamEntry _sargs[];
ArrayResize(_sargs, ArraySize(_args) - 1);
for (int i = 0; i < ArraySize(_sargs); i++) {
_sargs[i] = _args[i + 1];
}
_result = trade.ExecuteAction((ENUM_TRADE_ACTION)_args[0].integer_value, _sargs);
/* @fixme
if (_result) {
Order *_order = trade.GetOrderLast();
switch ((ENUM_TRADE_ACTION)_args[0].integer_value) {
case TRADE_ACTION_ORDERS_CLOSE_BY_TYPE:
// OnOrderClose();// @todo
break;
case TRADE_ACTION_ORDER_OPEN:
// @fixme: Operation on the structure copy.
OnOrderOpen(_order.GetParams());
break;
}
}
*/
}
return _result;
case STRAT_ACTION_UNSUSPEND:
sparams.Suspended(false);
return true;
default:
GetLogger().Error(StringFormat("Invalid Strategy action: %s!", EnumToString(_action), __FUNCTION_LINE__));
return false;
}
return _result;
}
bool ExecuteAction(ENUM_STRATEGY_ACTION _action, long _arg1) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
ArrayPushObject(_args, _param1);
return Strategy::ExecuteAction(_action, _args);
}
bool ExecuteAction(ENUM_STRATEGY_ACTION _action, long _arg1, long _arg2) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
DataParamEntry _param2 = _arg2;
ArrayPushObject(_args, _param1);
ArrayPushObject(_args, _param2);
return Strategy::ExecuteAction(_action, _args);
}
bool ExecuteAction(ENUM_STRATEGY_ACTION _action, long _arg1, long _arg2, long _arg3) {
ARRAY(DataParamEntry, _args);
DataParamEntry _param1 = _arg1;
DataParamEntry _param2 = _arg2;
DataParamEntry _param3 = _arg3;
ArrayPushObject(_args, _param1);
ArrayPushObject(_args, _param2);
ArrayPushObject(_args, _param3);
return Strategy::ExecuteAction(_action, _args);
}
bool ExecuteAction(ENUM_STRATEGY_ACTION _action) {
ARRAY(DataParamEntry, _args);
return Strategy::ExecuteAction(_action, _args);
}
/* Printers methods */
/**
* Prints strategy's details.
*/
string const ToString() { return StringFormat("%s: %s", GetName(), sparams.ToString()); }
/* Virtual methods */
/**
* Event on order close.
*/
virtual void OnOrderClose(ENUM_ORDER_TYPE _cmd) {}
/**
* Event on strategy's init.
*/
virtual void OnInit() {
SetStops(GetPointer(this), GetPointer(this));
// trade.SetStrategy(&this); // @fixme
}
/**
* Event on strategy's order open.
*
* @param
* _oparams Order parameters to update before the open.
*/
virtual void OnOrderOpen(OrderParams &_oparams) {
int _index = 0;
ENUM_TIMEFRAMES _stf = Get<ENUM_TIMEFRAMES>(STRAT_PARAM_TF);
unsigned int _stf_secs = ChartTf::TfToSeconds(_stf);
if (sparams.order_close_time != 0) {
long _close_time_arg = sparams.order_close_time > 0 ? sparams.order_close_time * 60
: (int)round(-sparams.order_close_time * _stf_secs);
_oparams.Set(ORDER_PARAM_COND_CLOSE, ORDER_COND_LIFETIME_GT_ARG, _index);
_oparams.Set(ORDER_PARAM_COND_CLOSE_ARG_VALUE, _close_time_arg, _index);
_index++;
}
if (sparams.order_close_loss != 0.0f) {
float _loss_limit = sparams.order_close_loss;
_oparams.Set(ORDER_PARAM_COND_CLOSE, ORDER_COND_IN_LOSS, _index);
_oparams.Set(ORDER_PARAM_COND_CLOSE_ARG_VALUE, _loss_limit, _index);
_index++;
}
if (sparams.order_close_profit != 0.0f) {
float _profit_limit = sparams.order_close_profit;
_oparams.Set(ORDER_PARAM_COND_CLOSE, ORDER_COND_IN_PROFIT, _index);
_oparams.Set(ORDER_PARAM_COND_CLOSE_ARG_VALUE, _profit_limit, _index);
_index++;
}
_oparams.Set(ORDER_PARAM_UPDATE_FREQ, _stf_secs);
}
/**
* Event on new time periods.
*
* Example:
* unsigned short _periods = (DATETIME_MINUTE | DATETIME_HOUR);
* OnPeriod(_periods);
*
* @param
* _periods unsigned short
* List of periods which started. See: ENUM_DATETIME_UNIT.
*/
virtual void OnPeriod(unsigned int _periods = DATETIME_NONE) {
if ((_periods & DATETIME_MINUTE) != 0) {
// New minute started.
#ifndef __optimize__
if (Terminal::IsRealtime()) {
logger.Flush();
}
#endif
}
if ((_periods & DATETIME_HOUR) != 0) {
// New hour started.
}
if ((_periods & DATETIME_DAY) != 0) {
// New day started.
#ifndef __optimize__
GetLogger().Flush();
#endif
}
if ((_periods & DATETIME_WEEK) != 0) {
// New week started.
}
if ((_periods & DATETIME_MONTH) != 0) {
// New month started.
}
if ((_periods & DATETIME_YEAR) != 0) {
// New year started.
}
}
/**
* Filters strategy's market tick.
*
* @param
* _method - signal method to filter a tick (bitwise AND operation)
*
* @result bool
* Returns true when tick should be processed, otherwise false.
*/
virtual bool TickFilter(const MqlTick &_tick, const int _method) {
bool _res = _method >= 0;
bool _val;
int _method_abs = fabs(_method);
if (_method_abs != 0) {
if (METHOD(_method_abs, 0)) { // 1
// Process on every minute.
_val = _tick.time % 60 < last_tick.time % 60;
_res = _method > 0 ? _res & _val : _res | _val;
last_tick = _tick;
}
if (METHOD(_method_abs, 1)) { // 2
// Process low and high ticks of a bar.
_val = _tick.bid >= trade.GetChart().GetHigh() || _tick.bid <= trade.GetChart().GetLow();
_res = _method > 0 ? _res & _val : _res | _val;
}
if (METHOD(_method_abs, 2)) { // 4
// Process only peak prices of each minute.
static double _peak_high = _tick.bid, _peak_low = _tick.bid;
if (_tick.time % 60 < last_tick.time % 60) {
// Resets peaks each minute.
_peak_high = _peak_low = _tick.bid;
} else {
// Sets new peaks.
_peak_high = _tick.bid > _peak_high ? _tick.bid : _peak_high;
_peak_low = _tick.bid < _peak_low ? _tick.bid : _peak_low;
}
_val = (_tick.bid == _peak_high) || (_tick.bid == _peak_low);
_res = _method > 0 ? _res & _val : _res | _val;
}
if (METHOD(_method_abs, 3)) { // 8
// Process only unique ticks (avoid duplicates).
_val = _tick.bid != last_tick.bid && _tick.ask != last_tick.ask;
_res = _method > 0 ? _res & _val : _res | _val;
}
if (METHOD(_method_abs, 4)) { // 16
// Process ticks in the middle of the bar.
_val = (trade.GetChart().GetBarTime() +
(ChartTf::TfToSeconds(trade.Get<ENUM_TIMEFRAMES>(CHART_PARAM_TF)) / 2)) == TimeCurrent();
_res = _method > 0 ? _res & _val : _res | _val;
}
if (METHOD(_method_abs, 5)) { // 32
// Process bar open price ticks.
_val = last_tick.time < trade.GetChart().GetBarTime();
_res = _method > 0 ? _res & _val : _res | _val;
}
if (METHOD(_method_abs, 6)) { // 64
// Process every 10th of the bar.
_val = TimeCurrent() % (int)(ChartTf::TfToSeconds(trade.Get<ENUM_TIMEFRAMES>(CHART_PARAM_TF)) / 10) == 0;
_res = _method > 0 ? _res & _val : _res | _val;
}