forked from EA31337/EA31337-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strategy.mqh
1122 lines (1004 loc) · 30.1 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-2020, 31337 Investments 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
// Includes.
#include "Dict.mqh"
#include "Indicator.mqh"
#include "Object.mqh"
#include "String.mqh"
#include "Trade.mqh"
// Defines.
#ifndef __noinput__
#define INPUT extern
#else
#define INPUT static
#endif
// Enums.
// EA actions.
enum ENUM_STRATEGY_ACTION {
STRAT_ACTION_DISABLE = 0, // Disables Strategy.
STRAT_ACTION_ENABLE, // Enables Strategy.
STRAT_ACTION_SUSPEND, // Suspend Strategy.
STRAT_ACTION_UNSUSPEND, // Unsuspend Strategy.
FINAL_STRATEGY_ACTION_ENTRY
};
// EA conditions.
enum ENUM_STRATEGY_CONDITION {
STRAT_COND_IS_ENABLED = 1, // When Strategy is enabled.
STRAT_COND_IS_SUSPENDED, // When Strategy is suspended.
FINAL_STRATEGY_CONDITION_ENTRY
};
/**
* Implements strategy class.
*/
class Strategy;
struct StgParams {
// Strategy config parameters.
bool is_enabled; // State of the strategy (whether enabled or not).
bool is_suspended; // State of the strategy (whether suspended or not)
bool is_boosted; // State of the boost feature (to increase lot size).
long id; // Identification number of the strategy.
unsigned long magic_no; // Magic number of the strategy.
double weight; // Weight of the strategy.
int signal_open_method; // Signal open method.
double signal_open_level; // Signal open level.
int signal_open_filter; // Signal open filter method.
int signal_open_boost; // Signal open boost method (for lot size increase).
int signal_close_method; // Signal close method.
double signal_close_level; // Signal close level.
int price_limit_method; // Price limit method.
double price_limit_level; // Price limit level.
double lot_size; // Lot size to trade.
double lot_size_factor; // Lot size multiplier factor.
double max_risk; // Maximum risk to take (1.0 = normal, 2.0 = 2x).
double max_spread; // Maximum spread to trade (in pips).
int tp_max; // Hard limit on maximum take profit (in pips).
int sl_max; // Hard limit on maximum stop loss (in pips).
datetime refresh_time; // Order refresh frequency (in sec).
Chart *chart; // Pointer to Chart class.
Ref<Log> logger; // Reference to Log object.
Trade *trade; // Pointer to Trade class.
Indicator *data; // Pointer to Indicator class.
Strategy *sl, *tp; // Pointers to Strategy class (stop-loss and profit-take).
// Constructor.
StgParams(Trade *_trade = NULL, Indicator *_data = NULL, Strategy *_sl = NULL, Strategy *_tp = NULL) :
trade(_trade),
chart(Object::IsValid(_trade) ? _trade.Chart() : NULL),
data(_data),
is_enabled(true),
is_suspended(false),
is_boosted(true),
magic_no(rand()),
weight(0),
signal_open_method(0),
signal_open_level(0),
signal_open_filter(0),
signal_open_boost(0),
signal_close_method(0),
signal_close_level(0),
price_limit_method(0),
price_limit_level(0),
lot_size(Object::IsValid(chart) ? chart.GetVolumeMin() : 0),
lot_size_factor(1.0),
max_risk(1.0),
max_spread(0.0),
tp_max(0),
sl_max(0),
refresh_time(0),
logger(new Log)
{}
// Deconstructor.
~StgParams() {}
// Struct methods.
// Getters.
bool IsBoosted() { return is_boosted; }
bool IsEnabled() { return is_enabled; }
bool IsSuspended() { return is_suspended; }
// Setters.
void SetId(long _id) { id = _id; }
void SetMagicNo(unsigned long _mn) { magic_no = _mn; }
void SetTf(ENUM_TIMEFRAMES _tf, string _symbol = NULL) {
trade = new Trade(_tf, _symbol);
}
void SetSignals(int _open_method, double _open_level, int _open_filter, int _open_boost, int _close_method, double _close_level)
{
signal_open_method = _open_method;
signal_open_level = _open_level;
signal_open_filter = _open_filter;
signal_open_boost = _open_boost;
signal_close_method = _close_method;
signal_close_level = _close_level;
}
void SetPriceLimits(int _method, double _level) {
price_limit_method = _method;
price_limit_level = _level;
}
void SetMaxSpread(double _spread) {
max_spread = _spread;
}
void SetMaxRisk(double _risk) {
max_risk = _risk;
}
void Enabled(bool _is_enabled) { is_enabled = _is_enabled; };
void Suspended(bool _is_suspended) { is_suspended = _is_suspended; };
void Boost(bool _is_boosted) { is_boosted = _is_boosted; };
void DeleteObjects() {
Object::Delete(data);
Object::Delete(sl);
Object::Delete(tp);
Object::Delete(chart);
Object::Delete(trade);
}
// Printers.
string ToString() {
return StringFormat("Enabled:%s;Suspended:%s;Boosted:%s;Id:%d,MagicNo:%d;Weight:%.2f;" +
"SOM:%d,SOL:%.2f;" +
"SCM:%d,SCL:%.2f;" +
"PLM:%d,PLL:%.2f;" +
"LS:%.2f(Factor:%.2f);MS:%.2f;",
// @todo: "Data:%s;SL/TP-Strategy:%s/%s",
is_enabled ? "Yes" : "No",
is_suspended ? "Yes" : "No",
is_boosted ? "Yes" : "No",
id, magic_no, weight,
signal_open_method, signal_open_level,
signal_close_method, signal_close_level,
price_limit_method, price_limit_level,
lot_size, lot_size_factor, max_spread
// @todo: data, sl, tp
);
}
};
// Defines struct for individual strategy's param values.
struct Stg_Params {
string symbol;
ENUM_TIMEFRAMES tf;
Stg_Params() : symbol(_Symbol), tf((ENUM_TIMEFRAMES) _Period) {}
};
// Defines struct to store results for signal processing.
struct StgProcessResult {
unsigned int pos_closed; // Number of positions closed.
unsigned int pos_opened; // Number of positions opened.
unsigned int pos_updated; // Number of positions updated.
unsigned int stops_invalid_sl; // Number of invalid stop-loss values.
unsigned int stops_invalid_tp; // Number of invalid take-profit values;
unsigned int last_error; // Last error code.
StgProcessResult() { Reset(); }
void ProcessLastError() {
last_error = fmax(last_error, Terminal::GetLastError());
}
void Reset() {
pos_closed = pos_opened = pos_updated = stops_invalid_sl = stops_invalid_tp = 0;
last_error = ERR_NO_ERROR;
}
string ToString() {
return StringFormat("%d,%d,%d,%d,%d,%d", pos_closed, pos_opened, pos_updated, stops_invalid_sl, stops_invalid_tp, last_error);
}
};
class Strategy : public Object {
// Enums.
enum ENUM_OPEN_METHOD {
OPEN_METHOD1 = 1, // Method #1.
OPEN_METHOD2 = 2, // Method #2.
OPEN_METHOD3 = 4, // Method #3.
OPEN_METHOD4 = 8, // Method #4.
OPEN_METHOD5 = 16, // Method #5.
OPEN_METHOD6 = 32, // Method #6.
OPEN_METHOD7 = 64, // Method #7.
OPEN_METHOD8 = 128, // Method #8.
OPEN_METHOD9 = 256, // Method #9.
OPEN_METHOD10 = 512, // Method #10.
OPEN_METHOD11 = 1024, // Method #11.
OPEN_METHOD12 = 2048 // Method #12.
};
enum ENUM_STRATEGY_STATS_PERIOD {
EA_STATS_DAILY,
EA_STATS_WEEKLY,
EA_STATS_MONTHLY,
EA_STATS_TOTAL,
FINAL_ENUM_STRATEGY_STATS_PERIOD
};
// Structs.
protected:
Dict<string, double> *ddata;
Dict<string, int> *idata;
Dict<int, int> *iidata;
StgParams sparams;
StgProcessResult sresult;
private:
// Strategy statistics.
struct StgStats {
uint orders_open; // Number of current opened orders.
uint errors; // Count reported errors.
} stats;
// Strategy statistics per period.
struct StgStatsPeriod {
// Statistics variables.
uint orders_total; // Number of total opened orders.
uint orders_won; // Number of total won orders.
uint orders_lost; // Number of total lost orders.
double profit_factor; // Profit factor.
double avg_spread; // Average spread.
double net_profit; // Total net profit.
double gross_profit; // Total gross profit.
double gross_loss; // Total gross profit.
} 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.
// Date time variables.
// Includes.
// Class variables.
public:
/* Special methods */
/**
* Class constructor.
*/
Strategy(const StgParams &_sparams, string _name = "")
:
ddata(new Dict<string, double>),
idata(new Dict<string, int>),
iidata(new Dict<int, int>)
{
// Assign struct.
// We don't want objects which were instantiated by default.
sparams.DeleteObjects();
sparams = _sparams;
// Initialize variables.
name = _name;
// Link log instances.
Logger().Link(sparams.trade.Logger());
// Statistics variables.
UpdateOrderStats(EA_STATS_DAILY);
UpdateOrderStats(EA_STATS_WEEKLY);
UpdateOrderStats(EA_STATS_MONTHLY);
UpdateOrderStats(EA_STATS_TOTAL);
}
/**
* Class copy constructor.
*/
Strategy(const Strategy &_strat) {
// @todo
sparams = _strat.GetParams();
// ...
}
/**
* Class deconstructor.
*/
~Strategy() {
sparams.DeleteObjects();
Object::Delete(ddata);
Object::Delete(idata);
Object::Delete(iidata);
}
/* Processing methods */
/**
* Process strategy's signals.
*
* Call this method for every new bar.
*
* @return
* Returns StgProcessResult struct.
*/
StgProcessResult ProcessSignals() {
double _boost_factor = 1.0;
if (SignalOpen(ORDER_TYPE_BUY, sparams.signal_open_method, sparams.signal_open_level)
&& SignalOpenFilter(ORDER_TYPE_BUY, sparams.signal_open_filter)) {
_boost_factor = sparams.IsBoosted() ? SignalOpenBoost(ORDER_TYPE_BUY, sparams.signal_open_boost) : GetLotSize();
if (OrderOpen(ORDER_TYPE_BUY, _boost_factor, GetOrderOpenComment("SignalOpen"))) {
sresult.pos_opened++;
}
}
sresult.ProcessLastError();
if (SignalOpen(ORDER_TYPE_SELL, sparams.signal_open_method, sparams.signal_open_level)
&& SignalOpenFilter(ORDER_TYPE_SELL, sparams.signal_open_filter)) {
_boost_factor = sparams.IsBoosted() ? SignalOpenBoost(ORDER_TYPE_SELL, sparams.signal_open_boost) : GetLotSize();
if (OrderOpen(ORDER_TYPE_SELL, _boost_factor, GetOrderOpenComment("SignalOpen"))) {
sresult.pos_opened++;
}
}
sresult.ProcessLastError();
if (SignalClose(ORDER_TYPE_BUY, sparams.signal_close_method, sparams.signal_close_level) && Trade().GetOrdersOpened() > 0) {
if (Trade().OrdersCloseViaCmd(ORDER_TYPE_BUY, GetOrderCloseComment("SignalClose")) > 0) {
sresult.pos_closed++;
}
}
sresult.ProcessLastError();
if (SignalClose(ORDER_TYPE_SELL, sparams.signal_close_method, sparams.signal_close_level) && Trade().GetOrdersOpened() > 0) {
if (Trade().OrdersCloseViaCmd(ORDER_TYPE_SELL, GetOrderCloseComment("SignalClose")) > 0) {
sresult.pos_closed++;
}
}
sresult.ProcessLastError();
return sresult;
}
/**
* Process strategy's orders.
*
* Call this method for every new bar.
*
* @return
* Returns StgProcessResult struct.
*/
StgProcessResult ProcessOrders() {
bool sl_valid, tp_valid;
double sl_new, tp_new;
Collection<Order> *_orders = this.Trade().Orders();
Order *_order;
for (_order = _orders.GetFirstItem(); Object::IsValid(_order); _order = _orders.GetNextItem()) {
sl_new = PriceLimit(_order.OrderType(), ORDER_TYPE_SL, sparams.price_limit_method, sparams.price_limit_level);
tp_new = PriceLimit(_order.OrderType(), ORDER_TYPE_TP, sparams.price_limit_method, sparams.price_limit_level);
sl_new = Market().NormalizeSLTP(sl_new, _order.GetRequest().type, ORDER_TYPE_SL);
tp_new = Market().NormalizeSLTP(tp_new, _order.GetRequest().type, ORDER_TYPE_TP);
sl_valid = Trade().ValidSL(sl_new, _order.GetRequest().type);
tp_valid = Trade().ValidTP(tp_new, _order.GetRequest().type);
_order.OrderModify(
sl_valid && sl_new > 0 ? Market().NormalizePrice(sl_new) : _order.GetStopLoss(),
tp_valid && tp_new > 0 ? Market().NormalizePrice(tp_new) : _order.GetTakeProfit()
);
sresult.stops_invalid_sl += (int) sl_valid;
sresult.stops_invalid_tp += (int) tp_valid;
}
sresult.ProcessLastError();
return sresult;
}
/**
* Process strategy's signals and orders.
*
* Call this method for every new bar.
*
* @return
* Returns StgProcessResult struct.
*/
StgProcessResult Process() {
sresult.last_error = ERR_NO_ERROR;
ProcessSignals();
ProcessOrders();
return sresult;
}
/* State checkers */
/**
* Validate strategy's timeframe and parameters.
*
* @return
* Returns true when strategy params are valid, otherwise false.
*/
bool IsValid() {
return Object::IsValid(sparams.trade) && Object::IsValid(sparams.chart) && sparams.chart.IsValidTf();
}
/**
* Check state of the strategy.
*/
bool IsEnabled() {
return sparams.IsEnabled();
}
/**
* Check suspension status of the strategy.
*/
bool IsSuspended() {
return sparams.IsSuspended();
}
/**
* Check state of the strategy.
*/
bool IsBoostEnabled() {
return sparams.IsBoosted();
}
/* Class getters */
/**
* Returns strategy's market class.
*/
Market *Market() {
return sparams.trade.Market();
}
/**
* Returns strategy's indicator data class.
*/
Indicator *Data() {
return sparams.data;
}
/**
* Returns strategy's log class.
*/
Log *Logger() {
return sparams.logger.Ptr();
}
/**
* Returns handler to the strategy's trading class.
*/
Trade *Trade() {
return sparams.trade;
}
/**
* Returns access to Chart information.
*/
Chart *Chart() {
return sparams.chart;
}
/**
* Returns handler to the strategy's indicator class.
*/
Indicator *Indicator() {
return sparams.data;
}
/* Struct getters */
/**
* Gets result of the last signal processing.
*/
StgProcessResult GetProcessResult() {
return sresult;
}
/* Getters */
/**
* Get strategy's name.
*/
string GetName() {
return name;
}
/**
* Get strategy's ID.
*/
virtual long GetId() {
return sparams.id;
}
/**
* Get strategy's weight.
*
* Note: Implementation of inherited method.
*/
virtual double GetWeight() {
return sparams.weight;
}
/**
* Get strategy's magic number.
*/
unsigned long GetMagicNo() {
return sparams.magic_no;
}
/**
* Get strategy's timeframe.
*/
ENUM_TIMEFRAMES GetTf() {
return sparams.chart.GetTf();
}
/**
* 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 limit method.
*/
int GetPriceLimitMethod() {
return sparams.signal_close_method;
}
/**
* Get strategy's price limit level.
*/
double GetPriceLimitLevel() {
return sparams.signal_close_level;
}
/**
* Get strategy's order open comment.
*/
string GetOrderOpenComment(string _prefix = "", string _suffix = "") {
return StringFormat("%s%s[%s];s:%gp%s",
_prefix != "" ? _prefix + ": " : "",
name, sparams.chart.TfToString(), GetCurrSpread(),
_suffix != "" ? "| " + _suffix : ""
);
}
/**
* Get strategy's order close comment.
*/
string GetOrderCloseComment(string _prefix = "", string _suffix = "") {
return StringFormat("%s%s[%s];s:%gp%s",
_prefix != "" ? _prefix + ": " : "",
name, sparams.chart.TfToString(), GetCurrSpread(),
_suffix != "" ? "| " + _suffix : ""
);
}
/**
* Get strategy's lot size.
*/
double GetLotSize() {
return sparams.lot_size * sparams.lot_size_factor;
}
/**
* Get strategy's lot size factor.
*/
double GetLotSizeFactor() {
return sparams.lot_size_factor;
}
/**
* Get strategy's max risk.
*/
double GetMaxRisk() {
return sparams.max_risk;
}
/**
* Get strategy's max spread.
*/
double GetMaxSpread() {
return sparams.max_spread;
}
/**
* 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 data.
*/
Dict<string, double> *GetDataSD() {
return ddata;
}
Dict<string, int> *GetDataSI() {
return idata;
}
Dict<int, int> *GetDataII() {
return iidata;
}
/* 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 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 weight.
*/
void SetWeight(double _weight) {
sparams.weight = _weight;
}
/**
* Sets strategy's magic number.
*/
void SetMagicNo(ulong _magic_no) {
sparams.magic_no = _magic_no;
}
/**
* Sets strategy's signal open method.
*/
void SetSignalOpenMethod(int _method) {
sparams.signal_open_method = _method;
}
/**
* Sets strategy's signal open level.
*/
void SetSignalOpenLevel(double _level) {
sparams.signal_open_level = _level;
}
/**
* Sets strategy's signal close method.
*/
void SetSignalCloseMethod(int _method) {
sparams.signal_close_method = _method;
}
/**
* Sets strategy's signal close level.
*/
void SetSignalCloseLevel(double _level) {
sparams.signal_close_level = _level;
}
/**
* Sets strategy's price limit method.
*/
void SetPriceLimitMethod(int _method) {
sparams.signal_close_method = _method;
}
/**
* Sets strategy's price limit level.
*/
void SetPriceLimitLevel(double _level) {
sparams.signal_close_level = _level;
}
/**
* Enable/disable the strategy.
*/
void Enabled(bool _enable = true) {
sparams.Enabled(_enable);
}
/**
* Suspend the strategy.
*/
void Suspended(bool _suspended = true) {
sparams.Suspended(_suspended);
}
/**
* Sets initial data.
*/
void SetData(Dict<string, double> *_ddata) {
delete ddata;
ddata = _ddata;
}
void SetData(Dict<string, int> *_idata) {
delete idata;
idata = _idata;
}
void SetData(Dict<int, int> *_iidata) {
delete iidata;
iidata = _iidata;
}
/* 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.
*/
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 (Market().GetSymbol() == Order::OrderSymbol() && sparams.magic_no == 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 sparams.chart.GetSpreadInPips();
}
/**
* Convert timeframe constant to index value.
*/
uint TfToIndex(ENUM_TIMEFRAMES _tf) {
return Chart::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 (!sparams.chart.IsValidTf()) {
Logger().Warning(StringFormat("Could not initialize %s since %s timeframe is not active!", GetName(), sparams.chart.TfToString()), __FUNCTION__ + ": ");
return false;
}
return true;
}
/* Orders methods */
/**
* Open an order.
*/
bool OrderOpen(ENUM_ORDER_TYPE _cmd, double _lot_size = 0, string _comment = "") {
MqlTradeRequest _request = {0};
_request.action = TRADE_ACTION_DEAL;
_request.comment = _comment;
_request.deviation = 10;
_request.magic = GetMagicNo();
_request.price = Market().GetOpenOffer(_cmd);
_request.symbol = Market().GetSymbol();
_request.type = _cmd;
_request.type_filling = Order::GetOrderFilling(_request.symbol);
_request.volume = _lot_size > 0 ? _lot_size : GetLotSize();
ResetLastError();
Order *_order = new Order(_request);
return Trade().OrderAdd(_order);
}
/* Conditions and actions */
/**
* Checks for Strategy condition.
*
* @param ENUM_STRATEGY_CONDITION _cond
* Strategy condition.
* @return
* Returns true when the condition is met.
*/
bool Condition(ENUM_STRATEGY_CONDITION _cond) {
switch (_cond) {
case STRAT_COND_IS_ENABLED:
return sparams.IsEnabled();
case STRAT_COND_IS_SUSPENDED:
return sparams.IsSuspended();
default: