forked from EA31337/EA31337-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strategy.mqh
559 lines (495 loc) · 15 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
//+------------------------------------------------------------------+
//| EA31337 framework |
//| Copyright 2016-2018, 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 <https://www.gnu.org/licenses/>.
*/
// Properties.
#property strict
// Includes.
#include "Indicator.mqh"
#include "String.mqh"
#include "Trade.mqh"
/**
* Base class for strategy features.
*/
#ifndef STRATEGY_MQH
#define STRATEGY_MQH
class Strategy {
protected:
// 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.
};
enum ENUM_STRATEGY_STATS_PERIOD {
EA_STATS_DAILY,
EA_STATS_WEEKLY,
EA_STATS_MONTHLY,
EA_STATS_TOTAL,
FINAL_ENUM_STRATEGY_STATS_PERIOD
};
// Structs.
struct StrategyParams {
// Strategy config parameters.
String *name; // Name of the strategy.
bool enabled; // State of the strategy (enabled or disabled).
bool suspended; // State of the strategy.
uint magic_no; // Magic number of the strategy.
double weight; // Weight of the strategy.
int signal_base_method; // Base signal method to check.
int signal_open_method; // Open signal method on top of base signal.
double signal_level; // Open signal level to consider the trade.
double lot_size; // Lot size to trade.
double lot_size_factor; // Lot size multiplier factor.
double spread_limit; // Spread limit to trade (in pips).
ENUM_INDICATOR_TYPE indi_tp_method; // Take profit method.
ENUM_INDICATOR_TYPE indi_sl_method; // Stop loss method.
uint tp_max; // Hard limit on maximum take profit (in pips).
uint sl_max; // Hard limit on maximum stop loss (in pips).
datetime refresh_time; // Order refresh frequency (in sec).
Indicator *data, *sl, *tp; // Pointer to Indicator class.
Trade *trade; // Pointer to Trade class.
};
// Strategy statistics.
struct StrategyStats {
uint orders_open; // Number of current opened orders.
uint errors; // Count reported errors.
};
// Strategy statistics per period.
struct StrategyStatsPeriod {
// 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.
};
/*
struct StrategyTradeRequest {
Strategy *strategy; // Strategy pointer.
ENUM_TRADE_REQUEST_ACTIONS action; // Trade operation type.
ulong magic; // Expert Advisor ID (magic number).
ulong order; // Order ticket.
String *symbol; // Trade symbol.
double volume; // Requested volume for a deal in lots.
double price; // Price.
double stoplimit; // StopLimit level of the order.
double sl; // Stop Loss level of the order.
double tp; // Take Profit level of the order.
ulong deviation; // Maximal possible deviation from the requested price.
ENUM_ORDER_TYPE type; // Order type.
ENUM_ORDER_TYPE_FILLING type_filling; // Order execution type.
ENUM_ORDER_TYPE_TIME type_time; // Order expiration type.
datetime expiration; // Order expiration time (for the orders of ORDER_TIME_SPECIFIED type.
String *comment; // Order comment.
ulong position; // Position ticket.
ulong position_by; // The ticket of an opposite position.
};
*/
// Struct variables.
StrategyParams params;
StrategyStats stats;
StrategyStatsPeriod stats_period[FINAL_ENUM_STRATEGY_STATS_PERIOD];
// 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:
/* State checkers */
/**
* Check state of the strategy.
*/
bool IsEnabled() {
return params.enabled;
}
/**
* Check suspension status of the strategy.
*/
bool IsSuspended() {
return params.suspended;
}
/* Class getters */
/**
* Returns strategy's market class.
*/
Market *MarketInfo() {
return params.trade.MarketInfo();
}
/**
* Returns strategy's indicator class.
*/
Indicator *IndicatorInfo() {
return params.data;
}
/**
* Returns strategy's log class.
*/
Log *Logger() {
return (Log *) params.trade.Logger();
}
/**
* Returns handler to the strategy's trading class.
*/
Trade *Trade() {
return params.trade;
}
/**
* Returns access to Chart information.
*/
Chart *ChartInfo() {
return params.trade.ChartInfo();
}
/* Variable getters */
/**
* Get strategy's name.
*/
string GetName() {
return params.name.ToString();
}
/**
* Get strategy's weight.
*/
double GetWeight() {
return params.weight;
}
/**
* Get strategy's magic number.
*/
ulong GetMagicNo() {
return params.magic_no;
}
/**
* Get strategy's timeframe.
*/
ENUM_TIMEFRAMES GetTimeframe() {
return ChartInfo().GetTf();
}
/**
* Get strategy's signal base method.
*/
int GetSignalBaseMethod() {
// @todo: Check overrides.
return params.signal_base_method;
}
/**
* Get strategy's signal open method.
*/
int GetSignalOpenMethod() {
// @todo: Check overrides.
return params.signal_open_method;
}
/**
* Get strategy's signal level.
*/
double GetSignalLevel() {
// @todo: Check overrides.
return params.signal_level;
}
/**
* Get strategy's take profit indicator method.
*/
ENUM_INDICATOR_TYPE GetTpMethod() {
return params.indi_tp_method;
}
/**
* Get strategy's stop loss indicator method.
*/
ENUM_INDICATOR_TYPE GetSlMethod() {
return params.indi_sl_method;
}
/**
* Get strategy's order comment.
*/
string GetOrderComment() {
return StringFormat("%s:%s; spread %gpips",
GetName(), GetTimeframe(), GetCurrSpread()
);
}
/**
* Get strategy's lot size.
*/
double GetLotSize() {
return params.lot_size;
}
/**
* Get strategy's lot size factor.
*/
double GetLotSizeFactor() {
return params.lot_size_factor;
}
/**
* Get strategy orders currently open.
*/
uint GetOrdersOpen() {
// UpdateOrderStats(EA_STATS_TOTAL);
// @todo
return stats.orders_open;
}
/* Statistics */
/**
* Get strategy orders total opened.
*/
uint GetOrdersTotal(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].orders_total;
}
/**
* Get strategy orders won.
*/
uint GetOrdersWon(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].orders_won;
}
/**
* Get strategy orders lost.
*/
uint GetOrdersLost(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].orders_lost;
}
/**
* Get strategy net profit.
*/
double GetNetProfit(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].net_profit;
}
/**
* Get strategy gross profit.
*/
double GetGrossProfit(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].gross_profit;
}
/**
* Get strategy gross loss.
*/
double GetGrossLoss(ENUM_STRATEGY_STATS_PERIOD _period = EA_STATS_TOTAL) {
UpdateOrderStats(_period);
return stats_period[_period].gross_loss;
}
/**
* Get 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 */
/**
* Enable the strategy.
*/
void Enable() {
params.enabled = true;
}
/**
* Disable the strategy.
*/
void Disable() {
params.enabled = false;
}
/**
* Resume suspended strategy.
*/
void Resume() {
params.suspended = false;
}
/**
* Suspend the strategy.
*/
void Suspend() {
params.suspended = true;
}
/* Calculations */
/**
* 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() - params.refresh_time) {
return; // Do not update too often.
}
uint _total = 0, _won = 0, _lost = 0, _open = 0;
double _gross_profit = 0, _gross_loss = 0, _net_profit = 0, _order_profit = 0;
datetime _order_datetime;
for (uint i = 0; i < Orders::OrdersTotal(); i++) {
// @todo: Select order.
if (MarketInfo().GetSymbol() == Order::OrderSymbol() && params.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 ChartInfo().GetSpreadInPips();
}
public:
/**
* Convert timeframe constant to index value.
*/
uint TfToIndex(ENUM_TIMEFRAMES _tf) {
return Chart::TfToIndex(_tf);
}
/**
* Class constructor.
*/
/*
bool Strategy(
string si_name,
int si_magic_no,
double si_lot_size,
double si_weight = 1.0,
int si_spread_limit = 10.0,
string si_symbol = NULL
) {
// Basic strategy variables.
s_name = si_name;
s_magic_no = si_magic_no;
s_weight = si_weight;
s_enabled = true;
s_suspended = false;
// Trading variables.
s_symbol = si_symbol != NULL ? si_symbol : Symbol();
s_lot_size = si_lot_size;
s_lot_factor = GetLotSizeFactor();
s_avg_spread = GetCurrSpread();
s_spread_limit = si_spread_limit;
s_pattern_method = 0;
s_open_level = 0.0;
s_tp_method = 0;
s_sl_method = 0;
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;
}
*/
/**
* Class constructor.
*/
/*
void Strategy(StrategyParams &_params) {
params = _params;
// Statistics variables.
UpdateOrderStats(EA_STATS_DAILY);
UpdateOrderStats(EA_STATS_WEEKLY);
UpdateOrderStats(EA_STATS_MONTHLY);
UpdateOrderStats(EA_STATS_TOTAL);
}
*/
/**
* Class deconstructor.
*/
void ~Strategy() {
// Remove class variables.
delete params.data;
delete params.sl;
delete params.tp;
delete params.trade;
}
/**
* Initialize strategy.
*/
bool Init() {
if (!ChartInfo().ValidTf()) {
Logger().Warning(StringFormat("Could not initialize %s since %s timeframe is not active!", GetName(), ChartInfo().TfToString()), __FUNCTION__ + ": ");
return false;
}
return true;
}
/* Virtual methods */
/**
* Checks strategy's trade signal.
*
* @param
* _cmd (int) - type of trade order command
* _base_method (int) - base signal method
* _open_method (int) - open signal method to use by using bitwise AND operation
* _level (double) - signal level to consider the signal
*/
virtual bool Signal(ENUM_ORDER_TYPE _cmd, int _base_method, int _open_method, double _level) = NULL;
virtual bool Signal(ENUM_ORDER_TYPE _cmd) = NULL;
};
#endif