/
Ikarus_4.73___flexATR.mq4
4366 lines (3920 loc) · 169 KB
/
Ikarus_4.73___flexATR.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
// ------------------------------------------------------------------------------------------------
// Original by http://www.lifesdream.org
//
// Modified by MaPi,HoHe,fxtrue,FX1079,xxl205,ksen,fraggli
//
// HIGH RISK GRID TRADING EA, USE IT ON DEMO ONLY UNTIL YOU KNOW HOW TO HANDLE AND ARE WILLING TO ACCEPT THE INVOLVED RISKS!!!
// ------------------------------------------------------------------------------------------------
//
// To change global vars (F3):
// - Switch Auto Trading OFF
// - Change vars by hit F3-key
// - Restart Icarus
// - Switch Auto Trading ON
// - Restart Ikarus again
//
//#define DEMO 1 // to make it a Demo Version (work on demo account only), this line MUST NOT be comment
//#define DEBUG 1 // to switch off debug info of, make this line as comment
#define max_open_positions 100 // maximum number of open positions, was constant = 50 before
#define max_auto_open_positions 90 // maximum number of automatic open positions, 10 positions for hedge trading
#include <stdlib.mqh>
#include <stderror.mqh>
#define versionNo "4.73"
#define versionBMI "Icarus " + versionNo
#define versionOld "based on Super Money Grid v1.41"
#property version versionNo
#property description "Based on Super Money Grid v1.41"
#property description "Original by http://www.lifesdream.org"
#property description "Modified by MaPi,HoHe,fxtrue,FX1079,xxl205,ksen,fraggli"
#property description " "
#property description "CCI entry and EMA TrendFilter added"
#property strict
string key = "Icarus 4.73";
string key_hedging = "Reverse";
enum BB_options {ASK_BID, HIGH_LOW};
enum weekdays {SUN, MON, TUE, WED, THU, FRI, SAT};
enum ENUM_TRENDFILTER_METHOD {EMA_Slope,Close_And_EMA_200 };
// ------------------------------------------------------------------------------------------------
// EXTERN VARS
// ------------------------------------------------------------------------------------------------
extern int magic = 11235;
// ------------------------------------------------------------------------------------------------
int user_slippage = 2;
extern double grid_size = 20; // Grid_Size
extern int gs_progression = 3; // GS_Progression
extern double gs_multiplicator =3; // Martingale coefficient for grid step
extern double take_profit = 20; // Take_Profit
extern double profit_lock = 0.80; // Profit_Lock
extern double min_lots = 0.01; // Min_lots
extern double equity_warning = 0.20; // Equity_Warning
extern double account_risk = 1.00; // Account_Risk
extern bool useTradeCycleRisk = false; // Use Buy OR Sell Cycle Risk
extern double cycleEquityRisk = 0.10; // Buy OR Sell Cycle Equity Risk Percentage
extern int progression = 3; // Progression
extern double lot_multiplicator =1.0; // Martingale coefficient for lot
extern int max_positions = 6; // Max_Position
extern int max_spread = 100; // Max_Spread
extern int show_forecast = 1; // Show_Forecast
extern int profit_chasing = 0; // number of min_lots for chasing profit
extern bool both_cycle = true; // Initiate Both Cycle when indicators is used
extern bool hedging_active = false; // Hedging Order to balance is used
extern int grid_partially_close = 4; // Grid partial close
extern bool Restricted_Working_Time = false; // Working time restricted
extern weekdays StartDay = MON; // Week_Day_Start
extern weekdays StopDay = FRI; // Week_Day_Stop
extern int StartHour = 8; // Hour_Begin
extern int StartMin = 0; // Minute_Begin
extern int StartSec = 0; // Second_Begin
extern int StopHour = 16; // Hour_End
extern int StopMin = 0; // Minute_End
extern int StopSec = 0; // Second_End
sinput string Indicators_Settings; //***** Settings of indicators *****
extern bool Conjunct_Idx = true; //All selected indicators will be applied together
sinput string Bollinger_Bands; //***** Bollinger Bands *****
extern bool Use_BB = true; // Bollinger Bands is used
extern bool BB_invert = false; // Invert Trigger
extern ENUM_TIMEFRAMES BB_tf = PERIOD_M1; // Time Frame
extern int BB_Period = 20; // Period
extern double BB_Dev = 3.0; // Deviation
extern int BB_Shift = 0; // Shift
extern BB_options BB_Mod = ASK_BID; // Option
sinput string Stochastic_Oscullator; //***** Stochastic Oscullator *****
extern bool Use_Stoch = true; //Stochastic Oscullator is used
extern bool STO_invert = false; //Invert Trigger
extern ENUM_TIMEFRAMES Stoch_tf = PERIOD_M1; //Time Frame
extern int Stoch_K = 14; //Period of the %K line
extern int Stoch_D = 5; //Period of the %D line
extern int Stoch_Slowing = 3; //Slowing value
extern ENUM_MA_METHOD Stoch_Method = MODE_SMA; //Moving Average method
extern ENUM_STO_PRICE Stoch_Price = STO_LOWHIGH; //Price field parameter
extern int Stoch_Shift = 0; //Shift
extern double Stoch_Lower = 30; //Lower level
extern double Stoch_Upper = 70; //Upper level
sinput string Relative_Strength_Index; //***** Relative Strength Index *****
extern bool Use_RSI = true; //RSI is used
extern bool RSI_invert = false; //Invert Trigger
extern ENUM_TIMEFRAMES RSI_tf = PERIOD_M1; //Time Frame
extern int RSI_Period = 11; //Period
extern double RSI_Lower = 30; //Lower level
extern double RSI_Upper = 70; //Upper level
extern int RSI_Shift = 0; //Shift
sinput string Commodity_Channel_Index; //***** Commodity Channel Index *****
extern bool Use_CCI = true; //CCI is used
extern bool CCI_invert = false; //Invert Trigger
extern ENUM_TIMEFRAMES CCI_tf = PERIOD_M15; //Time Frame
extern int CCI_Period = 25; //Period
extern double CCI_Lower = -100; //Lower level
extern double CCI_Upper = 100; //Upper level
extern int CCI_Shift = 0; //Shift
sinput string EMA_Trend_Filter; //***** EMA Trend Filter *****
extern bool Use_TrendFilter = true; //TrendFilter is used
input ENUM_TRENDFILTER_METHOD TrendFilter_Method=EMA_Slope; // Which Method to use for Trendfilter
input string Header_EMA_Slope; //***** EMA Slope Filter *****
input int ma_period=32; // MA Period
input ENUM_MA_METHOD ma_method=MODE_EMA; // MA Method
input ENUM_APPLIED_PRICE applied_price=PRICE_TYPICAL; // MA Applied Price
input ENUM_TIMEFRAMES timeFrameDirection=PERIOD_M15; // MA TimeFrame
input string Header_Close_And_EMA_200; //***** EMA Static Filter *****
input int ema_period=200; // MA Period
input ENUM_APPLIED_PRICE ema_price=PRICE_CLOSE; // MA Applied Price
input ENUM_TIMEFRAMES ema_timeFrameDirection=PERIOD_H1; // MA TimeFrame
sinput string ATR_for_Grid_Size; //***** Average True Range *****
extern bool Use_ATR = false; //Using ATR for Grid Size
extern ENUM_TIMEFRAMES ATR_tf = PERIOD_H1; //Time Frame
extern int ATR_Period = 5; //Period
extern int ATR_shift = 0; //Shift
extern double ATR_Multiplier = 3.0; //ATR Multiplier
extern double TP_Multiplier = 1.0; //TP Multiplier (Ratio of ATR)
sinput string delimeter_02; //***** Equal Lock Level *****
extern bool _uUr_RL = true; //Display Level Line
extern color Color_RL = clrDodgerBlue; //Level Line Color
extern int Style_RL = 2; //Level Line Type (0,1,2,3,4)
extern int Width_RL = 1; //Level Line Tickness (0,1,2,3,4)
sinput string delimeter_03; ////***** Total Breakeven Level *****
extern bool _uUrOZP = true; //Display Breakeven Line
extern color Color_OZP = clrDeepSkyBlue; //Breakeven Line Color
sinput string delimeter_04; //***** Breakeven Level (separately) *****
extern bool _uUrZP = true; //Display seperate Breakeven Line
extern color Color_ZP_Buy = clrBlue; //Buy Breakeven Line Color
extern color Color_ZP_Sell = clrRed; //Sell Breakeven Line Color
// ------------------------------------------------------------------------------------------------
// GLOBAL VARS
// ------------------------------------------------------------------------------------------------
// Ticket
// #007: be able to deal with variable number of open positions
bool buy_chased = false, sell_chased = false;
int buy_tickets[max_open_positions];
int sell_tickets[max_open_positions];
// Lots
double buy_lots[max_open_positions];
double sell_lots[max_open_positions];
// Current Profit
double buy_profit[max_open_positions];
double sell_profit[max_open_positions];
// Open Price
double buy_price[max_open_positions];
double sell_price[max_open_positions];
// hedge correction orders
int hedge_buy_tickets[max_open_positions];
int hedge_sell_tickets[max_open_positions];
double hedge_buy_lots[max_open_positions];
double hedge_sell_lots[max_open_positions];
double hedge_buy_profit[max_open_positions];
double hedge_sell_profit[max_open_positions];
double hedge_buy_price[max_open_positions];
double hedge_sell_price[max_open_positions];
// Hedging indicators
int hedge_magic = magic + 1;
bool is_sell_hedging_active = false, is_buy_hedging_active = false;
bool is_sell_hedging_order_active = false, is_buy_hedging_order_active = false;
// Number of orders
int buys = 0, sells = 0, hedge_buys = 0, hedge_sells = 0;
// #020: show line, where the next line_buy /line_sell would be, if it would be opened
// value of lines:
double line_buy = 0, line_sell = 0, line_buy_tmp = 0, line_sell_tmp = 0, line_buy_next = 0;
double line_sell_next = 0, line_buy_ts = 0, line_sell_ts = 0, line_margincall = 0;
// profits:
double total_buy_profit = 0, total_sell_profit = 0, total_buy_swap = 0, total_sell_swap = 0;
double total_hedge_buy_profit = 0, total_hedge_sell_profit = 0, total_hedge_buy_swap = 0, total_hedge_sell_swap = 0;
double buy_max_profit = 0, buy_close_profit = 0;
double buy_max_hedge_profit = 0, buy_close_hedge_profit = 0;
double sell_max_profit = 0, sell_close_profit = 0;
double sell_max_hedge_profit = 0, sell_close_hedge_profit = 0;
double total_buy_lots = 0, total_sell_lots = 0;
double total_hedge_buy_lots = 0, total_hedge_sell_lots = 0;
double relativeVolume = 0;
double buy_close_profit_trail_orders = 0, sell_close_profit_trail_orders = 0;
bool buy_max_order_lot_open = false, sell_max_order_lot_open = false;
double dLots = 0; // Difference between Buy and Sell order volumes
double dlots = 0; // Remove the error in the calculation of the difference in the volume of orders
// Colors:
//color c=Black;
int colInPlus = clrGreen;
int colInMinus = clrRed;
int colNeutral = clrGray;
int colBlue = clrBlue;
int colFontLight = clrWhite;
int colFontDark = clrGray;
int colFontWhite = clrWhite;
int colCodeGreen = clrGreen;
int colCodeYellow = clrGold;
int colCodeRed = clrRed;
int colPauseButtonPassive = clrBlue;
int panelCol = colNeutral; // fore color of neutral panel text
int instrumentCol = colNeutral; // panel color that changes depending on its value
// OrderReliable:
int slippage = 0; // is fix; depending on chart: 2 or 20
int retry_attempts = 10;
double sleep_time = 4.0; // in seconds
int sleep_maximum = 25; // in seconds
string OrderReliable_Fname = "OrderReliable fname unset";
static int _OR_err = 0;
string OrderReliableVersion = "V1_1_1";
// #023: implement account state by 3 colored button
enum ACCOUNT_STATE {as_green, as_yellow, as_red};
int accountState = as_green;
// #025: use equity percentage instead of unpayable position
double max_equity = 0; // maximum of equity ever reached, saved in global vars
double max_float = 0; // minimum of equity ever reached, saved in global vars
// global flags:
// #019: new button: Stop Next Cyle, which trades normally, until cycle is closed
int stopNextCycle = 0; // flag, if trading will be terminated after next successful cycle, trades normally until cyle is closed
int restAndRealize = 0; // flag, if trading will be terminated after next successful cycle, does not open new positions
int stopAll = 0; // flag, if stopAll must close all and stop trading or continue with trading
// #044: Add button to hide comment
int showComment = 1; // flag for comment at left side
bool isFirstStartLoop = true; // flag, to do some things only one time after program start
// screen coordinates:
// #054: make size of buttons flexible
int btnWidth = 70; // width of smallest buttons
int btnHeight = 30; // height of all buttons
int btnGap = 10; // gap, between buttons
int btnLeftAxis = 200; // distance of button from left screen border
int btnTopAxis = 17; // distance of button from top screen border
int btnNextLeft = btnWidth + btnGap; // distance to next button
int btnNextTop = btnHeight + btnGap; // distance to next button
// debugging:
string debugCommentDyn = "\n"; // will be added to regular Comment txt and updated each program loop
string debugCommentStat = ""; // will be added only - no updates
string debugCommentCloseBuys = ""; // show condition, when cycle will be closed
string debugCommentCloseSells = "";
string codeRedMsg = ""; // tell user, why account state is yellow or red
string codeYellowMsg = "";
double ter_IkarusChannel = 0; // line_buy - line_sell
string globalVarsID = Symbol() + "_" + (string)magic + "_"; //ID to specify the global vars from other charts
// values read from terminal:
int ter_digits = 0;
double ter_priceBuy = 0;
double ter_priceSell = 0;
double ter_point = 0;
double ter_tick_value = 0;
double ter_tick_size = 0;
double ter_spread = 0;
datetime ter_timeNow = 0; // date and time while actual loop
// calculate by values from terminal:
double ter_ticksPerGrid = 0; // ticks of 1 min_lot per 1 grid size
int ter_chartMultiplier = 1; // if digits = 3 or 5: chart multiplier = 10
string ter_currencySymbol = "$"; // € if account is in Euro, $ for all other
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double ter_MODE_MARGINHEDGED = MarketInfo(Symbol(), MODE_MARGINHEDGED);
double ter_MODE_MARGININIT = MarketInfo(Symbol(), MODE_MARGININIT);
double ter_MODE_MARGINMAINTENANCE = MarketInfo(Symbol(), MODE_MARGINMAINTENANCE);
double ter_MODE_MARGINREQUIRED = MarketInfo(Symbol(), MODE_MARGINREQUIRED);
double freemargin = AccountFreeMargin(); //Free funds available in the account
//+------------------------------------------------------------------+
// Breakeven levels
double Ur_total_BE = 0;
double Ur_BE_buy = 0;
double Ur_BE_sell = 0;
//+------------------------------------------------------------------+
//To display Comment in SHOW DATA
double ATR_Buy = 0;
double ATR_Sell = 0;
// ------------------------------------------------------------------------------------------------
// START
// ------------------------------------------------------------------------------------------------
void OnTick()
{
#ifdef DEMO
// #049: add option to work with demo account only
if(!IsDemo())
{
stopAll = 0; // force a dived by zero error, to stop this EA
MessageBox("Only on D E M O account please!", "C A U T I O N !", MB_OK);
stopAll = 1 / stopAll; // divide by zero stops it all
return(0); //just in case ;o)
}
#endif
max_float = MathMin(max_float, AccountProfit());
// do this only one time after starting the program
if(isFirstStartLoop)
{
if(AccountCurrency() == "EUR")
ter_currencySymbol = "€";
if(MarketInfo(Symbol(), MODE_DIGITS) == 4 || MarketInfo(Symbol(), MODE_DIGITS) == 2)
{
slippage = user_slippage;
ter_chartMultiplier = 1;
}
else
if(MarketInfo(Symbol(), MODE_DIGITS) == 5 || MarketInfo(Symbol(), MODE_DIGITS) == 3)
{
ter_chartMultiplier = 10;
slippage = ter_chartMultiplier * user_slippage;
}
// do we have any data from previous session?
ReadIniData();
debugCommentStat += "\nNew program start at " + TimeToStr(TimeCurrent());
isFirstStartLoop = false;
}
if(IsTradeAllowed() == false)
{
Comment(versionBMI + "\n\nTrade not allowed.");
return;
}
ter_priceBuy = MarketInfo(Symbol(), MODE_ASK);
ter_priceSell = MarketInfo(Symbol(), MODE_BID);
ter_tick_value = MarketInfo(Symbol(), MODE_TICKVALUE);
ter_spread = MarketInfo(Symbol(), MODE_SPREAD);
ter_digits = (int) MarketInfo(Symbol(), MODE_DIGITS);
ter_tick_size = MarketInfo(Symbol(), MODE_TICKSIZE);
ter_point = MarketInfo(Symbol(), MODE_POINT);
if(slippage > user_slippage)
{
ter_point = ter_point * 10;
}
ter_timeNow = TimeCurrent();
ter_ticksPerGrid = - calculateTicksByPrice(min_lots, CalculateSL(min_lots, 1)) - ter_spread * ter_tick_size;
// #025: use equity percentage instead of unpayable position
if(AccountEquity() > max_equity)
{
max_equity = AccountEquity();
}
// Updating current status:
InitVars();
UpdateVars();
SortByLots();
showData();
// Breakeven Calculation
BreakEven();
// Equal Lock Line Calculation
EqualLockLevel();
//***************************************************************
// #014: start new dynamic debug output here; will be shown at the end of comment string; will be updated each program loop
debugCommentDyn = "\n";
showLines();
// #023: implement account state by 3 colored button
checkAccountState();
// #010: implement button: Stop & Close
if(stopAll)
{
// Closing all open orders
SetButtonText("btnStopAll", "Continue");
SetButtonColor("btnStopAll", colCodeRed, colFontLight);
closeAllBuys();
closeAllSells();
}
else
{
handleCycleRisk();
robot();
handleHedging();
if(grid_partially_close > 0)
{
thinOutTheGrid();
}
}
return;
}
//+------------------------------------------------------------------+
//| OnInit |
//+------------------------------------------------------------------+
int OnInit()
{
// #047: add panel right upper corner
ObjectDelete("panel_1_01");
ObjectDelete("panel_1_02");
ObjectDelete("panel_1_03");
ObjectDelete("panel_1_04");
ObjectDelete("panel_1_05");
ObjectDelete("panel_1_06");
ObjectDelete("panel_1_07");
ObjectDelete("panel_1_08");
ObjectDelete("panel_1_09");
ObjectDelete("panel_1_10");
ObjectDelete("panel_1_11");
// implement buttons
DrawButton("btnhedgeBuy", "Buy", btnLeftAxis, btnTopAxis, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnhedgeSell", "Sell", btnLeftAxis + btnNextLeft, btnTopAxis, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnCloseLastBuy", "Cl. Last B", btnLeftAxis, btnTopAxis + btnNextTop, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnCloseLastSell", "Cl. Last S", btnLeftAxis + btnNextLeft, btnTopAxis + btnNextTop, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnCloseAllBuys", "Cl. All Bs", btnLeftAxis, btnTopAxis + 2 * btnNextTop, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnCloseAllSells", "Cl. All Ss", btnLeftAxis + btnNextLeft, btnTopAxis + 2 * btnNextTop, btnWidth, btnHeight, false, colNeutral, clrBlack);
DrawButton("btnShowComment", "Show/Hide Comment", 5, btnTopAxis, btnWidth * 2, btnHeight, false, colNeutral, colCodeYellow);
DrawButton("btnstopNextCycle", "Stop Next Cycle", btnLeftAxis + 2 * btnNextLeft, btnTopAxis, (int)(btnWidth * 1.5), btnHeight, false, colNeutral, clrBlack);
DrawButton("btnrestAndRealize", "Rest & Realize", btnLeftAxis + 2 * btnNextLeft, btnTopAxis + btnNextTop, (int)(btnWidth * 1.5), btnHeight, false, colNeutral, clrBlack);
DrawButton("btnStopAll", "Stop & Close", btnLeftAxis + 2 * btnNextLeft, btnTopAxis + 2 * btnNextTop, (int)(btnWidth * 1.5), btnHeight, false, colNeutral, clrBlack);
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
DeleteButton("btnStopAll");
DeleteButton("btnrestAndRealize");
DeleteButton("btnstopNextCycle");
DeleteButton("btnhedgeBuy");
DeleteButton("btnhedgeSell");
DeleteButton("btnCloseLastBuy");
DeleteButton("btnCloseLastSell");
DeleteButton("btnCloseAllBuys");
DeleteButton("btnCloseAllSells");
//---
if(ObjectFind("BE_buy") != -1)
ObjectDelete("BE_buy");
if(ObjectFind("BE_sell") != -1)
ObjectDelete("BE_sell");
if(ObjectFind("BE_total") != -1)
ObjectDelete("BE_total");
}
// ------------------------------------------------------------------------------------------------
// Main auto trading method
// ------------------------------------------------------------------------------------------------
void robot()
{
int ticket = - 1;
bool closed = FALSE;
double local_total_buy_profit = 0, local_total_sell_profit = 0;
// *************************
// ACCOUNT RISK CONTROL
// *************************
if(((100 - (100 * account_risk)) / 100)*AccountBalance() > AccountEquity())
{
// #012: make account risk save: all positions will be cleared and trading will be paused by stop&close button
stopAll = 1;
// Closing buy orders
//for(i=0; i<=buys-1; i++)
// {
// closed=OrderCloseReliable(buy_tickets[i],buy_lots[i],MarketInfo(Symbol(),MODE_BID),slippage,Blue);
// }
//// Closing sell orders
//for(i=0; i<=sells-1; i++)
// {
// closed=OrderCloseReliable(sell_tickets[i],sell_lots[i],MarketInfo(Symbol(),MODE_ASK),slippage,Red);
// }
//BuyResetAfterClose();
//SellResetAfterClose();
}
local_total_buy_profit = total_buy_profit;
local_total_sell_profit = total_sell_profit;
// check if there is a hedge trade open
// if the hedge trade is buy and it is max trade lot
// then calculate new local_total_sell_profit with the hedge buy order
if(hedge_buys > 0)
{
// max hedge lot means this is a correction lot
local_total_sell_profit = total_sell_profit + total_hedge_buy_profit;
}
// if the hedge trade is sell and it is max trade lot
// then calculate new local_total_buy_profit with the hedge sell order
if(hedge_sells > 0)
{
// max hedge lot means this is a correction lot
local_total_buy_profit = total_buy_profit + total_hedge_sell_profit;
}
// **************************************************
// BUYS==0
// **************************************************
// there are not buys check the indicators and open new buy order
if(buys == 0 && Time_to_Trade())
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
}
// #019: new button: Stop Next Cyle, which trades normally, until cycle is closed
if(Use_BB || Use_Stoch || Use_RSI || Use_CCI)
{
if(!stopNextCycle && !restAndRealize && Indicators_Buy() && Get_TrendDirection() != OP_SELL)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
if(sells == 0 && both_cycle)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
}
}
else
{
if(!stopNextCycle && !restAndRealize)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
}
}
}
// **************************************************
// BUYS == 1
// **************************************************
if(buys == 1)
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
}
if(!stopNextCycle && !restAndRealize && max_positions > 1)
{
// CASE 1 >>> We reach Stop Loss (grid size)
if(buy_profit[buys - 1] <= CalculateSL(buy_lots[buys - 1], 1))
{
// We are going to open a new order. Volume depends on chosen progression.
NewGridOrder(OP_BUY, false);
}
}
// CASE 2.1 >>> We reach Take Profit so we activate profit lock
if(buy_max_profit == 0 && local_total_buy_profit > CalculateTP(buy_lots[0]))
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * buy_max_profit;
}
// CASE 2.2 >>> Profit locked is updated in real time
if(buy_max_profit > 0 && local_total_buy_profit > buy_max_profit)
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * local_total_buy_profit;
}
// CASE 2.3 >>> If profit falls below profit locked we close all orders
if(buy_max_profit > 0 && buy_close_profit > 0
&& buy_max_profit >= buy_close_profit && local_total_buy_profit < buy_close_profit)
{
// At this point all order are closed.
// Global vars will be updated thanks to UpdateVars() on next start() execution
closeAllBuys();
}
} // if (buys==1)
// **************************************************
// BUYS > 1
// **************************************************
if(buys > 1)
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
}
// CASE 1 >>> We reach Stop Loss (grid size)
if(buy_profit[buys - 1] <= CalculateSL(buy_lots[buys - 1], buys))
{
// We are going to open a new order if we have less than 90 orders opened.
// Volume depends on chosen progression.
if(buys < max_auto_open_positions)
{
if(buys < max_positions && !buy_max_order_lot_open)
{
NewGridOrder(OP_BUY, false);
}
}
}
// CASE 2.1 >>> We reach Take Profit so we activate profit lock
if(buy_max_profit == 0 && progression == 0 && local_total_buy_profit > CalculateTP(buy_lots[0]))
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * buy_max_profit;
if(!buy_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
}
buy_chased = true;
}
}
if(buy_max_profit == 0 && progression == 1 && local_total_buy_profit > buys * CalculateTP(buy_lots[0]))
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * buy_max_profit;
if(!buy_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
buy_chased = true;
}
}
if(buy_max_profit == 0 && progression == 2 && local_total_buy_profit > CalculateTP(buy_lots[buys - 1]))
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * buy_max_profit;
if(!buy_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
}
buy_chased = true;
}
}
if(buy_max_profit == 0 && progression == 3 && local_total_buy_profit > CalculateTP(buy_lots[buys - 1]))
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * buy_max_profit;
if(!buy_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
}
buy_chased = true;
}
}
// CASE 2.2 >>> Profit locked is updated in real time
if(buy_max_profit > 0 && local_total_buy_profit > buy_max_profit)
{
buy_max_profit = local_total_buy_profit;
buy_close_profit = profit_lock * local_total_buy_profit;
}
// CASE 2.3 >>> If profit falls below profit locked we close all orders
if(buy_max_profit > 0 && buy_close_profit > 0 && buy_max_profit >= buy_close_profit
&& local_total_buy_profit < buy_close_profit)
{
// At this point all order are closed.
// Global vars will be updated thanks to UpdateVars() on next start() execution
closeAllBuys();
}
} // if (buys>1)
debugCommentCloseBuys
= "\nbuys will be closed if:\n" +
" - buy max profit: " + DoubleToString(buy_max_profit, 2) + " > buy close profit: " + DoubleToString(buy_close_profit, 2) + " AND \n" +
" - total buy profit: " + DoubleToString(local_total_buy_profit, 2) + " < buy close profit: " + DoubleToString(buy_close_profit, 2) + "\n";
// **************************************************
// SELLS==0
// **************************************************
// there are not sells check the indicators and open new buy order
if(sells == 0 && Time_to_Trade())
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier;
}
// #019: new button: Stop Next Cyle, which trades normally, until cycle is closed
if(Use_BB || Use_Stoch || Use_RSI || Use_CCI)
{
if(!stopNextCycle && !restAndRealize && Indicators_Sell() && Get_TrendDirection() != OP_BUY)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
if(buys == 0 && both_cycle)
{
ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
}
}
}
else
{
if(!stopNextCycle && !restAndRealize)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
}
}
// **************************************************
// SELLS == 1
// **************************************************
if(sells == 1)
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
}
// CASE 1 >>> We reach Stop Loss (grid size)
if(!stopNextCycle && !restAndRealize && max_positions > 1)
{
if(sell_profit[sells - 1] <= CalculateSL(sell_lots[sells - 1], 1))
{
// We are going to open a new order. Volume depends on chosen progression.
NewGridOrder(OP_SELL, false);
}
}
// CASE 2.1 >>> We reach Take Profit so we activate profit lock
if(sell_max_profit == 0 && local_total_sell_profit > CalculateTP(sell_lots[0]))
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
}
// CASE 2.2 >>> Profit locked is updated in real time
if(sell_max_profit > 0 && local_total_sell_profit > sell_max_profit)
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * local_total_sell_profit;
}
// CASE 2.3 >>> If profit falls below profit locked we close all orders
if(sell_max_profit > 0 && sell_close_profit > 0
&& sell_max_profit >= sell_close_profit && local_total_sell_profit < sell_close_profit)
{
// At this point all order are closed.
// Global vars will be updated thanks to UpdateVars() on next start() execution
closeAllSells();
}
} // if (sells==1)
// **************************************************
// SELLS>1
// **************************************************
if(sells > 1)
{
if(Use_ATR)
{
grid_size = ATR_Grid_Size();
take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
}
// CASE 1 >>> We reach Stop Loss (grid size)
if(sell_profit[sells - 1] <= CalculateSL(sell_lots[sells - 1], sells))
{
// We are going to open a new order if we have less than 90 orders opened.
// Volume depends on chosen progression.
if(sells < max_auto_open_positions)
{
if(sells < max_positions && !sell_max_order_lot_open)
{
NewGridOrder(OP_SELL, false);
}
}
}
// CASE 2.1 >>> We reach Take Profit so we activate profit lock
if(sell_max_profit == 0 && progression == 0 && local_total_sell_profit > CalculateTP(sell_lots[0]))
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
if(!sell_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
sell_chased = true;
}
}
if(sell_max_profit == 0 && progression == 1 && local_total_sell_profit > sells * CalculateTP(sell_lots[0]))
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
if(!sell_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
sell_chased = true;
}
}
if(sell_max_profit == 0 && progression == 2 && local_total_sell_profit > CalculateTP(sell_lots[sells - 1]))
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
if(!sell_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
sell_chased = true;
}
}
if(sell_max_profit == 0 && progression == 3 && local_total_sell_profit > CalculateTP(sell_lots[sells - 1]))
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
if(!sell_chased && profit_chasing > 0)
{
if(buys < max_auto_open_positions && buys < max_positions)
{
ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
}
sell_chased = true;
}
}
// CASE 2.2 >>> Profit locked is updated in real time
if(sell_max_profit > 0 && local_total_sell_profit > sell_max_profit)
{
sell_max_profit = local_total_sell_profit;
sell_close_profit = profit_lock * sell_max_profit;
}
// CASE 2.3 >>> If profit falls below profit locked we close all orders
if(sell_max_profit > 0 && sell_close_profit > 0
&& sell_max_profit >= sell_close_profit && local_total_sell_profit < sell_close_profit)
{
// At this point all order are closed.
// Global vars will be updated thanks to UpdateVars() on next start() execution
closeAllSells();
}
} // if (sells>1)
debugCommentCloseSells = "\nsells will be closed if:\n" +
" - sell max profit: " + DoubleToString(sell_max_profit, 2) + " > sell close profit: " + DoubleToString(sell_close_profit, 2) + " AND \n" +
" - total sell profit: " + DoubleToString(local_total_sell_profit, 2) + " < sell close profit: " + DoubleToString(sell_close_profit, 2);
// #017: deal with global vars to save and restore data, while chart is closed or must be restarted by other reason
WriteIniData();
}
//+------------------------------------------------------------------+
//| CheckAccountState
//+------------------------------------------------------------------+
void checkAccountState()
{
accountState = as_green; // init state
codeYellowMsg = ""; // #038: give user info, why account state is yellow or red
codeRedMsg = "";
double myPercentage = 0;
// check if max_positions is reached:
if(buys >= max_positions)
accountState = as_yellow;
if(sells >= max_positions)
accountState = as_yellow;
if(accountState == as_yellow)
codeYellowMsg = "Code YELLOW: Max positions reached";
// #024: calculate, if margin of next position can be paid
if(CalculateNextMargin() > AccountFreeMargin())
{
accountState = as_red;
codeRedMsg = "Code RED: Next M. " + DoubleToString(CalculateNextMargin(), 2) + " > Free M. " + DoubleToString(AccountFreeMargin(), 2);
}
// #025: use equity percentage instead of unpayable position
if((100 - (100 * equity_warning)) / 100 * max_equity > AccountEquity())
{
accountState = as_red;
if(codeRedMsg == "")
{
codeRedMsg = "Code RED: Equ. " + DoubleToStr(AccountEquity(), 2) + " < " + DoubleToStr((100 * equity_warning), 0) + "% of max. equ. " + DoubleToStr(max_equity, 2);
}
else
{
codeRedMsg += "\nand\nEqu. " + DoubleToStr(AccountEquity(), 2) + " < " + DoubleToStr((100 * equity_warning), 0) + "% of max. equ. " + DoubleToStr(max_equity, 2);
}
}
// #026: implement hedge trades, if account state is not green
// #053: paint comment button in status color
switch(accountState)
{
case as_yellow:
SetButtonColor("btnhedgeBuy", colCodeYellow, colFontDark);
SetButtonColor("btnhedgeSell", colCodeYellow, colFontDark);
SetButtonColor("btnCloseLastBuy", colCodeYellow, colFontDark);
SetButtonColor("btnCloseLastSell", colCodeYellow, colFontDark);
SetButtonColor("btnCloseAllBuys", colCodeYellow, colFontDark);
SetButtonColor("btnCloseAllSells", colCodeYellow, colFontDark);
SetButtonColor("btnShowComment", colCodeYellow, colFontDark);
break;
case as_red:
SetButtonColor("btnhedgeBuy", colCodeRed, colFontLight);
SetButtonColor("btnhedgeSell", colCodeRed, colFontLight);
SetButtonColor("btnCloseLastBuy", colCodeRed, colFontLight);
SetButtonColor("btnCloseLastSell", colCodeRed, colFontLight);
SetButtonColor("btnCloseAllBuys", colCodeRed, colFontLight);
SetButtonColor("btnCloseAllSells", colCodeRed, colFontLight);
SetButtonColor("btnShowComment", colCodeRed, colFontLight);
break;
default:
SetButtonColor("btnhedgeBuy", colCodeGreen, colFontLight);
SetButtonColor("btnhedgeSell", colCodeGreen, colFontLight);
SetButtonColor("btnCloseLastBuy", colCodeGreen, colFontLight);
SetButtonColor("btnCloseLastSell", colCodeGreen, colFontLight);
SetButtonColor("btnCloseAllBuys", colCodeGreen, clrRed);
SetButtonColor("btnCloseAllSells", colCodeGreen, clrRed);
SetButtonColor("btnShowComment", colCodeGreen, colFontLight);
break;
}
return;
}
//+------------------------------------------------------------------+
//| CalculateVolume |
//+------------------------------------------------------------------+
double calculateVolume(int positions)
{
int factor = 0;
int i = 0;
if(positions == 0)
return(min_lots);
switch(gs_progression)
{
case 0:
factor = 1;
break;
case 1:
factor = positions;