-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
EA.mqh
1230 lines (1140 loc) · 46.3 KB
/
EA.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-2023, EA31337 Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
/*
* This file is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* @file
* Implements Expert Advisor class for writing custom trading robots.
*/
// Prevents processing this includes file for the second time.
#ifndef EA_MQH
#define EA_MQH
// Includes.
#include "Chart.mqh"
#include "Data.struct.h"
#include "Dict.mqh"
#include "DictObject.mqh"
#include "EA.enum.h"
#include "EA.struct.h"
#include "Market.mqh"
#include "Refs.struct.h"
#include "SerializerConverter.mqh"
#include "SerializerCsv.mqh"
#include "SerializerJson.mqh"
#include "SerializerSqlite.mqh"
#include "Strategy.mqh"
#include "SummaryReport.mqh"
#include "Task/TaskManager.h"
#include "Task/Taskable.h"
#include "Terminal.mqh"
#include "Trade.mqh"
#include "Trade/TradeSignal.h"
#include "Trade/TradeSignalManager.h"
class EA : public Taskable<DataParamEntry> {
protected:
// Class variables.
AccountMt *account;
DictStruct<long, Ref<Strategy>> strats;
Log logger;
Terminal terminal;
// Data variables.
BufferStruct<ChartEntry> data_chart;
BufferStruct<SymbolInfoEntry> data_symbol;
Dict<string, double> ddata; // Custom user data.
Dict<string, int> idata; // Custom user data.
DictObject<string, Trade> trade;
DictObject<ENUM_TIMEFRAMES, BufferStruct<IndicatorDataEntry>> data_indi;
DictObject<ENUM_TIMEFRAMES, BufferStruct<StgEntry>> data_stg;
EAParams eparams;
EAProcessResult eresults;
EAState estate;
TaskManager tasks;
TradeSignalManager tsm;
protected:
/* Protected methods */
/**
* Init code (called on constructor).
*/
void Init() { InitTask(); }
/**
* Process initial task (called on constructor).
*/
void InitTask() {
// Add and process init task.
TaskObject<EA, EA> _taskobj_init(eparams.GetStruct<TaskEntry>(STRUCT_ENUM(EAParams, EA_PARAM_STRUCT_TASK_ENTRY)),
THIS_PTR, THIS_PTR);
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_ON_INIT), true);
_taskobj_init.Process();
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_ON_INIT), false);
}
public:
/**
* Class constructor.
*/
EA(EAParams &_params) : account(new AccountMt) {
eparams = _params;
UpdateStateFlags();
// Add and process tasks.
Init();
// Initialize a trade instance for the current chart and symbol.
ChartParams _cparams((ENUM_TIMEFRAMES)_Period, _Symbol);
TradeParams _tparams(0, 1.0f, 0, eparams.Get<ENUM_LOG_LEVEL>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_LOG_LEVEL)));
Trade _trade(_tparams, _cparams);
trade.Set(_Symbol, _trade);
logger.Link(_trade.GetLogger());
logger.SetLevel(eparams.Get<ENUM_LOG_LEVEL>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_LOG_LEVEL)));
//_trade.GetLogger().SetLevel(eparams.Get<ENUM_LOG_LEVEL>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_LOG_LEVEL)));
}
/**
* Class deconstructor.
*/
~EA() {
// Process tasks on quit.
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_ON_QUIT), true);
ProcessTasks();
// Deinitialize classes.
Object::Delete(account);
}
/* Getters */
/**
* Gets EA state flag value.
*/
bool Get(STRUCT_ENUM(EAState, ENUM_EA_STATE_FLAGS) _prop) { return estate.Get(_prop); }
/**
* Gets EA parameter value.
*/
template <typename T>
T Get(STRUCT_ENUM(EAParams, ENUM_EA_PARAM_PROP) _param) {
return eparams.Get<T>(_param);
}
/**
* Gets EA state property value.
*/
template <typename T>
T Get(STRUCT_ENUM(EAState, ENUM_EA_STATE_PROP) _prop) {
return estate.Get<T>(_prop);
}
/**
* Gets a Trade's state value.
*/
template <typename T>
T Get(ENUM_TRADE_STATE _state, string _symbol = NULL) {
return trade.GetByKey(_symbol != NULL ? _symbol : _Symbol).Get<T>(_state);
}
/**
* Gets a strategy's signal entry.
*
* @param Strategy _strat
* Reference to strategy to get the signal from.
* @param bool _trade_allowed
* True if trade is allowed.
* @param int _shift
* Bar shift.
*
* @return
* Returns TradeSignalEntry struct.
*/
TradeSignalEntry GetStrategySignalEntry(Strategy *_strat, bool _trade_allowed = true, int _shift = 0) {
// float _bf = 1.0;
float _scl = _strat.Get<float>(STRAT_PARAM_SCL);
float _sol = _strat.Get<float>(STRAT_PARAM_SOL);
int _scfm = _strat.Get<int>(STRAT_PARAM_SCFM);
int _scft = _strat.Get<int>(STRAT_PARAM_SCFT);
int _scm = _strat.Get<int>(STRAT_PARAM_SCM);
int _sob = _strat.Get<int>(STRAT_PARAM_SOB);
int _sofm = _strat.Get<int>(STRAT_PARAM_SOFM);
int _soft = _strat.Get<int>(STRAT_PARAM_SOFT);
int _som = _strat.Get<int>(STRAT_PARAM_SOM);
int _ss = _shift >= 0 ? _shift : _strat.Get<int>(STRAT_PARAM_SHIFT);
unsigned int _signals = 0;
// sparams.Get<float>(STRAT_PARAM_WEIGHT));
if (_trade_allowed) {
// Process boost factor and lot size.
// sresult.SetBoostFactor(sparams.IsBoosted() ? SignalOpenBoost(ORDER_TYPE_BUY, _sob) : 1.0f);
// sresult.SetLotSize(sparams.GetLotSizeWithFactor());
// Process open signals when trade is allowed.
_signals |= _strat.SignalOpen(ORDER_TYPE_BUY, _som, _sol, _ss) ? SIGNAL_OPEN_BUY_MAIN : 0;
_signals |= !_strat.SignalOpenFilterMethod(ORDER_TYPE_BUY, _sofm) ? SIGNAL_OPEN_BUY_FILTER : 0;
_signals |= _strat.SignalOpen(ORDER_TYPE_SELL, _som, _sol, _ss) ? SIGNAL_OPEN_SELL_MAIN : 0;
_signals |= !_strat.SignalOpenFilterMethod(ORDER_TYPE_SELL, _sofm) ? SIGNAL_OPEN_SELL_FILTER : 0;
_signals |= !_strat.SignalOpenFilterTime(_soft) ? SIGNAL_OPEN_TIME_FILTER : 0;
}
// Process close signals.
_signals |= _strat.SignalClose(ORDER_TYPE_BUY, _scm, _scl, _ss) ? SIGNAL_CLOSE_BUY_MAIN : 0;
_signals |= !_strat.SignalCloseFilter(ORDER_TYPE_BUY, _scfm) ? SIGNAL_CLOSE_BUY_FILTER : 0;
_signals |= _strat.SignalClose(ORDER_TYPE_SELL, _scm, _scl, _ss) ? SIGNAL_CLOSE_SELL_MAIN : 0;
_signals |= !_strat.SignalCloseFilter(ORDER_TYPE_SELL, _scfm) ? SIGNAL_CLOSE_SELL_FILTER : 0;
_signals |= !_strat.SignalCloseFilterTime(_scft) ? SIGNAL_CLOSE_TIME_FILTER : 0;
TradeSignalEntry _sentry(_signals, _strat.Get<ENUM_TIMEFRAMES>(STRAT_PARAM_TF), _strat.Get<long>(STRAT_PARAM_ID));
_sentry.Set(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_STRENGTH), _strat.SignalOpen(_sofm, _sol, _ss));
_sentry.Set(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_TIME), ::TimeGMT());
return _sentry;
}
/**
* Gets EA's trade instance.
*/
Trade *GetTrade(string _symbol) { return trade.GetByKey(_symbol); }
/* Setters */
/**
* Sets an EA parameter value.
*/
template <typename T>
void Set(STRUCT_ENUM(EAParams, ENUM_EA_PARAM_PROP) _param, T _value) {
eparams.Set<T>(_param, _value);
}
/**
* Sets EA state flag value.
*/
void Set(STRUCT_ENUM(EAState, ENUM_EA_STATE_FLAGS) _prop, bool _value) { estate.Set(_prop, _value); }
/**
* Sets an strategy parameter value for all strategies.
*/
template <typename T>
void Set(ENUM_STRATEGY_PARAM _param, T _value) {
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
Strategy *_strat = iter.Value().Ptr();
_strat.Set<T>(_param, _value);
}
}
/**
* Sets a trade parameter value for all trade instances.
*/
template <typename T>
void Set(ENUM_TRADE_PARAM _param, T _value) {
for (DictObjectIterator<string, Trade> iter = trade.Begin(); iter.IsValid(); ++iter) {
Trade *_trade = iter.Value();
_trade.Set<T>(_param, _value);
}
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
Strategy *_strat = iter.Value().Ptr();
_strat.Set<T>(_param, _value);
}
}
/* Processing methods */
/**
* Process strategy signals.
*/
bool ProcessSignals(const MqlTick &_tick, unsigned int _sig_filter = 0, bool _trade_allowed = true) {
bool _result = true;
int _last_error = ERR_NO_ERROR;
ResetLastError();
for (DictObjectIterator<int, TradeSignal> _iter = tsm.GetIterSignalsActive(); _iter.IsValid(); ++_iter) {
bool _result_local = true;
TradeSignal *_signal = _iter.Value();
if (_signal.Get(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_FLAG_PROCESSED))) {
// Ignores already processed signals.
continue;
}
Trade *_trade = trade.GetByKey(_Symbol);
Strategy *_strat =
strats.GetByKey(_signal.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_MAGIC_ID))).Ptr();
_trade_allowed &= _trade.IsTradeAllowed();
if (_trade.Get<bool>(TRADE_STATE_ORDERS_ACTIVE)) {
float _sig_close = _signal.GetSignalClose();
string _comment_close =
_strat != NULL && _sig_close != 0.0f ? _strat.GetOrderCloseComment() : __FUNCTION_LINE__;
// Check if we should close the orders.
_trade_allowed &= _strat.GetTrade().IsTradeAllowed(_sig_close != 0.0f);
if (_sig_close != 0.0f && _trade_allowed) {
if (_sig_close >= 0.5f) {
// Close signal for buy order.
_trade.OrdersCloseViaProp2<ENUM_ORDER_PROPERTY_INTEGER, long>(
ORDER_MAGIC, _signal.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_MAGIC_ID)), ORDER_TYPE,
ORDER_TYPE_BUY, MATH_COND_EQ, ORDER_REASON_CLOSED_BY_SIGNAL, _comment_close);
// Buy orders closed.
_strat.OnOrderClose(ORDER_TYPE_BUY);
}
if (_sig_close <= -0.5f) {
// Close signal for sell order.
_trade.OrdersCloseViaProp2<ENUM_ORDER_PROPERTY_INTEGER, long>(
ORDER_MAGIC, _signal.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_MAGIC_ID)), ORDER_TYPE,
ORDER_TYPE_SELL, MATH_COND_EQ, ORDER_REASON_CLOSED_BY_SIGNAL, _comment_close);
// Sell orders closed.
_strat.OnOrderClose(ORDER_TYPE_SELL);
}
}
}
_trade_allowed &= !_strat.IsSuspended();
if (_trade_allowed) {
float _sig_open = _signal.GetSignalOpen();
unsigned int _sig_f = eparams.Get<unsigned int>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_SIGNAL_FILTER));
string _comment_open = _strat != NULL && _sig_open != 0.0f ? _strat.GetOrderOpenComment() : __FUNCTION_LINE__;
// Open orders on signals.
_trade_allowed &= _strat.GetTrade().IsTradeAllowed(_sig_open != 0.0f);
if (_sig_open != 0.0f && _trade_allowed) {
if (_sig_open >= 0.5f) {
// Open signal for buy.
// When H1 or H4 signal filter is enabled, do not open minute-based orders on opposite or neutral signals.
if (GetSignalOpenFiltered(_signal, _sig_f) >= 0.5f) {
_strat.Set(TRADE_PARAM_ORDER_COMMENT, _comment_open);
// Buy order open.
_result_local &= TradeRequest(ORDER_TYPE_BUY, _Symbol, _strat);
if (_result_local && eparams.CheckSignalFilter(STRUCT_ENUM(EAParams, EA_PARAM_SIGNAL_FILTER_FIRST))) {
_signal.Set(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_FLAG_PROCESSED), true);
break;
}
} else {
// Signal filtered.
}
}
if (_sig_open <= -0.5f) {
// Open signal for sell.
// When H1 or H4 signal filter is enabled, do not open minute-based orders on opposite or neutral signals.
if (GetSignalOpenFiltered(_signal, _sig_f) <= -0.5f) {
_strat.Set(TRADE_PARAM_ORDER_COMMENT, _comment_open);
// Sell order open.
_result_local &= TradeRequest(ORDER_TYPE_SELL, _Symbol, _strat);
if (_result_local && eparams.CheckSignalFilter(STRUCT_ENUM(EAParams, EA_PARAM_SIGNAL_FILTER_FIRST))) {
_signal.Set(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_FLAG_PROCESSED), true);
break;
}
} else {
// Signal filtered.
}
}
}
if (_result_local) {
_signal.Set(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_FLAG_PROCESSED), true);
} else {
_last_error = GetLastError();
if (_last_error > 0) {
logger.Warning(StringFormat("Error: %d", _last_error), __FUNCTION_LINE__, _strat.GetName());
#ifdef __debug_ea__
Print(__FUNCTION_LINE__ + "(): " + SerializerConverter::FromObject(_signal).ToString<SerializerJson>());
#endif
ResetLastError();
}
if (_trade.Get<bool>(TRADE_STATE_MONEY_NOT_ENOUGH)) {
logger.Warning(StringFormat("Suspending strategy.", _last_error), __FUNCTION_LINE__, _strat.GetName());
_strat.Suspended(true);
}
}
}
_result &= _result_local;
}
_last_error = GetLastError();
if (_last_error > 0) {
logger.Warning(StringFormat("Processing signals failed! Code: %d", _last_error), __FUNCTION_LINE__);
}
// Refresh signals after processing.
tsm.Refresh();
return _result && _last_error == 0;
}
/**
* Process a trade request.
*
* @return
* Returns true on successful request.
*/
virtual bool TradeRequest(ENUM_ORDER_TYPE _cmd, string _symbol = NULL, Strategy *_strat = NULL) {
bool _result = false;
Trade *_etrade = trade.GetByKey(_symbol);
Trade *_strade = _strat.GetTrade();
// Prepare a request.
MqlTradeRequest _request = _etrade.GetTradeOpenRequest(_cmd);
_request.comment = _strat.GetOrderOpenComment();
_request.magic = _strat.Get<long>(STRAT_PARAM_ID);
_request.price = SymbolInfoStatic::GetOpenOffer(_symbol, _cmd);
_request.volume = fmax(_strat.Get<float>(STRAT_PARAM_LS), SymbolInfoStatic::GetVolumeMin(_symbol));
_request.volume = _etrade.NormalizeLots(_request.volume);
// Check strategy's trade states.
switch (_request.action) {
case TRADE_ACTION_DEAL:
if (!_etrade.IsTradeRecommended()) {
if (logger.GetLevel() > V_INFO) {
logger.Debug(
StringFormat("Trade not opened due to EA trading states (%d).", _strade.GetStates().GetStates()),
__FUNCTION_LINE__);
}
return _result;
} else if (!_strade.IsTradeRecommended()) {
if (logger.GetLevel() > V_INFO) {
logger.Debug(
StringFormat("Trade not opened due to strategy trading states (%d).", _strade.GetStates().GetStates()),
__FUNCTION_LINE__);
}
return _result;
}
break;
}
// Prepare an order parameters.
OrderParams _oparams;
_strat.OnOrderOpen(_oparams);
// Send the request.
_result = _etrade.RequestSend(_request, _oparams);
if (!_result) { // && _strade.IsTradeRecommended(
logger.Debug(
StringFormat("Error while sending a trade request! Entry: %s",
SerializerConverter::FromObject(MqlTradeRequestProxy(_request)).ToString<SerializerJson>()),
__FUNCTION_LINE__, StringFormat("Code: %d, Msg: %s", _LastError, Terminal::GetErrorText(_LastError)));
if (_etrade.IsTradeRecommended() && _strade.IsTradeRecommended()) {
logger.Debug(
StringFormat("Error while sending a trade request! Entry: %s",
SerializerConverter::FromObject(MqlTradeRequestProxy(_request)).ToString<SerializerJson>()),
__FUNCTION_LINE__, StringFormat("Code: %d, Msg: %s", _LastError, Terminal::GetErrorText(_LastError)));
}
#ifdef __debug_ea__
Print(__FUNCTION_LINE__ + "(): " + SerializerConverter::FromObject(MqlTradeRequestProxy(_request)).ToString<SerializerJson>());
#endif
}
return _result;
}
/**
* Process strategy signals on tick event.
*
* Note: Call this method for every market tick.
*
* @return
* Returns struct with the processed results.
*/
virtual EAProcessResult ProcessTick() {
if (estate.IsEnabled()) {
MqlTick _tick = SymbolInfoStatic::GetTick(_Symbol);
eresults.Reset();
if (estate.IsActive()) {
ProcessPeriods();
// Process all enabled strategies and retrieve their signals.
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
Strategy *_strat = iter.Value().Ptr();
Trade *_trade = _strat.GetTrade();
if (_strat.IsEnabled()) {
if (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) >= DATETIME_MINUTE) {
// Process when new periods started.
_strat.OnPeriod(estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)));
_strat.ProcessTasks();
_trade.OnPeriod(estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)));
eresults.stg_processed_periods++;
}
if (_strat.TickFilter(_tick)) {
bool _can_trade = !_trade.HasState(TRADE_STATE_MODE_DISABLED);
_can_trade &= !_strat.IsSuspended();
TradeSignalEntry _sentry = GetStrategySignalEntry(_strat, _can_trade, _strat.Get<int>(STRAT_PARAM_SHIFT));
if (_sentry.Get<unsigned int>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_SIGNALS)) > 0) {
TradeSignal _signal(_sentry);
if (_signal.GetSignalClose() != _signal.GetSignalOpen()) {
tsm.SignalAdd(_signal); //, _tick.time);
}
StgProcessResult _strat_result = _strat.GetProcessResult();
eresults.last_error = fmax(eresults.last_error, _strat_result.last_error);
eresults.stg_errored += (int)_strat_result.last_error > ERR_NO_ERROR;
eresults.stg_processed++;
}
}
}
}
if (tsm.GetSignalsActive().Size() > 0 && tsm.IsReady()) {
// Process all strategies' signals and trigger trading orders.
ProcessSignals(_tick, eparams.Get<unsigned int>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_SIGNAL_FILTER)));
}
if (eresults.last_error > ERR_NO_ERROR) {
// On error, print logs.
logger.Flush();
}
if (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) >= DATETIME_MINUTE) {
// Process data, tasks and trades on new periods.
ProcessTrades();
}
}
estate.last_updated.Update();
if (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) >= DATETIME_MINUTE) {
// Process data and tasks on new periods.
ProcessData();
ProcessTasks();
}
}
return eresults;
}
/**
* Process data to store.
*/
void ProcessData() {
long _timestamp = estate.last_updated.GetEntry().GetTimestamp();
if (eparams.CheckFlagDataStore(EA_DATA_STORE_CHART)) {
ChartEntry _entry = Chart().GetEntry();
data_chart.Add(_entry, _entry.bar.ohlc.time);
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_INDICATOR)) {
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
Strategy *_strati = iter.Value().Ptr();
IndicatorData *_indi = _strati.GetIndicator();
if (_indi != NULL) {
ENUM_TIMEFRAMES _itf = _indi.GetParams().tf.GetTf();
IndicatorDataEntry _ientry = _indi.GetEntry();
if (!data_indi.KeyExists(_itf)) {
// Create new timeframe buffer if does not exist.
BufferStruct<IndicatorDataEntry> *_ide = new BufferStruct<IndicatorDataEntry>;
data_indi.Set(_itf, _ide);
}
// Save entry into data_indi.
data_indi[_itf].Add(_ientry);
}
}
}
/*
if (eparams.CheckFlagDataStore(EA_DATA_STORE_STRATEGY)) {
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
Strategy *_strat = iter.Value().Ptr();
StgEntry _sentry = _strat.GetEntry();
ENUM_TIMEFRAMES _stf = iter_tf.Key(); // @fixme
if (!data_stg.KeyExists(_stf)) {
// Create new timeframe buffer if does not exist.
BufferStruct<StgEntry> *_se = new BufferStruct<StgEntry>;
data_stg.Set(_stf, _se);
}
// Save data into data_stg.
data_stg[_stf].Add(_sentry);
}
}
*/
if (eparams.CheckFlagDataStore(EA_DATA_STORE_SYMBOL)) {
data_symbol.Add(SymbolInfo().GetEntryLast(), _timestamp);
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_TRADE)) {
// @todo
}
}
/**
* Checks for new starting periods.
*/
unsigned int ProcessPeriods() {
estate.Set<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS), estate.last_updated.GetStartedPeriods());
OnPeriod();
return estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS));
}
/**
* Export data.
*/
void DataExport(unsigned short _methods) {
long _timestamp = estate.last_updated.GetEntry().GetTimestamp();
int _serializer_flags = SERIALIZER_FLAG_SKIP_HIDDEN | SERIALIZER_FLAG_INCLUDE_DEFAULT |
SERIALIZER_FLAG_INCLUDE_DYNAMIC | SERIALIZER_FLAG_REUSE_STUB | SERIALIZER_FLAG_REUSE_OBJECT;
if (eparams.CheckFlagDataStore(EA_DATA_STORE_CHART)) {
string _key_chart = "Chart";
_key_chart += StringFormat("-%d-%d", data_chart.GetMin(), data_chart.GetMax());
SerializerConverter _stub = SerializerConverter::MakeStubObject<BufferStruct<ChartEntry>>(_serializer_flags);
SerializerConverter _obj = SerializerConverter::FromObject(data_chart, _serializer_flags);
if ((_methods & EA_DATA_EXPORT_CSV) != 0) {
_obj.ToFile<SerializerCsv>(_key_chart + ".csv", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_DB) != 0) {
SerializerSqlite::ConvertToFile(_obj, _key_chart + ".sqlite", "chart", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_JSON) != 0) {
_obj.ToFile<SerializerJson>(_key_chart + ".json", _serializer_flags, &_stub);
}
// Required because of SERIALIZER_FLAG_REUSE_STUB flag.
_stub.Clean();
// Required because of SERIALIZER_FLAG_REUSE_OBJECT flag.
_obj.Clean();
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_INDICATOR)) {
SerializerConverter _stub =
SerializerConverter::MakeStubObject<BufferStruct<IndicatorDataEntry>>(_serializer_flags);
/*
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
ENUM_TIMEFRAMES _itf = iter_tf.Key(); // @fixme
if (data_indi.KeyExists(_itf)) {
BufferStruct<IndicatorDataEntry> _indi_buff = data_indi.GetByKey(_itf);
SerializerConverter _obj = SerializerConverter::FromObject(_indi_buff, _serializer_flags);
for (DictStructIterator<long, Ref<Strategy>> iter = strats[_itf].Begin(); iter.IsValid(); ++iter) {
string _key_indi = "Indicator";
_key_indi += StringFormat("-%d-%d-%d", _itf, _indi_buff.GetMin(), _indi_buff.GetMax());
if ((_methods & EA_DATA_EXPORT_CSV) != 0) {
_obj.ToFile<SerializerCsv>(_key_indi + ".csv", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_DB) != 0) {
SerializerSqlite::ConvertToFile(_obj, _key_indi + ".sqlite", "indicator", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_JSON) != 0) {
_obj.ToFile<SerializerJson>(_key_indi + ".json", _serializer_flags, &_stub);
}
} // for
// Required because of SERIALIZER_FLAG_REUSE_OBJECT flag.
_obj.Clean();
} // if
}
*/
// Required because of SERIALIZER_FLAG_REUSE_STUB flag.
_stub.Clean();
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_STRATEGY)) {
SerializerConverter _stub = SerializerConverter::MakeStubObject<BufferStruct<StgEntry>>(_serializer_flags);
/* @fixme
for (DictStructIterator<long, Ref<Strategy>> iter = strats.Begin(); iter.IsValid(); ++iter) {
ENUM_TIMEFRAMES _stf = iter_tf.Key(); // @fixme
if (data_stg.KeyExists(_stf)) {
string _key_stg = StringFormat("Strategy-%d", _stf);
BufferStruct<StgEntry> _stg_buff = data_stg.GetByKey(_stf);
SerializerConverter _obj = SerializerConverter::FromObject(_stg_buff, _serializer_flags);
_key_stg += StringFormat("-%d-%d-%d", _stf, _stg_buff.GetMin(), _stg_buff.GetMax());
if ((_methods & EA_DATA_EXPORT_CSV) != 0) {
_obj.ToFile<SerializerCsv>(_key_stg + ".csv", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_DB) != 0) {
SerializerSqlite::ConvertToFile(_obj, _key_stg + ".sqlite", "strategy", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_JSON) != 0) {
_obj.ToFile<SerializerJson>(_key_stg + ".json", _serializer_flags, &_stub);
}
// Required because of SERIALIZER_FLAG_REUSE_OBJECT flag.
_obj.Clean();
}
}
*/
// Required because of SERIALIZER_FLAG_REUSE_STUB flag.
_stub.Clean();
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_SYMBOL)) {
SerializerConverter _stub = SerializerConverter::MakeStubObject<BufferStruct<SymbolInfoEntry>>(_serializer_flags);
SerializerConverter _obj = SerializerConverter::FromObject(data_symbol, _serializer_flags);
string _key_sym = "Symbol";
_key_sym += StringFormat("-%d-%d", data_symbol.GetMin(), data_symbol.GetMax());
if ((_methods & EA_DATA_EXPORT_CSV) != 0) {
_obj.ToFile<SerializerCsv>(_key_sym + ".csv", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_DB) != 0) {
SerializerSqlite::ConvertToFile(_obj, _key_sym + ".sqlite", "symbol", _serializer_flags, &_stub);
}
if ((_methods & EA_DATA_EXPORT_JSON) != 0) {
_obj.ToFile<SerializerJson>(_key_sym + ".json", _serializer_flags, &_stub);
}
// Required because of SERIALIZER_FLAG_REUSE_STUB flag.
_stub.Clean();
// Required because of SERIALIZER_FLAG_REUSE_OBJECT flag.
_obj.Clean();
}
if (eparams.CheckFlagDataStore(EA_DATA_STORE_TRADE)) {
string _key_trade = "Trade";
// _key_sym += StringFormat("-%d-%d", data_trade.GetMin(), data_trade.GetMax());
if ((_methods & EA_DATA_EXPORT_CSV) != 0) {
// @todo
// SerializerConverter _stub_trade =
// Serializer::MakeStubObject<BufferStruct<TradeEntry>>(SERIALIZER_FLAG_SKIP_HIDDEN);
// SerializerConverter::FromObject(data_trade, SERIALIZER_FLAG_SKIP_HIDDEN).ToFile<SerializerCsv>(_key + ".csv",
// SERIALIZER_FLAG_SKIP_HIDDEN, &_stub_trade);
}
if ((_methods & EA_DATA_EXPORT_DB) != 0) {
// @todo: Use Database class.
}
if ((_methods & EA_DATA_EXPORT_JSON) != 0) {
// @todo
// SerializerConverter _stub_trade =
// Serializer::MakeStubObject<BufferStruct<TradeEntry>>(SERIALIZER_FLAG_SKIP_HIDDEN);
// SerializerConverter::FromObject(data_trade, SERIALIZER_FLAG_SKIP_HIDDEN).ToFile<SerializerJson>(_key +
// ".json", SERIALIZER_FLAG_SKIP_HIDDEN, &_stub_trade);
}
}
}
/**
* Export data using default methods.
*/
void DataExport() { DataExport(eparams.Get<unsigned short>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_DATA_EXPORT))); }
/* Signal methods */
/**
* Returns signal open value after filtering.
*
* @return
* Returns positive for buy signal, negative for sell, otherwise 0 for neutral signal.
*/
float GetSignalOpenFiltered(TradeSignal &_signal, unsigned int _sf) {
bool _res_sig = false;
float _sig_open = _signal.GetSignalOpen();
ENUM_TIMEFRAMES _sig_tf = _signal.Get<ENUM_TIMEFRAMES>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_TF));
if (ChartTf::TfToHours(_sig_tf) < 1 && bool(_sf & STRUCT_ENUM(EAParams, EA_PARAM_SIGNAL_FILTER_OPEN_M_IF_H))) {
for (DictStructIterator<long, Ref<Strategy>> _iter = GetStrategies().Begin(); _iter.IsValid(); ++_iter) {
Strategy *_strat = _iter.Value().Ptr();
ENUM_TIMEFRAMES _stf = _strat.Get<ENUM_TIMEFRAMES>(STRAT_PARAM_TF);
if (ChartTf::TfToHours(_stf) >= 1) {
TradeSignal *_hsignal0 =
tsm.GetSignalByCid(_strat.Get<int>(STRAT_PARAM_ID), (int)_stf, (int)ChartStatic::iTime(_Symbol, _stf));
TradeSignal *_hsignal1 =
tsm.GetSignalByCid(_strat.Get<int>(STRAT_PARAM_ID), (int)_stf, (int)ChartStatic::iTime(_Symbol, _stf, 1));
TradeSignal *_hsignal2 =
tsm.GetSignalByCid(_strat.Get<int>(STRAT_PARAM_ID), (int)_stf, (int)ChartStatic::iTime(_Symbol, _stf, 2));
// Increase signal if confirmed by hourly signal.
if (_hsignal0 != NULL && _hsignal0.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_TIME)) > 0) {
_sig_open += ((_sig_open > 0) == (_hsignal0.GetSignalOpen() > 0)) ? 1.0f : -1.0f;
_sig_open -= ((_sig_open < 0) == (_hsignal0.GetSignalOpen() < 0)) ? 1.0f : -1.0f;
} else if (_hsignal1 != NULL &&
_hsignal1.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_TIME)) > 0) {
_sig_open += ((_sig_open > 0) == (_hsignal1.GetSignalOpen() > 0)) ? 0.5f : -0.5f;
_sig_open -= ((_sig_open < 0) == (_hsignal1.GetSignalOpen() < 0)) ? 0.5f : -0.5f;
} else if (_hsignal2 != NULL &&
_hsignal2.Get<long>(STRUCT_ENUM(TradeSignalEntry, TRADE_SIGNAL_PROP_TIME)) > 0) {
_sig_open += ((_sig_open > 0) == (_hsignal2.GetSignalOpen() > 0)) ? 0.2f : -0.2f;
_sig_open -= ((_sig_open < 0) == (_hsignal2.GetSignalOpen() < 0)) ? 0.2f : -0.2f;
} else {
// Decrease signal by 0.1 if no hourly signal is found.
_sig_open -= 0.1f;
}
}
}
}
return _sig_open;
}
/* Strategy methods */
/**
* Adds strategy to specific timeframe.
*
* @param
* _tf - timeframe to add the strategy.
* _magic_no - unique order identified
*
* @return
* Returns true if the strategy has been initialized correctly, otherwise false.
*/
template <typename SClass>
bool StrategyAdd(ENUM_TIMEFRAMES _tf, long _magic_no = 0, int _type = 0) {
bool _result = true;
_magic_no = _magic_no > 0 ? _magic_no : rand();
Ref<Strategy> _strat = ((SClass *)NULL).Init(_tf);
_strat.Ptr().Set<long>(STRAT_PARAM_ID, _magic_no);
_strat.Ptr().Set<long>(TRADE_PARAM_MAGIC_NO, _magic_no);
_strat.Ptr().Set<ENUM_LOG_LEVEL>(STRAT_PARAM_LOG_LEVEL,
eparams.Get<ENUM_LOG_LEVEL>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_LOG_LEVEL)));
_strat.Ptr().Set<ENUM_TIMEFRAMES>(STRAT_PARAM_TF, _tf);
_strat.Ptr().Set<int>(STRAT_PARAM_TYPE, _type);
_strat.Ptr().OnInit();
if (!strats.KeyExists(_magic_no)) {
_result &= strats.Set(_magic_no, _strat);
} else {
logger.Error("Strategy adding conflict!", __FUNCTION_LINE__);
DebugBreak();
}
OnStrategyAdd(_strat.Ptr());
return _result;
}
/**
* Adds strategy to multiple timeframes.
*
* @param
* _tfs - timeframes to add strategy (using bitwise operation).
* _sid - strategy ID
* _init_magic - initial order identified
*
* Note:
* Final magic number is going to be increased by timeframe index value.
*
* @see: ENUM_TIMEFRAMES_INDEX
*
* @return
* Returns true if all strategies has been initialized correctly, otherwise false.
*/
template <typename SClass>
bool StrategyAdd(unsigned int _tfs, long _init_magic = 0, int _type = 0) {
bool _result = true;
for (int _tfi = 0; _tfi < sizeof(int) * 8; ++_tfi) {
if ((_tfs & (1 << _tfi)) != 0) {
_result &= StrategyAdd<SClass>(ChartTf::IndexToTf((ENUM_TIMEFRAMES_INDEX)_tfi), _init_magic + _tfi, _type);
}
}
return _result;
}
/**
* Loads existing trades for the given strategy.
*/
bool StrategyLoadTrades(Strategy *_strat) {
bool _result = true;
Trade *_trade = trade.GetByKey(_Symbol);
// Load active trades.
_result &= _trade.OrdersLoadByMagic(_strat.Get<long>(STRAT_PARAM_ID));
// Load strategy-specific order parameters (e.g. conditions).
// This is a temporary workaround for GH-705.
// @todo: To move to Strategy class.
Ref<Order> _order;
for (DictStructIterator<long, Ref<Order>> iter = _trade.GetOrdersActive().Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order.IsSet() && _order.Ptr().IsOpen()) {
_strat.OnOrderLoad(_order.Ptr());
}
}
return _result;
}
/* Trade methods */
/**
* Process open trades.
*
* @return
* Returns true on success, otherwise false.
*/
bool ProcessTrades() {
bool _result = true;
ResetLastError();
for (DictObjectIterator<string, Trade> titer = trade.Begin(); titer.IsValid(); ++titer) {
Trade *_trade = titer.Value();
if (_trade.Get<bool>(TRADE_STATE_ORDERS_ACTIVE) && !_trade.Get<bool>(TRADE_STATE_MARKET_CLOSED)) {
for (DictStructIterator<long, Ref<Order>> oiter = _trade.GetOrdersActive().Begin(); oiter.IsValid(); ++oiter) {
bool _sl_valid = false, _tp_valid = false;
double _sl_new = 0, _tp_new = 0;
Order *_order = oiter.Value().Ptr();
if (!_order.ShouldUpdate()) {
continue;
}
_order.ProcessConditions();
if (_order.IsClosed()) {
_trade.OrderMoveToHistory(_order);
continue;
}
ENUM_ORDER_TYPE _otype = _order.Get<ENUM_ORDER_TYPE>(ORDER_TYPE);
Strategy *_strat = strats.GetByKey(_order.Get<unsigned long>(ORDER_MAGIC)).Ptr();
Strategy *_strat_sl = _strat.GetStratSl();
Strategy *_strat_tp = _strat.GetStratTp();
if (_strat_sl != NULL || _strat_tp != NULL) {
float _olots = _order.Get<float>(ORDER_VOLUME_CURRENT);
float _trisk = _trade.Get<float>(TRADE_PARAM_RISK_MARGIN);
if (_strat_sl != NULL) {
float _psl = _strat_sl.Get<float>(STRAT_PARAM_PSL);
float _sl_max = _trade.GetMaxSLTP(_otype, _olots, ORDER_TYPE_SL, _trisk);
int _psm = _strat_sl.Get<int>(STRAT_PARAM_PSM);
_sl_new = _strat_sl.PriceStop(_otype, ORDER_TYPE_SL, _psm, _psl);
_sl_new = _trade.GetSaferSLTP(_sl_new, _sl_max, _otype, ORDER_TYPE_SL);
_sl_new = _trade.NormalizeSL(_sl_new, _otype);
_sl_valid = _trade.IsValidOrderSL(_sl_new, _otype, _order.Get<double>(ORDER_SL), _psm > 0);
_sl_new = _sl_valid ? _sl_new : _order.Get<double>(ORDER_SL);
}
if (_strat_tp != NULL) {
float _ppl = _strat_tp.Get<float>(STRAT_PARAM_PPL);
float _tp_max = _trade.GetMaxSLTP(_otype, _olots, ORDER_TYPE_TP, _trisk);
int _ppm = _strat_tp.Get<int>(STRAT_PARAM_PPM);
_tp_new = _strat_tp.PriceStop(_otype, ORDER_TYPE_TP, _ppm, _ppl);
_tp_new = _trade.GetSaferSLTP(_tp_new, _tp_max, _otype, ORDER_TYPE_TP);
_tp_new = _trade.NormalizeTP(_tp_new, _otype);
_tp_valid = _trade.IsValidOrderTP(_tp_new, _otype, _order.Get<double>(ORDER_TP), _ppm > 0);
_tp_new = _tp_valid ? _tp_new : _order.Get<double>(ORDER_TP);
}
}
if (_sl_valid || _tp_valid) {
_result &= _order.OrderModify(_sl_new, _tp_new);
if (_result) {
_order.Set(ORDER_PROP_TIME_LAST_UPDATE, TimeCurrent());
} else {
_trade.UpdateStates(true);
}
}
}
}
}
return _result && _LastError == ERR_NO_ERROR;
}
/* Update methods */
/**
* Update EA state flags.
*/
void UpdateStateFlags() {
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_CONNECTED), GetTerminal().IsConnected());
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_LIBS_ALLOWED), GetTerminal().IsLibrariesAllowed());
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_OPTIMIZATION), GetTerminal().IsOptimization());
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_TESTING), GetTerminal().IsTesting());
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_TRADE_ALLOWED), GetTerminal().IsTradeAllowed());
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_VISUAL_MODE), GetTerminal().IsVisualMode());
}
/**
* Updates info on chart.
*/
bool UpdateInfoOnChart() {
bool _result = false;
if (eparams.Get<int>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_CHART_INFO_FREQ)) > 0) {
static datetime _last_update = 0;
if (_last_update + eparams.Get<int>(STRUCT_ENUM(EAParams, EA_PARAM_PROP_CHART_INFO_FREQ)) < TimeCurrent()) {
_last_update = TimeCurrent();
// @todo
_result = true;
}
}
return _result;
}
/**
* Updates strategy lot size.
*/
bool UpdateLotSize() {
bool _result = false;
if (eparams.CheckFlag(EA_PARAM_FLAG_LOTSIZE_AUTO)) {
// Auto calculate lot size for all strategies.
Trade *_trade = trade.GetByKey(_Symbol);
_result &= _trade.Run(TRADE_ACTION_CALC_LOT_SIZE);
Set(STRAT_PARAM_LS, _trade.Get<float>(TRADE_PARAM_LOT_SIZE));
}
return _result;
}
/* Tasks methods */
/**
* Add task.
*/
bool AddTask(TaskEntry &_tentry) {
bool _is_valid = _tentry.IsValid();
if (_is_valid) {
tasks.Add(new TaskObject<EA, EA>(_tentry, THIS_PTR, THIS_PTR));
}
return _is_valid;
}
/**
* Add task object.
*/
template <typename TA, typename TC>
bool AddTaskObject(TaskObject<TA, TC> *_tobj) {
return EA::tasks.Add<TA, TC>(_tobj);
}
/**
* Process tasks.
*/
void ProcessTasks() { tasks.Process(); }
/* Tasks */
/**
* Checks a condition.
*/
virtual bool Check(const TaskConditionEntry &_entry) {
bool _result = false;
switch (_entry.GetId()) {
case EA_COND_IS_ACTIVE:
return estate.IsActive();
case EA_COND_IS_ENABLED:
return estate.IsEnabled();
case EA_COND_IS_NOT_CONNECTED:
estate.Set(STRUCT_ENUM(EAState, EA_STATE_FLAG_CONNECTED), GetTerminal().IsConnected());
return !estate.IsConnected();
case EA_COND_ON_NEW_MINUTE: // On new minute.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_MINUTE) != 0;
case EA_COND_ON_NEW_HOUR: // On new hour.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_HOUR) != 0;
case EA_COND_ON_NEW_DAY: // On new day.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_DAY) != 0;
case EA_COND_ON_NEW_WEEK: // On new week.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_WEEK) != 0;
case EA_COND_ON_NEW_MONTH: // On new month.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_MONTH) != 0;
case EA_COND_ON_NEW_YEAR: // On new year.
return (estate.Get<unsigned int>(STRUCT_ENUM(EAState, EA_STATE_PROP_NEW_PERIODS)) & DATETIME_YEAR) != 0;
case EA_COND_ON_INIT:
return estate.IsOnInit();
case EA_COND_ON_QUIT:
return estate.IsOnQuit();
default:
GetLogger().Error(StringFormat("Invalid EA condition: %d!", _entry.GetId(), __FUNCTION_LINE__));
SetUserError(ERR_INVALID_PARAMETER);
break;
}
return _result;
}