-
Notifications
You must be signed in to change notification settings - Fork 2
/
yapon.mq4
6857 lines (6451 loc) · 336 KB
/
yapon.mq4
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 - multi-strategy advanced trading robot. |
//| Copyright 2016-2017, 31337 Investments Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| EA includes. |
//+------------------------------------------------------------------+
#include <EA31337\ea-mode.mqh>
#include <EA31337\ea-code-conf.mqh>
#include <EA31337\ea-defaults.mqh>
#include <EA31337\ea-expire.mqh>
#include <EA31337\ea-properties.mqh>
#include <EA31337\ea-enums.mqh>
#ifdef __advanced__
#ifdef __rider__
#include <EA31337\rider\ea-conf.mqh>
#else
#include <EA31337\advanced\ea-conf.mqh>
#endif
#else
#include <EA31337\lite\ea-conf.mqh>
#endif
//+------------------------------------------------------------------+
//| EA properties.
//+------------------------------------------------------------------+
#property version ea_version
#property description ea_name
#property description ea_desc
#property link ea_link
#property copyright ea_copy
#property icon "resources\\favicon.ico"
#property strict
//#property stacksize
//#property tester_file "trade_patterns.csv" // File with the data to be read by an Expert Advisor.
//#property tester_indicator "smoothed_ma.ex4" // File with a custom indicator specified in iCustom() as a variable.
//#property tester_library "MT4EA2DLL.dll" // Library file name from <terminal_data_folder>\MQL4\Libraries\ to be sent to a virtual server.
//+------------------------------------------------------------------+
//| Include public classes.
//+------------------------------------------------------------------+
// #include <EA31337-classes\Account.mqh>
#include <EA31337-classes\Array.mqh>
// #include <EA31337-classes\Chart.mqh>
#include <EA31337-classes\Convert.mqh>
#include <EA31337-classes\DateTime.mqh>
// #include <EA31337-classes\Draw.mqh>
#include <EA31337-classes\File.mqh>
#include <EA31337-classes\Indicator.mqh>
#include <EA31337-classes\Order.mqh>
#include <EA31337-classes\Orders.mqh>
#include <EA31337-classes\Market.mqh>
#include <EA31337-classes\MD5.mqh>
#include <EA31337-classes\Misc.mqh>
#include <EA31337-classes\Msg.mqh>
#include <EA31337-classes\Report.mqh>
#include <EA31337-classes\Stats.mqh>
//#include <EA31337-classes\Strategies.mqh>
#include <EA31337-classes\String.mqh>
#include <EA31337-classes\SummaryReport.mqh>
#include <EA31337-classes\Terminal.mqh>
#include <EA31337-classes\Tester.mqh>
#include <EA31337-classes\Tests.mqh>
#include <EA31337-classes\Ticks.mqh>
#include <EA31337-classes\Trade.mqh>
#ifdef __profiler__
#include <EA31337-classes\Profiler.mqh>
#endif
//#property tester_file "trade_patterns.csv" // file with the data to be read by an Expert Advisor
//+------------------------------------------------------------------+
//| User input variables.
//+------------------------------------------------------------------+
extern string __EA_Parameters__ = "-- Input EA parameters for " + ea_name + " v" + ea_version + " --"; // >>> EA31337 <<<
#ifdef __advanced__ // Include default input settings based on the mode.
#ifdef __rider__
#include <EA31337\rider\ea-input.mqh>
#else
#include <EA31337\advanced\ea-input.mqh>
#endif
#else
#include <EA31337\lite\ea-input.mqh>
#endif
/*
* Predefined constants:
* Ask (for buying) - The latest known seller's price (ask price) of the current symbol.
* Bid (for selling) - The latest known buyer's price (offer price, bid price) of the current symbol.
* Point - The current symbol point value in the quote currency.
* Digits - Number of digits after decimal point for the current symbol prices.
* Bars - Number of bars in the current chart.
*/
/*
* Notes:
* - __MQL4__ macro is defined when compiling *.mq4 file, __MQL5__ macro is defined when compiling *.mq5 one.
*/
//+------------------------------------------------------------------+
// Class variables.
Account *account;
Chart *chart;
Log *logger;
Market *market;
Stats *total_stats, *hourly_stats;
SummaryReport *summary_report; // For summary report.
Ticks *ticks; // For recording ticks.
Terminal *terminal;
Trade *trade;
// Market/session variables.
double pip_size, ea_lot_size;
double last_ask, last_bid;
uint order_freezelevel; // Order freeze level in points.
double curr_spread; // Broker current spread in pips.
double curr_trend; // Current trend.
double ea_risk_margin_per_order, ea_risk_margin_total; // Risk marigin in percent.
uint pts_per_pip; // Number points per pip.
int gmt_offset = 0; // Current difference between GMT time and the local computer time in seconds, taking into account switch to winter or summer time. Depends on the time settings of your computer.
// double total_sl, total_tp; // Total SL/TP points.
// Account variables.
string account_type;
double init_balance; // Initial account balance.
long init_spread; // Initial spread.
// State variables.
bool session_initiated = false;
bool session_active = false;
// Time-based variables.
// Bar time: initial, current and last one to check if bar has been changed since the last time.
datetime init_bar_time, curr_bar_time, last_bar_time = (int) EMPTY_VALUE;
datetime time_current = (int)EMPTY_VALUE;
int hour_of_day, day_of_week, day_of_month, day_of_year, month, year;
datetime last_order_time = 0, last_action_time = 0;
int last_history_check = 0; // Last ticket position processed.
datetime last_traded;
// Strategy variables.
int info[FINAL_STRATEGY_TYPE_ENTRY][FINAL_STRATEGY_INFO_ENTRY];
double conf[FINAL_STRATEGY_TYPE_ENTRY][FINAL_STRATEGY_VALUE_ENTRY], stats[FINAL_STRATEGY_TYPE_ENTRY][FINAL_STRATEGY_STAT_ENTRY];
int open_orders[FINAL_STRATEGY_TYPE_ENTRY], closed_orders[FINAL_STRATEGY_TYPE_ENTRY];
int signals[FINAL_STAT_PERIOD_TYPE_ENTRY][FINAL_STRATEGY_TYPE_ENTRY][FINAL_ENUM_TIMEFRAMES_INDEX][2]; // Count signals to buy and sell per period and strategy.
int tickets[200]; // List of tickets to process.
string sname[FINAL_STRATEGY_TYPE_ENTRY];
int worse_strategy[FINAL_STAT_PERIOD_TYPE_ENTRY], best_strategy[FINAL_ENUM_TIMEFRAMES_INDEX];
// EA variables.
bool ea_active = false; bool ea_expired = false;
double ea_risk_ratio; string rr_text; // Vars for calculation risk ratio.
double ea_margin_risk_level[3]; // For margin risk (all/buy/sell);
uint max_orders = 10, daily_orders; // Maximum orders available to open.
uint max_order_slippage; // Maximum price slippage for buy or sell orders (in points)
int err_code; // Error code.
string last_err, last_msg, last_debug, last_trace;
double last_pip_change; // Last tick change in pips.
double last_close_profit = EMPTY;
// int last_trail_update = 0, last_indicators_update = 0, last_stats_update = 0;
int todo_queue[100][8];
datetime last_queue_process = 0;
uint total_orders = 0; // Number of total orders currently open.
double daily[FINAL_VALUE_TYPE_ENTRY], weekly[FINAL_VALUE_TYPE_ENTRY], monthly[FINAL_VALUE_TYPE_ENTRY];
double hourly_profit[367][24]; // Keep track of hourly profit.
// Used for writing the report file.
string log[];
// Condition and actions.
int acc_conditions[30][3];
string last_cname;
// Order queue.
long order_queue[100][FINAL_ORDER_QUEUE_ENTRY];
// Indicator variables.
double iac[H1][FINAL_ENUM_INDICATOR_INDEX];
double ad[H1][FINAL_ENUM_INDICATOR_INDEX];
double adx[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_ADX_ENTRY];
double alligator[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_ALLIGATOR_ENTRY];
double atr[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_MA_ENTRY];
double awesome[H1][FINAL_ENUM_INDICATOR_INDEX];
double bands[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_BANDS_ENTRY];
double bwmfi[H1][FINAL_ENUM_INDICATOR_INDEX];
double bpower[H1][FINAL_ENUM_INDICATOR_INDEX][ORDER_TYPE_SELL+1];
double cci[H1][FINAL_ENUM_INDICATOR_INDEX];
double demarker[H1][FINAL_ENUM_INDICATOR_INDEX];
double envelopes[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_LINE_ENTRY];
double iforce[H1][FINAL_ENUM_INDICATOR_INDEX];
double fractals[H4][FINAL_ENUM_INDICATOR_INDEX][FINAL_LINE_ENTRY];
double gator[H1][FINAL_ENUM_INDICATOR_INDEX][LIPS+1];
double ichimoku[H1][FINAL_ENUM_INDICATOR_INDEX][CHIKOUSPAN_LINE+1];
double ma_fast[H1][FINAL_ENUM_INDICATOR_INDEX], ma_medium[H1][FINAL_ENUM_INDICATOR_INDEX], ma_slow[H1][FINAL_ENUM_INDICATOR_INDEX];
double macd[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_SLINE_ENTRY];
double mfi[H1][FINAL_ENUM_INDICATOR_INDEX];
double momentum[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_MA_ENTRY];
double obv[H1][FINAL_ENUM_INDICATOR_INDEX];
double osma[H1][FINAL_ENUM_INDICATOR_INDEX];
double rsi[H1][FINAL_ENUM_INDICATOR_INDEX], rsi_stats[H1][3];
double rvi[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_SLINE_ENTRY];
double sar[H1][FINAL_ENUM_INDICATOR_INDEX]; int sar_week[H1][7][2];
double stddev[H1][FINAL_ENUM_INDICATOR_INDEX];
double stochastic[H1][FINAL_ENUM_INDICATOR_INDEX][FINAL_SLINE_ENTRY];
double wpr[H1][FINAL_ENUM_INDICATOR_INDEX];
double zigzag[H1][FINAL_ENUM_INDICATOR_INDEX];
/*
* TODO:
* - add trailing stops/profit for support/resistence,
* - daily higher highs and lower lows,
* - check risky dates and times,
* - check for risky patterns,
* - implement condition to close all strategy orders: when to trade, skip the day or week, etc.
* - implement SendFTP,
* - implement SendNotification,
* - send daily, weekly reports (SendMail),
* - check TesterStatistics(),
* - check ResourceCreate/ResourceSave to store dynamic parameters
* - consider to use Donchian Channel (ihighest/ilowest) for detecting s/r levels
* - convert `ma_fast`, `ma_medium`, `ma_slow` into one `ma` variable.
* - add RSI threshold param
* - trend calculated based on RSI
* - calculate support and resistance levels
* - calculate pivot levels
* - action to close the order after X hours when all orders of strategy are profitable
* - strategy flags: PP, S1-S3, R1-R3, trend
*/
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick() {
//#ifdef __trace__ PrintFormat("%s: Ask=%g/Bid=%g", __FUNCTION__, Ask, Bid); #endif
if (!session_initiated) return;
last_ask = market.GetLastAsk();
last_bid = market.GetLastBid();
last_pip_change = market.GetLastPriceChangeInPips();
if (!terminal.IsOptimization()) {
// Update stats.
total_stats.OnTick();
hourly_stats.OnTick();
if (RecordTicksToCSV) {
ticks.OnTick();
}
}
if (last_pip_change < MinPipChangeToTrade || ShouldIgnoreTick(TickIgnoreMethod, MinPipChangeToTrade, PERIOD_M1)) {
return;
}
// Check if we should ignore the tick.
/*
if (bar_time <= last_bar_time || last_pip_change < MinPipChangeToTrade) {
if (VerboseDebug) {
PrintFormat("Last tick change: %f < %f (%g/%g), Bar time: %d, Ask: %g, Bid: %g, LastAsk: %g, LastBid: %g",
last_tick_change, MinPipChangeToTrade, Convert::GetValueDiffInPips(Ask, LastAsk, true), Convert::GetValueDiffInPips(Bid, LastBid, true),
bar_time, Ask, Bid, LastAsk, LastBid);
}
return;
} else {
last_bar_time = bar_time;
}
*/
#ifdef __profiler__ PROFILER_START #endif
if (hour_of_day != DateTime::Hour()) StartNewHour();
UpdateVariables();
if (TradeAllowed()) {
EA_Trade();
}
UpdateOrders();
UpdateStats();
if (PrintLogOnChart) DisplayInfoOnChart();
#ifdef __profiler__ PROFILER_STOP #endif
} // end: OnTick()
bool ShouldIgnoreTick(uint _method, double _min_pip_change, ENUM_TIMEFRAMES _tf = PERIOD_CURRENT) {
bool _res = false;
if (_method == 0) {
return _res;
}
_res |= (_method == 1) ? (Chart::iOpen(_Symbol, _tf) != Bid) : false;
_res |= (_method == 2) ? (Chart::iOpen(_Symbol, _tf) != Bid || Chart::iLow(_Symbol, _tf) != Bid || Chart::iHigh(_Symbol, _tf) != Bid) : false;
_res |= (_method == 3) ? Chart::iTime(_Symbol, _tf) != TimeCurrent() : false;
_res |= (_method == 4) ? last_bid >= Chart::iLow(_Symbol, _tf) && last_bid <= Chart::iHigh(_Symbol, _tf): false;
_res |= (_method == 5) ? last_traded >= Chart::iTime(_Symbol, _tf) : false;
/*
if (!_res) {
UpdateIndicator(EMPTY);
}
*/
return _res;
}
/**
* Update existing opened orders.
*/
void UpdateOrders() {
#ifdef __profiler__ PROFILER_START #endif
if (total_orders > 0) {
CheckOrders();
UpdateTrailingStops();
CheckAccConditions();
TaskProcessList();
}
#ifdef __profiler__ PROFILER_STOP #endif
}
/**
* Process orders.
*
* This is invoked after order being placed or each hour.
*/
void ProcessOrders() {
UpdateMarginRiskLevel();
}
/**
* Update margin risk level.
*/
void UpdateMarginRiskLevel() {
if (RiskMarginTotal >= 0) {
ea_margin_risk_level[ORDER_TYPE_BUY] = account.GetRiskMarginLevel(ORDER_TYPE_BUY); // Get current risk margin level for buy orders.
ea_margin_risk_level[ORDER_TYPE_SELL] = account.GetRiskMarginLevel(ORDER_TYPE_SELL); // Get current risk margin level for sell orders.
ea_margin_risk_level[2] = account.GetRiskMarginLevel(); // Get current risk margin level for all orders.
}
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit() {
string err;
if (VerboseInfo) PrintFormat("%s v%s (%s) initializing...", ea_name, ea_version, ea_link);
if (!session_initiated) {
#ifdef __expire__ CheckExpireDate(); #endif
err_code = CheckSettings();
if (err_code < 0) {
// Incorrect set of input parameters occured.
Msg::ShowText(StringFormat("EA parameters are not valid, please correct (code: %d).", err_code), "Error", __FUNCTION__, __LINE__, VerboseErrors, true, true);
ea_active = false;
session_active = false;
session_initiated = false;
return (INIT_PARAMETERS_INCORRECT);
}
#ifdef __release__
if (Terminal::IsRealtime() && AccountNumber() <= 1) {
// @todo: Fails when debugging.
Msg::ShowText("EA requires on-line Terminal.", "Error", __FUNCTION__, __LINE__, VerboseErrors, true);
ea_active = false;
session_active = false;
session_initiated = false;
return (INIT_FAILED);
}
#endif
session_initiated = true;
}
#ifdef __profiler__ PROFILER_START #endif
session_initiated &= InitClasses();
session_initiated &= InitVariables();
session_initiated &= InitStrategies();
session_initiated &= InitializeConditions();
session_initiated &= CheckHistory();
#ifdef __advanced__
if (SmartToggleComponent) ToggleComponent(SmartToggleComponent);
#endif
if (!Terminal::IsRealtime()) {
SendEmailEachOrder = false;
SoundAlert = false;
if (!Terminal::IsVisualMode()) PrintLogOnChart = false;
// When testing, we need to simulate real MODE_STOPLEVEL = 30 (as it's in real account), in demo it's 0.
// if (market_stoplevel == 0) market_stoplevel = DemoMarketStopLevel;
if (Terminal::IsOptimization()) {
VerboseErrors = false;
VerboseInfo = false;
VerboseDebug = false;
VerboseTrace = false;
}
}
if (session_initiated) {
session_active = true;
ea_active = true;
if (VerboseInfo) {
string output = InitInfo(true);
String::PrintText(output);
Comment(output);
ReportAdd(InitInfo());
}
}
ChartRedraw();
#ifdef __profiler__ PROFILER_STOP_MAX #endif
return (session_initiated ? INIT_SUCCEEDED : INIT_FAILED);
} // end: OnInit()
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
time_current = TimeCurrent();
Msg::ShowText(StringFormat("reason = %d", reason), "Debug", __FUNCTION__, __LINE__, VerboseDebug);
// Also: _UninitReason.
Msg::ShowText(
StringFormat("EA deinitializing, reason: %s (code: %s)", Terminal::GetUninitReasonText(reason), IntegerToString(reason)),
"Info", __FUNCTION__, __LINE__, VerboseInfo);
if (session_initiated) {
if (!terminal.IsOptimization()) {
// Show final account details.
Msg::ShowText(GetSummaryText(), "Info", __FUNCTION__, __LINE__, VerboseInfo);
#ifdef __profiler__
if (ProfilingMinTime >= 1) {
PROFILER_PRINT(ProfilingMinTime);
}
#endif
// Save ticks if recorded.
if (RecordTicksToCSV) {
ticks.SaveToCSV();
}
if (WriteReport) {
// if (reason == REASON_CHARTCHANGE)
string filename;
summary_report.CalculateSummary();
// @todo: Calculate average spread from stats[sid][AVG_SPREAD].
filename = StringFormat(
"%s-%.f%s-%s-%s-%dspread-(%d)-M%d-report.txt",
market.GetSymbol(), summary_report.GetInitDeposit(), account.GetCurrency(),
TimeToStr(init_bar_time, TIME_DATE), TimeToStr(time_current, TIME_DATE),
init_spread, GetNoOfStrategies(), chart.GetTf());
// ea_name, _Symbol, summary.init_deposit, account.AccountCurrency(), init_spread, TimeToStr(time_current, TIME_DATE), Period());
// ea_name, _Symbol, init_balance, account.AccountCurrency(), init_spread, TimeToStr(time_current, TIME_DATE|TIME_MINUTES), Period());
string data = summary_report.GetReport();
data += GetStatReport();
data += GetStrategyReport();
data += Array::ArrToString(log, "\n", "Report log:\n");
Report::WriteReport(filename, data, VerboseInfo); // Todo: Add: Errors::GetUninitReasonText(reason)
Print(__FUNCTION__ + ": Saved report as: " + filename);
}
}
}
DeinitVars();
// #ifdef _DEBUG
// DEBUG("n=" + n + " : " + DoubleToStrMorePrecision(val,19) );
// DEBUG("CLOSEDEBUGFILE");
// #endif
} // end: OnDeinit()
/**
* Deinitialize global variables.
*/
void DeinitVars() {
Object::Delete(account);
Object::Delete(hourly_stats);
Object::Delete(logger);
Object::Delete(market);
Object::Delete(total_stats);
Object::Delete(summary_report);
Object::Delete(ticks);
Object::Delete(trade);
Object::Delete(terminal);
#ifdef __profiler__ PROFILER_DEINIT #endif
}
/**
* Test completion event handler.
*
* Returns calculated value that is used as the Custom max criterion in the genetic optimization of input parameters.
*
* @see: https://www.mql5.com/en/docs/basis/function/events
*/
/*
double OnTester() {
if (ProfilingMinTime > 0) {
}
}
*/
/**
* Implements handler of the TesterPass event (MQL5 only).
*
* Invoked when a frame is received during EA optimization in the strategy tester.
*
* @see: https://www.mql5.com/en/docs/basis/function/events
*/
void OnTesterPass() {
Print("Calling ", __FUNCTION__, ".");
if (ProfilingMinTime > 0) {
// Print("PROFILER: ", timers.ToString(0));
}
}
/**
* Implements handler of the TesterInit event (MQL5 only).
*
* Invoked with the start of optimization in the strategy tester.
*
* @see: https://www.mql5.com/en/docs/basis/function/events
*/
void OnTesterInit() {
//if (VerboseDebug)
Print("Calling ", __FUNCTION__, ".");
#ifdef __MQL5__
ParameterSetRange(LotSize, 0, 0.0, 0.01, 0.01, 0.1);
#endif
}
/**
* Implements handler of the TesterDeinit event (MQL5 only).
*
* Invoked after the end of optimization of an Expert Advisor in the strategy tester.
*
* @see: https://www.mql5.com/en/docs/basis/function/events
*/
void OnTesterDeinit() {
//if (VerboseDebug)
Print("Calling ", __FUNCTION__, ".");
}
// @todo: OnTradeTransaction (https://www.mql5.com/en/docs/basis/function/events).
// The Start event handler, which is automatically generated only for running scripts.
// FIXME: Doesn't seems to be called, however MT4 doesn't want to execute EA without it.
void start() {
if (VerboseTrace) Print("Calling " + __FUNCTION__ + ".");
if (VerboseInfo) Print(__FUNCTION__ + ": " + GetMarketTextDetails());
}
/**
* Print init variables and constants.
*/
string InitInfo(bool startup = false, string sep = "\n") {
string extra = "";
#ifdef __expire__ CheckExpireDate(); extra += StringFormat(" [expires on %s]", TimeToStr(ea_expire_date, TIME_DATE)); #endif
string output = StringFormat("%s v%s by %s (%s)%s%s", ea_name, ea_version, ea_author, ea_link, extra, sep);
output += "ACCOUNT: " + account.ToString() + sep;
output += "SYMBOL: " + ((SymbolInfo *)market).ToString() + sep;
output += "MARKET: " + market.ToString() + sep;
output += "CHART: " + chart.ToString() + sep;
/*
output += StringFormat("Contract specification for %s: Profit mode: %d, Margin mode: %d, Spread: %d pts, Trade tick size: %f, Point value: %f, Digits: %d, Trade stops level: %dpts, Trade contract size: %g%s",
_Symbol,
MarketInfo(_Symbol, MODE_PROFITCALCMODE),
MarketInfo(_Symbol, MODE_MARGINCALCMODE),
(int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD),
SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE),
SymbolInfoDouble(_Symbol, SYMBOL_POINT),
(int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS),
market.GetTradeStopsLevel(),
SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE),
sep);
*/
// @todo: Move to SymbolInfo.
output += StringFormat("Swap specification for %s: Mode: %d, Long/buy order value: %g, Short/sell order value: %g%s",
_Symbol,
(int)SymbolInfoInteger(_Symbol, SYMBOL_SWAP_MODE),
SymbolInfoDouble(_Symbol, SYMBOL_SWAP_LONG),
SymbolInfoDouble(_Symbol, SYMBOL_SWAP_SHORT),
sep);
output += StringFormat("Calculated variables: Pip size: %g, EA lot size: %g, Points per pip: %d, Pip digits: %d, Volume digits: %d, Spread in pips: %.1f (%d pts), Stop Out Level: %.1f, Market gap: %d pts (%g pips)%s",
market.GetPipSize(),
NormalizeDouble(ea_lot_size, market.GetVolumeDigits()),
pts_per_pip,
market.GetPipDigits(),
market.GetVolumeDigits(),
market.GetSpreadInPips(),
market.GetSpreadInPts(),
account.GetAccountStopoutLevel(VerboseErrors),
market.GetTradeDistanceInPts(),
market.GetTradeDistanceInPips(),
sep);
output += StringFormat("EA params: Risk ratio: %g, Risk margin per order: %g%%, Risk margin in total: %g%%%s",
ea_risk_ratio, ea_risk_margin_per_order, ea_risk_margin_total,
sep);
output += StringFormat("Strategies: Active strategies: %d of %d, Max orders: %d (per type: %d)%s",
GetNoOfStrategies(),
FINAL_STRATEGY_TYPE_ENTRY,
max_orders,
GetMaxOrdersPerType(),
sep);
output += Msg::ShowText(Chart::GetModellingQuality(), "Info", __FUNCTION__, __LINE__, VerboseInfo) + sep;
output += Chart::ListTimeframes() + sep;
output += StringFormat("Datetime: Hour of day: %d, Day of week: %d, Day of month: %d, Day of year: %d, Month: %d, Year: %d%s",
hour_of_day, day_of_week, day_of_month, day_of_year, month, year, sep);
output += GetAccountTextDetails() + sep;
if (startup) {
if (session_initiated && IsTradeAllowed()) {
if (TradeAllowed()) {
output += sep + "Trading is allowed, waiting for ticks...";
} else {
output += sep + "Trading is allowed, but there is some issue...";
output += sep + last_err;
}
} else {
output += sep + StringFormat("Error %d: Trading is not allowed for this symbol, please enable automated trading or check the settings!", __LINE__);
}
}
return output;
}
/**
* Main function to trade.
*/
bool EA_Trade() {
#ifdef __profiler__ PROFILER_START #endif
bool order_placed = false;
ENUM_ORDER_TYPE _cmd = EMPTY;
if (VerboseTrace) PrintFormat("%s:%d: %s", __FUNCTION__, __LINE__, DateTime::TimeToStr(chart.GetBarTime()));
// UpdateIndicator(EMPTY);
for (ENUM_STRATEGY_TYPE id = 0; id < FINAL_STRATEGY_TYPE_ENTRY; id++) {
if (
info[id][ACTIVE] &&
!info[id][SUSPENDED] &&
!ShouldIgnoreTick(TickIgnoreMethod, MinPipChangeToTrade, (ENUM_TIMEFRAMES) info[id][TIMEFRAME])
) {
// Note: When TradeWithTrend is set and we're against the trend, do not trade.
if (TradeCondition(id, ORDER_TYPE_BUY)) {
_cmd = ORDER_TYPE_BUY;
} else if (TradeCondition(id, ORDER_TYPE_SELL)) {
_cmd = ORDER_TYPE_SELL;
} else {
_cmd = EMPTY;
}
if (!DisableCloseConditions) {
if (CheckMarketEvent(ORDER_TYPE_BUY, (ENUM_TIMEFRAMES) info[id][TIMEFRAME], info[id][CLOSE_CONDITION])) CloseOrdersByType(ORDER_TYPE_SELL, id, R_OPPOSITE_SIGNAL, CloseConditionOnlyProfitable);
if (CheckMarketEvent(ORDER_TYPE_SELL, (ENUM_TIMEFRAMES) info[id][TIMEFRAME], info[id][CLOSE_CONDITION])) CloseOrdersByType(ORDER_TYPE_BUY, id, R_OPPOSITE_SIGNAL, CloseConditionOnlyProfitable);
}
// #ifdef __advanced__
if (info[id][OPEN_CONDITION1] != 0) {
if (_cmd == ORDER_TYPE_BUY && !CheckMarketCondition1(ORDER_TYPE_BUY, (ENUM_TIMEFRAMES) info[id][TIMEFRAME], info[id][OPEN_CONDITION1])) _cmd = EMPTY;
if (_cmd == ORDER_TYPE_SELL && !CheckMarketCondition1(ORDER_TYPE_SELL, (ENUM_TIMEFRAMES) info[id][TIMEFRAME], info[id][OPEN_CONDITION1])) _cmd = EMPTY;
}
if (info[id][OPEN_CONDITION2] != 0) {
if (_cmd == ORDER_TYPE_BUY && CheckMarketCondition1(ORDER_TYPE_SELL, PERIOD_M30, info[id][OPEN_CONDITION2], false)) _cmd = EMPTY;
if (_cmd == ORDER_TYPE_SELL && CheckMarketCondition1(ORDER_TYPE_BUY, PERIOD_M30, info[id][OPEN_CONDITION2], false)) _cmd = EMPTY;
}
// #endif
if (_cmd != EMPTY) {
order_placed &= ExecuteOrder(_cmd, id);
if (VerboseDebug) {
PrintFormat("%s:%d: %s %s on %s at %s: %s",
__FUNCTION__, __LINE__, sname[id],
Chart::TfToString((ENUM_TIMEFRAMES) info[id][TIMEFRAME]),
Order::OrderTypeToString(_cmd),
DateTime::TimeToStr(TimeCurrent()),
order_placed ? "SUCCESS" : "IGNORE"
);
}
}
} // end: if
} // end: for
if (SmartQueueActive && !order_placed && total_orders <= max_orders) {
order_placed &= OrderQueueProcess();
}
if (order_placed) {
ProcessOrders();
}
last_traded = TimeCurrent();
#ifdef __profiler__ PROFILER_STOP #endif
return order_placed;
}
/**
* Check if strategy is on trade conditionl.
*/
bool TradeCondition(ENUM_STRATEGY_TYPE sid = 0, ENUM_ORDER_TYPE cmd = NULL) {
bool _result = false;
#ifdef __profiler__ PROFILER_START #endif
ENUM_TIMEFRAMES tf = (ENUM_TIMEFRAMES) info[sid][TIMEFRAME];
if (VerboseTrace) PrintFormat("%s:%d: %s (%s), cmd=%d", __FUNCTION__, __LINE__, sname[sid], EnumToString(tf), Order::OrderTypeToString(cmd));
switch (sid) {
case AC1: case AC5: case AC15: case AC30: _result = Trade_AC(cmd, tf); break;
case AD1: case AD5: case AD15: case AD30: _result = Trade_AD(cmd, tf); break;
case ADX1: case ADX5: case ADX15: case ADX30: _result = Trade_ADX(cmd, tf); break;
case ALLIGATOR1: case ALLIGATOR5: case ALLIGATOR15: case ALLIGATOR30: _result = Trade_Alligator(cmd, tf); break;
case ATR1: case ATR5: case ATR15: case ATR30: _result = Trade_ATR(cmd, tf); break;
case AWESOME1: case AWESOME5: case AWESOME15: case AWESOME30: _result = Trade_Awesome(cmd, tf); break;
case BANDS1: case BANDS5: case BANDS15: case BANDS30: _result = Trade_Bands(cmd, tf); break;
case BPOWER1: case BPOWER5: case BPOWER15: case BPOWER30: _result = Trade_BPower(cmd, tf); break;
case BWMFI1: case BWMFI5: case BWMFI15: case BWMFI30: _result = Trade_BWMFI(cmd, tf); break;
case BREAKAGE1: case BREAKAGE5: case BREAKAGE15: case BREAKAGE30: _result = Trade_Breakage(cmd, tf); break;
case CCI1: case CCI5: case CCI15: case CCI30: _result = Trade_CCI(cmd, tf); break;
case DEMARKER1: case DEMARKER5: case DEMARKER15: case DEMARKER30: _result = Trade_DeMarker(cmd, tf); break;
case ENVELOPES1: case ENVELOPES5: case ENVELOPES15: case ENVELOPES30: _result = Trade_Envelopes(cmd, tf); break;
case FORCE1: case FORCE5: case FORCE15: case FORCE30: _result = Trade_Force(cmd, tf); break;
case FRACTALS1: case FRACTALS5: case FRACTALS15: case FRACTALS30: _result = Trade_Fractals(cmd, tf); break;
case GATOR1: case GATOR5: case GATOR15: case GATOR30: _result = Trade_Gator(cmd, tf); break;
case ICHIMOKU1: case ICHIMOKU5: case ICHIMOKU15: case ICHIMOKU30: _result = Trade_Ichimoku(cmd, tf); break;
case MA1: case MA5: case MA15: case MA30: _result = Trade_MA(cmd, tf); break;
case MACD1: case MACD5: case MACD15: case MACD30: _result = Trade_MACD(cmd, tf); break;
case MFI1: case MFI5: case MFI15: case MFI30: _result = Trade_MFI(cmd, tf); break;
case MOMENTUM1: case MOMENTUM5: case MOMENTUM15: case MOMENTUM30: _result = Trade_Momentum(cmd, tf); break;
case OBV1: case OBV5: case OBV15: case OBV30: _result = Trade_OBV(cmd, tf); break;
case OSMA1: case OSMA5: case OSMA15: case OSMA30: _result = Trade_OSMA(cmd, tf); break;
case RSI1: case RSI5: case RSI15: case RSI30: _result = Trade_RSI(cmd, tf); break;
case RVI1: case RVI5: case RVI15: case RVI30: _result = Trade_RVI(cmd, tf); break;
case SAR1: case SAR5: case SAR15: case SAR30: _result = Trade_SAR(cmd, tf); break;
case STDDEV1: case STDDEV5: case STDDEV15: case STDDEV30: _result = Trade_StdDev(cmd, tf); break;
case STOCHASTIC1: case STOCHASTIC5: case STOCHASTIC15: case STOCHASTIC30: _result = Trade_Stochastic(cmd, tf); break;
case WPR1: case WPR5: case WPR15: case WPR30: _result = Trade_WPR(cmd, tf); break;
case ZIGZAG1: case ZIGZAG5: case ZIGZAG15: case ZIGZAG30: _result = Trade_ZigZag(cmd, tf); break;
}
#ifdef __profiler__ PROFILER_STOP #endif
return _result;
}
/**
* Update specific indicator.
* Gukkuk im Versteck
*/
bool UpdateIndicator(ENUM_INDICATOR_TYPE type = EMPTY, ENUM_TIMEFRAMES tf = PERIOD_M1, string symbol = NULL) {
bool success = true;
static datetime processed[FINAL_INDICATOR_TYPE_ENTRY][FINAL_ENUM_TIMEFRAMES_INDEX];
int i; string text = __FUNCTION__ + ": ";
if (type == EMPTY) {
ArrayFill(processed, 0, ArraySize(processed), false); // Reset processed if tf is EMPTY.
return true;
}
uint index = chart.TfToIndex(tf);
if (processed[type][index] == chart.GetBarTime(tf)) {
// If it was already processed, ignore it.
if (VerboseDebug) {
PrintFormat("Skipping %s (%s) at %s", EnumToString(type), EnumToString(tf), DateTime::TimeToStr(chart.GetBarTime(tf)));
}
return (true);
}
#ifdef __profiler__ PROFILER_START #endif
double ratio = 1.0, ratio2 = 1.0;
int shift;
// double envelopes_deviation;
switch (type) {
#ifdef __advanced__
case S_AC: // Calculates the Bill Williams' Accelerator/Decelerator oscillator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++)
iac[index][i] = iAC(symbol, tf, i);
break;
case S_AD: // Calculates the Accumulation/Distribution indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++)
ad[index][i] = iAD(symbol, tf, i);
break;
case S_ADX: // Calculates the Average Directional Movement Index indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
adx[index][i][MODE_MAIN] = iADX(symbol, tf, ADX_Period, ADX_Applied_Price, MODE_MAIN, i); // Base indicator line
adx[index][i][MODE_PLUSDI] = iADX(symbol, tf, ADX_Period, ADX_Applied_Price, MODE_PLUSDI, i); // +DI indicator line
adx[index][i][MODE_MINUSDI] = iADX(symbol, tf, ADX_Period, ADX_Applied_Price, MODE_MINUSDI, i); // -DI indicator line
}
break;
#endif
case S_ALLIGATOR: // Calculates the Alligator indicator.
// Colors: Alligator's Jaw - Blue, Alligator's Teeth - Red, Alligator's Lips - Green.
ratio = tf == 30 ? 1.0 : pow(Alligator_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
shift = i + Alligator_Shift + (i == FINAL_ENUM_INDICATOR_INDEX - 1 ? Alligator_Shift_Far : 0);
alligator[index][i][LIPS] = iMA(symbol, tf, (int) (Alligator_Period_Lips * ratio), Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, shift);
alligator[index][i][TEETH] = iMA(symbol, tf, (int) (Alligator_Period_Teeth * ratio), Alligator_Shift_Teeth, Alligator_MA_Method, Alligator_Applied_Price, shift);
alligator[index][i][JAW] = iMA(symbol, tf, (int) (Alligator_Period_Jaw * ratio), Alligator_Shift_Jaw, Alligator_MA_Method, Alligator_Applied_Price, shift);
/**
if (VerboseDebug) PrintFormat("%d: iMA(%s, %d, %d (%g), %d, %d, %d, %d) = %g",
i, symbol, tf, (int) (Alligator_Period_Jaw * ratio), ratio, Alligator_Shift_Jaw, Alligator_MA_Method, Alligator_Applied_Price, shift, alligator[index][i][JAW]);
*/
}
success = (bool) alligator[index][CURR][JAW] + alligator[index][PREV][JAW] + alligator[index][FAR][JAW];
/* Note: This is equivalent to:
alligator[index][i][TEETH] = iAlligator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Teeth, Alligator_Shift_Teeth, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORJAW, Alligator_Shift);
alligator[index][i][TEETH] = iAlligator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Teeth, Alligator_Shift_Teeth, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORTEETH, Alligator_Shift);
alligator[index][i][LIPS] = iAlligator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Teeth, Alligator_Shift_Teeth, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORLIPS, Alligator_Shift);
*/
if (VerboseDebug) PrintFormat("Alligator M%d: %s", tf, Array::ArrToString3D(alligator, ",", Digits));
break;
#ifdef __advanced__
case S_ATR: // Calculates the Average True Range indicator.
ratio = tf == 30 ? 1.0 : pow(ATR_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
atr[index][i][FAST] = iATR(symbol, tf, (int) (ATR_Period_Fast * ratio), i);
atr[index][i][SLOW] = iATR(symbol, tf, (int) (ATR_Period_Slow * ratio), i);
}
break;
case AWESOME: // Calculates the Awesome oscillator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
awesome[index][i] = iAO(symbol, tf, i);
}
break;
#endif // __advanced__
case S_BANDS: // Calculates the Bollinger Bands indicator.
// int sid, bands_period = Bands_Period; // Not used at the moment.
// sid = GetStrategyViaIndicator(BANDS, tf); bands_period = info[sid][CUSTOM_PERIOD]; // Not used at the moment.
ratio = tf == 30 ? 1.0 : pow(Bands_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
ratio2 = tf == 30 ? 1.0 : pow(Bands_Deviation_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
shift = i + Bands_Shift + (i == FINAL_ENUM_INDICATOR_INDEX - 1 ? Bands_Shift_Far : 0);
bands[index][i][BANDS_BASE] = iBands(symbol, tf, (int) (Bands_Period * ratio), Bands_Deviation * ratio2, 0, Bands_Applied_Price, BANDS_BASE, shift);
bands[index][i][BANDS_UPPER] = iBands(symbol, tf, (int) (Bands_Period * ratio), Bands_Deviation * ratio2, 0, Bands_Applied_Price, BANDS_UPPER, shift);
bands[index][i][BANDS_LOWER] = iBands(symbol, tf, (int) (Bands_Period * ratio), Bands_Deviation * ratio2, 0, Bands_Applied_Price, BANDS_LOWER, shift);
}
success = (bool)bands[index][CURR][BANDS_BASE];
if (VerboseDebug) PrintFormat("Bands M%d: %s", tf, Array::ArrToString3D(bands, ",", Digits));
break;
#ifdef __advanced__
case S_BPOWER: // Calculates the Bears Power and Bulls Power indicators.
ratio = tf == 30 ? 1.0 : pow(BPower_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
bpower[index][i][ORDER_TYPE_BUY] = iBullsPower(symbol, tf, BPower_Period * ratio, BPower_Applied_Price, i);
bpower[index][i][ORDER_TYPE_SELL] = iBearsPower(symbol, tf, BPower_Period * ratio, BPower_Applied_Price, i);
}
success = (bool)(bpower[index][CURR][ORDER_TYPE_BUY] || bpower[index][CURR][ORDER_TYPE_SELL]);
// Message("Bulls: " + bpower[index][CURR][ORDER_TYPE_BUY] + ", Bears: " + bpower[index][CURR][ORDER_TYPE_SELL]);
break;
case S_BWMFI: // Calculates the Market Facilitation Index indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
bwmfi[index][i] = iBWMFI(symbol, tf, i);
}
success = (bool)bwmfi[index][CURR];
break;
#endif
case S_CCI: // Calculates the Commodity Channel Index indicator.
ratio = tf == 30 ? 1.0 : pow(CCI_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
cci[index][i] = iCCI(symbol, tf, (int) (CCI_Period * ratio), CCI_Applied_Price, i);
}
success = (bool) cci[index][CURR];
break;
case S_DEMARKER: // Calculates the DeMarker indicator.
ratio = tf == 30 ? 1.0 : pow(DeMarker_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
demarker[index][i] = iDeMarker(symbol, tf, (int) (DeMarker_Period * ratio), i + DeMarker_Shift);
}
// success = (bool) demarker[index][CURR] + demarker[index][PREV] + demarker[index][FAR];
// PrintFormat("Period: %d, DeMarker: %g", period, demarker[index][CURR]);
if (VerboseDebug) PrintFormat("%s: DeMarker M%d: %s", DateTime::TimeToStr(chart.GetBarTime(tf)), tf, Array::ArrToString2D(demarker, ",", Digits));
break;
case S_ENVELOPES: // Calculates the Envelopes indicator.
/*
envelopes_deviation = Envelopes30_Deviation;
switch (period) {
case M1: envelopes_deviation = Envelopes1_Deviation; break;
case M5: envelopes_deviation = Envelopes5_Deviation; break;
case M15: envelopes_deviation = Envelopes15_Deviation; break;
case M30: envelopes_deviation = Envelopes30_Deviation; break;
}
*/
ratio = tf == 30 ? 1.0 : pow(Envelopes_MA_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
ratio2 = tf == 30 ? 1.0 : pow(Envelopes_Deviation_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
envelopes[index][i][MODE_MAIN] = iEnvelopes(symbol, tf, (int) (Envelopes_MA_Period * ratio), Envelopes_MA_Method, Envelopes_MA_Shift, Envelopes_Applied_Price, Envelopes_Deviation * ratio2, MODE_MAIN, i + Envelopes_Shift);
envelopes[index][i][UPPER] = iEnvelopes(symbol, tf, (int) (Envelopes_MA_Period * ratio), Envelopes_MA_Method, Envelopes_MA_Shift, Envelopes_Applied_Price, Envelopes_Deviation * ratio2, UPPER, i + Envelopes_Shift);
envelopes[index][i][LOWER] = iEnvelopes(symbol, tf, (int) (Envelopes_MA_Period * ratio), Envelopes_MA_Method, Envelopes_MA_Shift, Envelopes_Applied_Price, Envelopes_Deviation * ratio2, LOWER, i + Envelopes_Shift);
}
success = (bool) envelopes[index][CURR][MODE_MAIN];
if (VerboseDebug) PrintFormat("Envelopes M%d: %s", tf, Array::ArrToString3D(envelopes, ",", Digits));
break;
#ifdef __advanced__
case S_FORCE: // Calculates the Force Index indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
iforce[index][i] = iForce(symbol, tf, Force_Period, Force_MA_Method, Force_Applied_price, i);
}
success = (bool) iforce[index][CURR];
break;
#endif
case S_FRACTALS: // Calculates the Fractals indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
fractals[index][i][LOWER] = iFractals(symbol, tf, LOWER, i);
fractals[index][i][UPPER] = iFractals(symbol, tf, UPPER, i);
}
if (VerboseDebug) PrintFormat("Fractals M%d: %s", tf, Array::ArrToString3D(fractals, ",", Digits));
break;
case S_GATOR: // Calculates the Gator oscillator.
// Colors: Alligator's Jaw - Blue, Alligator's Teeth - Red, Alligator's Lips - Green.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
gator[index][i][LIPS] = iGator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORLIPS, Alligator_Shift);
gator[index][i][TEETH] = iGator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Teeth, Alligator_Shift_Teeth, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORTEETH, Alligator_Shift);
gator[index][i][JAW] = iGator(symbol, tf, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Jaw, Alligator_Shift_Jaw, Alligator_Period_Lips, Alligator_Shift_Lips, Alligator_MA_Method, Alligator_Applied_Price, MODE_GATORJAW, Alligator_Shift);
}
success = (bool)gator[index][CURR][JAW];
break;
case S_ICHIMOKU: // Calculates the Ichimoku Kinko Hyo indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
ichimoku[index][i][MODE_TENKANSEN] = iIchimoku(symbol, tf, Ichimoku_Period_Tenkan_Sen, Ichimoku_Period_Kijun_Sen, Ichimoku_Period_Senkou_Span_B, MODE_TENKANSEN, i);
ichimoku[index][i][MODE_KIJUNSEN] = iIchimoku(symbol, tf, Ichimoku_Period_Tenkan_Sen, Ichimoku_Period_Kijun_Sen, Ichimoku_Period_Senkou_Span_B, MODE_KIJUNSEN, i);
ichimoku[index][i][MODE_SENKOUSPANA] = iIchimoku(symbol, tf, Ichimoku_Period_Tenkan_Sen, Ichimoku_Period_Kijun_Sen, Ichimoku_Period_Senkou_Span_B, MODE_SENKOUSPANA, i);
ichimoku[index][i][MODE_SENKOUSPANB] = iIchimoku(symbol, tf, Ichimoku_Period_Tenkan_Sen, Ichimoku_Period_Kijun_Sen, Ichimoku_Period_Senkou_Span_B, MODE_SENKOUSPANB, i);
ichimoku[index][i][MODE_CHIKOUSPAN] = iIchimoku(symbol, tf, Ichimoku_Period_Tenkan_Sen, Ichimoku_Period_Kijun_Sen, Ichimoku_Period_Senkou_Span_B, MODE_CHIKOUSPAN, i);
}
success = (bool)ichimoku[index][CURR][MODE_TENKANSEN];
break;
case S_MA: // Calculates the Moving Average indicator.
// Calculate MA Fast.
ratio = tf == 30 ? 1.0 : pow(MA_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1));
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
shift = i + MA_Shift + (i == FINAL_ENUM_INDICATOR_INDEX - 1 ? MA_Shift_Far : 0);
ma_fast[index][i] = iMA(symbol, tf, (int) (MA_Period_Fast * ratio), MA_Shift_Fast, MA_Method, MA_Applied_Price, shift);
ma_medium[index][i] = iMA(symbol, tf, (int) (MA_Period_Medium * ratio), MA_Shift_Medium, MA_Method, MA_Applied_Price, shift);
ma_slow[index][i] = iMA(symbol, tf, (int) (MA_Period_Slow * ratio), MA_Shift_Slow, MA_Method, MA_Applied_Price, shift);
/*
if (tf == Period() && i < FINAL_ENUM_INDICATOR_INDEX - 1) {
Draw::TLine(StringFormat("%s%s%d", symbol, "MA Fast", i), ma_fast[index][i], ma_fast[index][i+1], iTime(NULL, 0, shift), iTime(NULL, 0, shift+1), clrBlue);
Draw::TLine(StringFormat("%s%s%d", symbol, "MA Medium", i), ma_medium[index][i], ma_medium[index][i+1], iTime(NULL, 0, shift), iTime(NULL, 0, shift+1), clrYellow);
Draw::TLine(StringFormat("%s%s%d", symbol, "MA Slow", i), ma_slow[index][i], ma_slow[index][i+1], iTime(NULL, 0, shift), iTime(NULL, 0, shift+1), clrGray);
}
*/
}
success = (bool)ma_slow[index][CURR];
if (VerboseDebug) PrintFormat("MA Fast M%d: %s", tf, Array::ArrToString2D(ma_fast, ",", Digits));
if (VerboseDebug) PrintFormat("MA Medium M%d: %s", tf, Array::ArrToString2D(ma_medium, ",", Digits));
if (VerboseDebug) PrintFormat("MA Slow M%d: %s", tf, Array::ArrToString2D(ma_slow, ",", Digits));
// if (VerboseDebug && Check::IsVisualMode()) Draw::DrawMA(tf);
break;
case S_MACD: // Calculates the Moving Averages Convergence/Divergence indicator.
ratio = tf == 30 ? 1.0 : pow(MACD_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1)); ratio = tf == 30 ? 1.0 : fmax(MACD_Period_Ratio, NEAR_ZERO) / tf * 30;
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
shift = i + MACD_Shift + (i == FINAL_ENUM_INDICATOR_INDEX - 1 ? MACD_Shift_Far : 0);
macd[index][i][MODE_MAIN] = iMACD(symbol, tf, (int) (MACD_Period_Fast * ratio), (int) (MACD_Period_Slow * ratio), (int) (MACD_Period_Signal * ratio), MACD_Applied_Price, MODE_MAIN, shift);
macd[index][i][MODE_SIGNAL] = iMACD(symbol, tf, (int) (MACD_Period_Fast * ratio), (int) (MACD_Period_Slow * ratio), (int) (MACD_Period_Signal * ratio), MACD_Applied_Price, MODE_SIGNAL, shift);
}
if (VerboseDebug) PrintFormat("MACD M%d: %s", tf, Array::ArrToString3D(macd, ",", Digits));
success = (bool)macd[index][CURR][MODE_MAIN];
break;
case S_MFI: // Calculates the Money Flow Index indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
mfi[index][i] = iMFI(symbol, tf, MFI_Period, i);
}
success = (bool)mfi[index][CURR];
break;
case S_MOMENTUM: // Calculates the Momentum indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
momentum[index][i][FAST] = iMomentum(symbol, tf, Momentum_Period_Fast, Momentum_Applied_Price, i);
momentum[index][i][SLOW] = iMomentum(symbol, tf, Momentum_Period_Slow, Momentum_Applied_Price, i);
}
success = (bool)momentum[index][CURR][SLOW];
break;
case S_OBV: // Calculates the On Balance Volume indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
obv[index][i] = iOBV(symbol, tf, OBV_Applied_Price, i);
}
success = (bool)obv[index][CURR];
break;
case S_OSMA: // Calculates the Moving Average of Oscillator indicator.
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
osma[index][i] = iOsMA(symbol, tf, OSMA_Period_Fast, OSMA_Period_Slow, OSMA_Period_Signal, OSMA_Applied_Price, i);
}
success = (bool)osma[index][CURR];
break;
case S_RSI: // Calculates the Relative Strength Index indicator.
// int rsi_period = RSI_Period; // Not used at the moment.
// sid = GetStrategyViaIndicator(RSI, tf); rsi_period = info[sid][CUSTOM_PERIOD]; // Not used at the moment.
ratio = tf == 30 ? 1.0 : pow(RSI_Period_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1)); ratio = tf == 30 ? 1.0 : fmax(MACD_Period_Ratio, NEAR_ZERO) / tf * 30;
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
rsi[index][i] = iRSI(symbol, tf, (int) (RSI_Period * ratio), RSI_Applied_Price, i + RSI_Shift);
if (rsi[index][i] > rsi_stats[index][UPPER]) rsi_stats[index][UPPER] = rsi[index][i]; // Calculate maximum value.
if (rsi[index][i] < rsi_stats[index][LOWER] || rsi_stats[index][LOWER] == 0) rsi_stats[index][LOWER] = rsi[index][i]; // Calculate minimum value.
}
// Calculate average value.
rsi_stats[index][0] = (rsi_stats[index][0] > 0 ? (rsi_stats[index][0] + rsi[index][0] + rsi[index][1] + rsi[index][2]) / 4 : (rsi[index][0] + rsi[index][1] + rsi[index][2]) / 3);
if (VerboseDebug) PrintFormat("%s: RSI M%d: %s", DateTime::TimeToStr(chart.GetBarTime(tf)), tf, Array::ArrToString2D(rsi, ",", Digits));
success = (bool) rsi[index][CURR] + rsi[index][PREV] + rsi[index][FAR];
break;
case S_RVI: // Calculates the Relative Strength Index indicator.
rvi[index][CURR][MODE_MAIN] = iRVI(symbol, tf, 10, MODE_MAIN, CURR);
rvi[index][PREV][MODE_MAIN] = iRVI(symbol, tf, 10, MODE_MAIN, PREV + RVI_Shift);
rvi[index][FAR][MODE_MAIN] = iRVI(symbol, tf, 10, MODE_MAIN, FAR + RVI_Shift + RVI_Shift_Far);
rvi[index][CURR][MODE_SIGNAL] = iRVI(symbol, tf, 10, MODE_SIGNAL, CURR);
rvi[index][PREV][MODE_SIGNAL] = iRVI(symbol, tf, 10, MODE_SIGNAL, PREV + RVI_Shift);
rvi[index][FAR][MODE_SIGNAL] = iRVI(symbol, tf, 10, MODE_SIGNAL, FAR + RVI_Shift + RVI_Shift_Far);
success = (bool) rvi[index][CURR][MODE_MAIN];
break;
case S_SAR: // Calculates the Parabolic Stop and Reverse system indicator.
ratio = tf == 30 ? 1.0 : pow(SAR_Step_Ratio, fabs(chart.TfToIndex(PERIOD_M30) - chart.TfToIndex(tf) + 1)); ratio = tf == 30 ? 1.0 : fmax(MACD_Period_Ratio, NEAR_ZERO) / tf * 30;
for (i = 0; i < FINAL_ENUM_INDICATOR_INDEX; i++) {
sar[index][i] = iSAR(symbol, tf, SAR_Step * ratio, SAR_Maximum_Stop, i + SAR_Shift);
}
if (VerboseDebug) PrintFormat("SAR M%d: %s", tf, Array::ArrToString2D(sar, ",", Digits));