-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathxLIQUIDEX_v2_mod1.mq4
More file actions
1819 lines (1713 loc) · 71.6 KB
/
Copy pathxLIQUIDEX_v2_mod1.mq4
File metadata and controls
1819 lines (1713 loc) · 71.6 KB
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
//+------------------------------------------------------------------+
//| xLIQUIDEX_v2_mod1.mq4 |
//| Copyright � 2013 - 2016,Scratchsoft International |
//| info@sbginter.com |
//| Apache License |
//| Version 2.0, January 2004 |
//| http://www.apache.org/licenses/ |
//| |
//+------------------------------------------------------------------+
#property copyright "xLiquidex_v2_mod1"
#property link "info@sbginter.com"
//---- constant values ------------------------------------------------------------------------+
#define Account_Number 898264 // write here the number of account; 0 = does not check the number of account
#define IndicatorFileName_KC "Keltner Channels"
//---- external parameters --------------------------------------------------------------------+
extern string DispEquityProtection = "if true, then the expert will protect the account equity to the percent specified";
extern bool EquityProtection = true; // if true, then the expert will protect the account equity to the percent specified
extern string AverageEquityProtection ="percent of the account to protect on a set of trades";
extern int AccountEquityPercentProtection= 75; // percent of the account to protect on a set of trades
extern bool UseMM = true; // enable/disable auto-calculation for size of lots: false = constant size of lots (value of parameter "Lots"); true = calculate size of lots by percent from FreeMargin (parameter "Risk")
extern double Lots = 0.01; // size of lots (used if UseMM = false)
extern double MinLots = 0.01;
extern double MaxLots = 100000.0;
extern double Risk = 3.0;
extern int BarAndMA_Mode = 0; //2; // (0-3) mode for rule "bullish(bearish) bar should be above(below) MA": 0 = does not use this rule; 1 = Close of bar should be above(below) MA; 2 = body of bar should be above(below) MA; 3 = Low(High) of bar should be above(below) MA
extern int RangeFilter = 10; // (amount pips) minimum body of candle for trading signal
extern double StopLoss = 0; // (amount pips) stop-loss; 0 = without stop-loss
extern double TakeProfit = 10; // (amount pips) take profit; 0 = without take profit
extern double MoveToBE = 5; // (amount pips) profit when move the stop-loss level to opening price; 0 = without move to BE (option is disabled)
extern double MoveToBE_Offset = 2; // (amount pips) offset of the new level stop-loss from the opening price of order, positive_value = offset to side of profit, negative_value = offset to side of loss
extern int TrailingLimit = 3; // (amount pips) distance to pending order
extern int TrailingDistance = 1; // (amount pips) trailing stop; 0 = without trailing-stop
extern int MAPeriod = 7;
extern int MAShift = 0;
extern int MAMethod = MODE_LWMA; // (0-3)
extern double MaxSpreadWithCommission = 20.0; // (amount pips)
extern double DefaultCommisionPoints = 0; // (amount pips)
extern string RangeFilterNote = "H-S 0-0: 250 0-1: 300 1-0: 80 1-1: 250";
extern string MAMethodNote = "SMA: 0 EMA: 1 SMMA: 2 LWMA 3";
extern int Slippage = 3; // (amount pips) maximum price slippage at open and close orders
extern int MagicNumber = 41403;
extern string TradeComment = "Liquidex_MKH-M15";
extern color ColorBuy = clrLime; // color arrows of Buy-orders
extern color ColorSell = clrOrange; // color arrows of Sell-orders
extern bool ShowComment = true; // enable/disable show comment on chart
extern bool WriteDebugLog = false; // enable/disable write to log the debug information
extern string ___Keltner_Channel____ = "---------------------------------------------";
extern bool UseFilterKeltnerChannel = false; // true = use indicator "Keltner Channels"; false = does not use indicator "Keltner Channels"
extern int KC_Period = 6; //12; // parameter for indicator "Keltner Channels"
//----- global variables ----------------------------------------------------------------------+
extern string partInRange = "sur EURJPY par de trades entre 23h et 2 heures du mat";
extern int EntryHourFrom = 2;
extern int EntryHourTo = 24;
extern int FridayEndHour = 22;
extern string part_iVAR = " Ivar pour supprimer les fausses entrees periods = 5 par def ";
extern int TimeFrameiVAR = 1;
extern int periods = 5;
extern double a1 = 0.01;
extern double a2 = 0.01;
extern double a3 = 0.55;
extern double a4 = 0.54;
//|------------------------------------------
// TICKWARE
//|__________________________________________
extern int TicksPeriod = 33;
extern int Length = 33; //14; //Period of evaluation for AVG Bears and Bulls by default 14
extern int MA_Mode = 3; //2; //MA Mode: 0-SMA,1-EMA,2-Wilder(SMMA),3-LWMA
extern int NumTicks = 0; //TimeFrame in ticks (=0 if NumSecs > 0)
extern int NumSecs = 70; // 0; //20; //TimeFrame in secs (=0 if NumTicks > 0)
extern string DispMaxBars = " MaxBars is matrix 'size, correlated to volatility check out";
extern int MaxBars = 350 ;// 150; //Max Number of Bars
int maxsize = 1200; // 1200 *0.2 (minimal time) gives a Time frame 4MN
double Ticks[];
double Bulls[];
double Bears[];
double AvgBulls[];
double AvgBears[];
double tRSI;
extern bool UseRSI = false;
int RSIdirection = 0;
double Hi;
double Lo;
double tOpen;
double tClose;
int tickCounter=0, barCounter, pSecs;
datetime pTime;
string short_name, t;
int LastTm;
double max = -1000000.0;
double min = 1000000.0;
double stoplevel, freezelevel;
string message;
////////////////////////////////////////////////////
int slippage;
int digits;
double point;
int my_digits;
double my_point;
int pips_digits;
int lots_digits;
double minlots;
double maxlots;
string symbol;
double risk;
double maxSpreadWithCommission;
double trailingLimit;
double trailingDistance;
double rangeFilter;
bool gotCommissionPointsFromTrade;
double commissionPoints;
double spreadHistory[30];
int spreadHistoryCount = 0;
string objname_hline;
bool is_testing;
double main_sl;
double main_tp;
double main_be_profit;
double main_be_offset;
static int account_number;
static bool is_ok;
int OnInit()
{
ArrayInitialize(spreadHistory,0.0);
is_testing = IsTesting();
symbol = Symbol();
digits = MarketInfo(symbol,MODE_DIGITS);
point = MarketInfo(symbol,MODE_POINT);
if(digits == 0)
{
my_point = 1.0;
my_digits = 0;
}
else
{
if(digits < 2)
{
my_point = 0.1;
my_digits = 1;
}
else
{
if(digits < 4)
{
my_point = 0.01;
my_digits = 2;
}
else
{
my_point = 0.0001;
my_digits = 4;
}
}
}
if(StringFind(symbol,"XAU") >= 0 || StringFind(symbol,"GOLD") >= 0)
{
my_point = 0.1;
my_digits = 1;
}
else
{
if(StringFind(symbol,"XAG") >= 0 || StringFind(symbol,"SILVER") >= 0)
{
my_point = 0.01;
my_digits = 2;
}
}
pips_digits = digits - my_digits;
double correction = MathPow(10,pips_digits);
slippage = Slippage * correction;
stoplevel = NormalizeDouble(MarketInfo(symbol,MODE_STOPLEVEL)*MarketInfo(symbol,MODE_POINT),digits);
freezelevel = MarketInfo(symbol, MODE_FREEZELEVEL);
lots_digits = MathLog(MarketInfo(symbol,MODE_LOTSTEP)) / MathLog(0.1);
minlots = NormalizeDouble(MathMax(MinLots,MarketInfo(symbol,MODE_MINLOT)),lots_digits);
maxlots = NormalizeDouble(MathMin(MaxLots,MarketInfo(symbol,MODE_MAXLOT)),lots_digits);
Lots = NormalizeDouble(Lots,lots_digits);
if(Lots < minlots) Lots = minlots;
else if(Lots > maxlots) Lots = maxlots;
if(WriteDebugLog)
{
Print(StringConcatenate("Digits: ",DoubleToStr(digits,0),", Point: ",DoubleToStr(point,digits)));
Print(StringConcatenate("LotsDigits: ",DoubleToStr(lots_digits,0),", MinLots: ",DoubleToStr(minlots,lots_digits),", MaxLots: ",DoubleToStr(maxlots,lots_digits)));
}
risk = Risk / 100.0;
main_sl = NormalizeDouble(my_point * StopLoss, digits);
main_tp = NormalizeDouble(my_point * TakeProfit, digits);
main_be_profit = NormalizeDouble(my_point * MoveToBE, digits);
main_be_offset = NormalizeDouble(my_point * MoveToBE_Offset, digits);
maxSpreadWithCommission = NormalizeDouble(my_point * MaxSpreadWithCommission,digits+1);
trailingLimit = NormalizeDouble(my_point * TrailingLimit, digits);
trailingDistance = NormalizeDouble(my_point * TrailingDistance, digits);
rangeFilter = NormalizeDouble(my_point * RangeFilter, digits);
commissionPoints = NormalizeDouble(my_point * DefaultCommisionPoints, digits+1);
gotCommissionPointsFromTrade = false;
if(BarAndMA_Mode < 0 || BarAndMA_Mode > 3) BarAndMA_Mode = 0;
account_number = Account_Number;
objname_hline = StringConcatenate("last_history_check_",symbol,strtf(Period()),"_",DoubleToStr(MagicNumber,0));
// -------------------------------------------
// TICK WARE RSI
pTime = Time[0];
pSecs = TimeCurrent();
maxsize = MaxBars;
ArraySetAsSeries(Ticks, false);
ArrayResize(Ticks, maxsize+1);
ArraySetAsSeries(Ticks,true);
ArraySetAsSeries(Bulls, false);
ArrayResize(Bulls, maxsize+1);
ArraySetAsSeries(Bulls,true);
ArraySetAsSeries(Bears, false);
ArrayResize(Bears, maxsize+1);
ArraySetAsSeries(Bears,true);
ArraySetAsSeries(AvgBulls, false);
ArrayResize(AvgBulls, maxsize+1);
ArraySetAsSeries(AvgBulls,true);
ArraySetAsSeries(AvgBears, false);
ArrayResize(AvgBears, maxsize+1);
ArraySetAsSeries(AvgBears,true);
//---- get commission ----------------------------------------------------------------------+
if(!gotCommissionPointsFromTrade)
{
for(int i=OrdersHistoryTotal()-1; i>=0; i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
if(OrderProfit() == 0.0) continue;
if(OrderSymbol() != symbol) continue;
double order_open_price = NormalizeDouble(OrderOpenPrice(), digits);
double order_close_price = NormalizeDouble(OrderClosePrice(),digits);
if(order_open_price == order_close_price) continue;
double pip_rate = MathAbs(OrderProfit() / (order_close_price - order_open_price));
commissionPoints = (0.0 - OrderCommission()) / pip_rate;
if(WriteDebugLog) Print(StringConcatenate("CommissionPoints: ",DoubleToStr(commissionPoints,digits)));
gotCommissionPointsFromTrade = true;
break;
}
}
return(INIT_SUCCEEDED);
}
////////////////////////
bool InRange()
{
bool Result=false;
if((EntryHourFrom<=EntryHourTo && Hour()>=EntryHourFrom && Hour()<=EntryHourTo) ||
(EntryHourFrom>EntryHourTo && (Hour()>=EntryHourFrom || Hour()<=EntryHourTo)))
Result=true;
return(Result);
}
/////////////
bool IsSafetyForTrade()
{
bool Result=false;
// if (DayOfWeek() == 0) return(Result);
if(DayOfWeek()!=5 || FridayEndHour<0 || DayOfWeek()!= 0 ||
(DayOfWeek()==5 && EntryHourFrom<=EntryHourTo && Hour()<FridayEndHour) ||
(DayOfWeek()==5 && EntryHourFrom>EntryHourTo && FridayEndHour>=EntryHourFrom && Hour()<FridayEndHour) ||
(DayOfWeek()==5 && EntryHourFrom>EntryHourTo && FridayEndHour<EntryHourFrom && Hour()<FridayEndHour) ||
(DayOfWeek()==5 && EntryHourFrom>EntryHourTo && FridayEndHour<EntryHourFrom && Hour()>=FridayEndHour && Hour()>=EntryHourFrom))
Result=true;
return(Result);
}
////////////////////////
bool iVAR()
{
bool Result=false;
double iVAR_1=iCustom(symbol,TimeFrameiVAR,"iVAR_nmc",periods,0,1);
double iVAR_2=iCustom(symbol,TimeFrameiVAR,"iVAR_nmc",periods,0,2);
if(iVAR_2>a1 && iVAR_1>a2 && iVAR_2<a3 && iVAR_1<a4)
Result=true;
return(Result);
}
bool isNewBar()
{
bool res=false;
if (Time[0]!=pTime)
{
res=true;
pTime=Time[0];
}
return(res);
}
void OnDeinit(const int reason)
{
if(ShowComment) Comment("");
return;
}
void OnTick()
{
int acc_num = AccountNumber();
int total_orders, i, signal_delete;
int order_type;
double order_open_price,order_close_price;
// is_ok is nothing
is_ok = account_number == 0 || acc_num == 0 || acc_num == account_number;
//STEP 1
// There is no time to calculate commission here
// but Account equity protection is a good looking up
if (EquityProtection && AccountEquity() <= AccountBalance()*AccountEquityPercentProtection/100)
{
message = message + "\nClosing all orders and stop trading because account money protection activated.";
Print("Closing all orders and stop trading because account money protection activated. Balance: ",AccountBalance()," Equity: ", AccountEquity());
Comment("Closing orders because account equity protection was triggered. Balance: ",AccountBalance()," Equity: ", AccountEquity());
// ContinueOpening=False;
return ;
}
// STEP 2
// Before doing anything else to this :
// Close all pending trades if outside trading hours
if(WriteDebugLog)
{
Print(" STEP 2" );
}
total_orders = OrdersTotal()-1;
if ( !InRange() || IsSafetyForTrade() )
{
for (int cnt = total_orders;cnt>0;cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
order_type = OrderType();
if ((OrderSymbol()==symbol && OrderMagicNumber() == MagicNumber) )
{
if (order_type==OP_SELLLIMIT || order_type==OP_BUYLIMIT || order_type==OP_BUYSTOP || order_type==OP_SELLSTOP)
{
signal_delete = OrderDelete(OrderTicket());
}
}
}
}
}
// STEP 3
// MOVING NEW BID INSIDE MATRIX
// Voir comment mettre la courbe des ticks dans une matrice raffinee
// Ici c est la base de la logique.
// faut il lisser la courbe avant de faire un iMAOnArray dessus ?
// je ferais une version avec fourier ou bien IHP21
// sinon, un slope direction line .. a voir
if(WriteDebugLog)
{
Print(" STEP 3" );
}
// TICK RSI
tickCounter++;
bool tcond = false;
if(NumTicks > 0 && NumSecs == 0)
tcond = tickCounter > 0 && tickCounter % NumTicks == 0;
if(NumTicks == 0 && NumSecs > 0)
tcond = TimeCurrent() >= pSecs + NumSecs;
if(tcond)
{
barCounter ++;
double oldbid = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
if(!isNewBar())
{
ShiftArray(0);
Ticks[0] = oldbid;
tickCounter = 0;
}
RefreshRates();
if (NormalizeDouble(MarketInfo(symbol,MODE_BID),digits) != oldbid )
{
tickCounter ++;
Ticks[barCounter] = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
}
Hi = TickHighest(Ticks,TicksPeriod);
Lo = TickLowest(Ticks,TicksPeriod);
if(NumSecs > 0) pSecs = TimeCurrent();
}
if(barCounter>=1)
{
oldbid = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
if(isNewBar())
{
ShiftArray(1);
Ticks[0] = oldbid;
barCounter = 0; // for simplification
}
RefreshRates();
if (NormalizeDouble(MarketInfo(symbol,MODE_BID),digits) != oldbid )
{
barCounter ++;
Ticks[barCounter] = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
}
Hi = TickHighest(Ticks,TicksPeriod);
Lo = TickLowest(Ticks,TicksPeriod);
}
if(barCounter >= MaxBars)
{
barCounter = 0;
}
Bulls[0] = MathAbs(Ticks[0]-Ticks[1])+(Ticks[0]-Ticks[1]);
Bears[0] = MathAbs(Ticks[0]-Ticks[1])-(Ticks[0]-Ticks[1]);
int len = Length;
if(MA_Mode == 2) len = 2*Length - 1;
if(barCounter > len)
{
if(MA_Mode == 0)
{
AvgBulls[0] = TickSMA(Bulls, len);
AvgBears[0] = TickSMA(Bears, len);
}
else
if(MA_Mode == 1 || MA_Mode == 2)
{
if(barCounter == len+1)
{
AvgBulls[0] = TickSMA(Bulls, len);
AvgBears[0] = TickSMA(Bears, len);
}
else
if(barCounter > len+1)
{
AvgBulls[0] = TickEMA(Bulls, AvgBulls, len);
AvgBears[0] = TickEMA(Bears, AvgBears, len);
}
}
else
if(MA_Mode == 3)
{
AvgBulls[0] = TickLWMA(Bulls, len);
AvgBears[0] = TickLWMA(Bears, len);
}
if (AvgBulls[0] != 0)
tRSI = 100.0/(1+AvgBears[0]/AvgBulls[0]);
else
tRSI = 0.00000001;
}
// STEP 4
//---- calculate average spread ------------------------------------------------------------+
if(WriteDebugLog)
{
Print(" STEP 4" );
}
double spread = NormalizeDouble(Ask - Bid,digits);
ArrayCopy(spreadHistory,spreadHistory,0,1,29);
spreadHistory[29] = spread;
if(spreadHistoryCount < 30) spreadHistoryCount++;
double spreadHistorySum = 0.0;
for(i=29; i>=30-spreadHistoryCount; i--) spreadHistorySum += spreadHistory[i];
double spreadAverage = spreadHistorySum / spreadHistoryCount;
//double askWithCommission = NormalizeDouble(Ask + commissionPoints,digits);
//double bidWithCommission = NormalizeDouble(Bid - commissionPoints,digits);
double spreadAverageWithCommission = NormalizeDouble(spreadAverage + commissionPoints,digits+1);
// STEP 5
//---- detect trading signal ---------------------------------------------------------------+
/////////////////////////////////////////////
if(WriteDebugLog)
{
Print(" STEP 5" );
}
double stddev_ema0 = iStdDev(symbol, 0, 20, 0, MODE_EMA, PRICE_CLOSE, 1);
double xhigh = iHigh(symbol, 0, 0);
double xlow = iLow(symbol, 0, 0);
double xopen = iOpen(symbol, 0, 0);
//double maLow = iMA(NULL, 0, MAPeriod, MAShift, MAMethod, PRICE_LOW, 0);
//double maHigh = iMA(NULL, 0, MAPeriod, MAShift, MAMethod, PRICE_HIGH, 0);
//-----------------------
// ORIG
//-----------------------
double ma = NormalizeDouble(iMA(symbol,0,MAPeriod,MAShift,MAMethod,PRICE_CLOSE,0),digits);
double close = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
double open = NormalizeDouble(iOpen(symbol,0,0),digits);
double range = NormalizeDouble(MathAbs(open - close),digits);
// STEP 6
//--------- direction -------------------------------------
if(WriteDebugLog)
{
Print(" STEP 6" );
}
int bar_direction = 0;
if(close > open) bar_direction++;
else if(close < open) bar_direction--;
bar_direction /= is_ok;
if(UseFilterKeltnerChannel)
{
double kc_upper = NormalizeDouble(iCustom(NULL,0,IndicatorFileName_KC,KC_Period,0,0),digits);
double kc_lower = NormalizeDouble(iCustom(NULL,0,IndicatorFileName_KC,KC_Period,2,0),digits);
}
if(BarAndMA_Mode == 0)
{
bool barandma_allow_buy = true;
bool barandma_allow_sell = true;
}
else
{
switch(BarAndMA_Mode)
{
case 1:
barandma_allow_buy = close > ma;
barandma_allow_sell = close < ma;
break;
case 2:
barandma_allow_buy = open > ma && close > ma;
barandma_allow_sell = open < ma && close < ma;
break;
case 3:
barandma_allow_buy = NormalizeDouble(iLow (NULL,0,0),digits) > ma;
barandma_allow_sell = NormalizeDouble(iHigh(NULL,0,0),digits) < ma;
break;
}
}
if (UseRSI)
{
if (Bid < ma && open>Bid && tRSI < 50 )
{
RSIdirection = -1; // SELL
}
else
if (Bid > ma && open<Bid && tRSI > 50 )
{
RSIdirection = +1; // BUY
}
}
// STEP 7
/////////// DIRECTION CALCULATING
// THE MOST IMPORTANT
if(WriteDebugLog)
{
Print(" STEP 7 RSIdirection=",RSIdirection );
}
int direction = 0;
if(range > rangeFilter)
{
if(close < ma && bar_direction < 0)
{
if( (!UseFilterKeltnerChannel || close < kc_lower)
&& (!UseRSI || RSIdirection < 0))
direction++; // SELL
}
else
{
if(close > ma && bar_direction > 0)
{
if( (!UseFilterKeltnerChannel || close > kc_upper)
&& (!UseRSI || RSIdirection > 0)) direction--; // BUY
}
}
}
direction /= is_ok;
// STEP 8
//---- place pending order immediately after closing previous order ------------------------+
if(WriteDebugLog)
{
Print(" STEP 8 direction=",direction );
}
int total_history_orders = OrdersHistoryTotal()-1;
for( i = total_history_orders; i>=0; i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
if(OrderMagicNumber() != MagicNumber
|| OrderSymbol() != symbol
|| OrderType() > OP_SELL )
continue;
datetime last_history_check = GetHLineValue(objname_hline);
if(OrderCloseTime() < last_history_check) break;
if(OrderCloseTime() > last_history_check)
{
if(direction != 0)
{
if(direction < 0)
{
if(barandma_allow_buy)
{
order_open_price = NormalizeDouble(MarketInfo(symbol,MODE_ASK) + trailingLimit,digits);
double order_lots = GetLots();
int ticket = OrderSendEx(symbol,OP_BUYSTOP,order_lots,order_open_price,slippage,0.0,0.0,TradeComment,MagicNumber,0,ColorBuy);
if(ticket < 0) Print(StringConcatenate("BUYSTOP Send Error: LT = ",DoubleToStr(order_lots,lots_digits)," OP = ",DoubleToStr(order_open_price,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
}
else
{
if(barandma_allow_sell)
{
order_open_price = NormalizeDouble(MarketInfo(symbol,MODE_BID) - trailingLimit,digits);
order_lots = GetLots();
ticket = OrderSendEx(symbol,OP_SELLSTOP,order_lots,order_open_price,slippage,0.0,0.0,TradeComment,MagicNumber,0,ColorSell);
if(ticket < 0) Print(StringConcatenate("SELLSTOP Send Error: LT = ",DoubleToStr(order_lots,lots_digits)," OP = ",DoubleToStr(order_open_price,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
}
}
DrawLine(objname_hline,TimeCurrent());
break;
}
}
// STEP 9
//---- watch orders ------------------------------------------------------------------------+
if(WriteDebugLog)
{
Print(" STEP 9 direction=",direction );
}
int num_orders = 0;
//double stoplevel = NormalizeDouble(MarketInfo(symbol,MODE_STOPLEVEL)*point,digits);
total_orders = OrdersTotal()-1;
for(i= total_orders ; i>=0; i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
if(OrderMagicNumber() != MagicNumber
||OrderSymbol() != symbol
|| OrderSymbol() != symbol)
continue;
order_type = OrderType();
if(order_type == OP_BUYLIMIT || order_type == OP_SELLLIMIT)
continue;
num_orders++;
order_open_price = NormalizeDouble(OrderOpenPrice(), digits);
order_close_price = NormalizeDouble(OrderClosePrice(),digits);
double order_stop_loss = NormalizeDouble(OrderStopLoss(), digits);
double order_take_profit = NormalizeDouble(OrderTakeProfit(),digits);
switch(order_type)
{
case OP_BUY:
if(StopLoss > 0.0 || TakeProfit > 0.0)
{
bool to_modify_sl = false;
if(StopLoss > 0.0 && order_stop_loss == 0.0)
{
double new_stop_loss = NormalizeDouble(order_open_price - main_sl,digits);
if(NormalizeDouble(order_close_price - new_stop_loss,digits) >= stoplevel) to_modify_sl = true;
else new_stop_loss = order_stop_loss;
}
else new_stop_loss = order_stop_loss;
bool to_modify_tp = false;
if(TakeProfit > 0.0 && order_take_profit == 0.0)
{
double new_take_profit = NormalizeDouble(order_open_price + main_tp,digits);
if(NormalizeDouble(new_take_profit - order_close_price,digits) >= stoplevel) to_modify_tp = true;
else new_take_profit = order_take_profit;
}
else new_take_profit = order_take_profit;
if(to_modify_sl || to_modify_tp)
{
bool no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss,new_take_profit,0,ColorBuy);
if(!no_error) Print(StringConcatenate("BUY Modify (SL/TP) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," TP = ",DoubleToStr(new_take_profit,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
if(MoveToBE > 0.0)
{
double new_stop_loss_be = NormalizeDouble(order_open_price + main_be_offset,digits);
if(order_stop_loss == 0.0 || new_stop_loss_be > order_stop_loss)
{
double order_profit = NormalizeDouble(order_close_price - order_open_price,digits);
if(order_profit >= main_be_profit)
{
if(order_profit >= stoplevel)
{
no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss_be,order_take_profit,0,ColorBuy);
if(!no_error) Print(StringConcatenate("BUY Modify (BE) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss_be,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
}
}
if(TrailingDistance > 0)
{
new_stop_loss = NormalizeDouble(order_close_price - trailingDistance,digits);
if(order_stop_loss == 0.0 || new_stop_loss > order_stop_loss)
{
no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss,order_take_profit,0,ColorBuy);
if(!no_error) Print(StringConcatenate("BUY Modify (TS) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
break;
case OP_SELL:
if(StopLoss > 0.0 || TakeProfit > 0.0)
{
to_modify_sl = false;
if(StopLoss > 0.0 && order_stop_loss == 0.0)
{
new_stop_loss = NormalizeDouble(order_open_price + main_sl,digits);
if(NormalizeDouble(new_stop_loss - order_close_price,digits) >= stoplevel) to_modify_sl = true;
else new_stop_loss = order_stop_loss;
}
else new_stop_loss = order_stop_loss;
to_modify_tp = false;
if(TakeProfit > 0.0 && order_take_profit == 0.0)
{
new_take_profit = NormalizeDouble(order_open_price - main_tp,digits);
if(NormalizeDouble(order_close_price - new_take_profit,digits) >= stoplevel) to_modify_tp = true;
else new_take_profit = order_take_profit;
}
else new_take_profit = order_take_profit;
if(to_modify_sl || to_modify_tp)
{
no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss,new_take_profit,0,ColorSell);
if(!no_error) Print(StringConcatenate("SELL Modify (SL/TP) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," TP = ",DoubleToStr(new_take_profit,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
if(MoveToBE > 0.0)
{
new_stop_loss_be = NormalizeDouble(order_open_price - main_be_offset,digits);
if(order_stop_loss == 0.0 || new_stop_loss_be < order_stop_loss)
{
order_profit = NormalizeDouble(order_open_price - order_close_price,digits);
if(order_profit >= main_be_profit)
{
if(order_profit >= stoplevel)
{
no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss_be,order_take_profit,0,ColorSell);
if(!no_error) Print(StringConcatenate("SELL Modify (BE) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss_be,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
}
}
if(TrailingDistance > 0)
{
new_stop_loss = NormalizeDouble(order_close_price + trailingDistance,digits);
if(order_stop_loss == 0.0 || new_stop_loss < order_stop_loss)
{
no_error = OrderModifyEx(OrderTicket(),order_open_price,new_stop_loss,order_take_profit,0,ColorSell);
if(!no_error) Print(StringConcatenate("SELL Modify (TS) Error: OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
break;
}
}
break;
case OP_BUYSTOP:
if(!barandma_allow_buy)
{
Print("BarAndMA_Mode: to delete order");
OrderDeleteEx(OrderTicket(),ColorBuy);
break;
}
double current_price = NormalizeDouble(MarketInfo(symbol,MODE_ASK),digits);
double new_open_price = NormalizeDouble(current_price + trailingLimit,digits);
if(new_open_price < order_open_price)
{
no_error = OrderModifyEx(OrderTicket(),new_open_price,order_stop_loss,order_take_profit,0,ColorBuy);
if(!no_error) Print(StringConcatenate("BUYSTOP Modify Error: OP = ",DoubleToStr(new_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
break;
case OP_SELLSTOP:
if(!barandma_allow_sell)
{
Print("BarAndMA_Mode: to delete order");
OrderDeleteEx(OrderTicket(),ColorSell);
break;
}
current_price = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits);
new_open_price = NormalizeDouble(current_price - trailingLimit,digits);
if(new_open_price > order_open_price)
{
no_error = OrderModifyEx(OrderTicket(),new_open_price,order_stop_loss,order_take_profit,0,ColorSell);
if(!no_error) Print(StringConcatenate("SELLSTOP Modify Error: OP = ",DoubleToStr(new_open_price,digits)," SL = ",DoubleToStr(new_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
break;
}
}
//---- open position -----------------------------------------------------------------------+
if(num_orders == 0 && direction != 0 && spreadAverageWithCommission <= maxSpreadWithCommission)
{
if(direction < 0)
{
order_open_price = MarketInfo(symbol,MODE_ASK); // NormalizeDouble(MarketInfo(symbol,MODE_ASK) + trailingLimit,digits);
order_lots = GetLots();
ticket = OrderSendEx(symbol,OP_BUY,order_lots,order_open_price,slippage,0.0,0.0,TradeComment,MagicNumber,0,ColorBuy);
if(ticket < 0) Print(StringConcatenate("BUY Send Error: LT = ",DoubleToStr(order_lots,lots_digits)," OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(order_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
else
{
order_open_price = MarketInfo(symbol,MODE_BID); // NormalizeDouble(MarketInfo(symbol,MODE_BID) - trailingLimit,digits);
order_lots = GetLots();
ticket = OrderSendEx(symbol,OP_SELL,order_lots,order_open_price,slippage,0.0,0.0,TradeComment,MagicNumber,0,ColorSell);
if(ticket < 0) Print(StringConcatenate("SELL Send Error: LT = ",DoubleToStr(order_lots,lots_digits)," OP = ",DoubleToStr(order_open_price,digits)," SL = ",DoubleToStr(order_stop_loss,digits)," Bid = ",DoubleToStr(Bid,digits)," Ask = ",DoubleToStr(Ask,digits)));
}
}
//---- show comment ------------------------------------------------------------------------+
if(ShowComment || WriteDebugLog)
{
if(!UseFilterKeltnerChannel) string comm_kc = "";
else comm_kc = StringConcatenate("Keltner: upper = ",DoubleToStr(kc_upper,digits),", lower = ",DoubleToStr(kc_lower,digits),"\n");
message = StringConcatenate("Copyrighted by www.sbginter.com & www.eaihub.com\n",
"Contact us : info@sbginter.com / info@eaihub.com\n",
"Licence type : Opensource\n",
"Account Name : ",AccountName(),"\n",
"Account Number : ",DoubleToStr(AccountNumber(),0),"\n",
"AvgSpread : ",DoubleToStr(spreadAverage,digits),"\n",
"Balance : ",DoubleToStr(AccountBalance(),2)," $\n",
"Equity : ",DoubleToStr(AccountEquity(),2)," $\n",
"Commission rate : ",DoubleToStr(commissionPoints,digits+1),"\n",
"Real avg. spread : ",DoubleToStr(spreadAverageWithCommission,digits+1),"\n",
"MA = ",DoubleToStr(ma,digits),"\n",
"Range = ",DoubleToStr(range/my_point,pips_digits)," pips\n",
comm_kc
);
if(spreadAverageWithCommission > maxSpreadWithCommission)
{
message = StringConcatenate(message,"\n",
"Robot is OFF :: Real avg. spread is too high for this scalping strategy ( ",DoubleToStr(spreadAverageWithCommission,digits+1)," > ",DoubleToStr(maxSpreadWithCommission,digits+1)," )"
);
}
if(ShowComment) Comment(message);
if(WriteDebugLog) if(num_orders != 0 || direction != 0) PrintLineLine(message);
}
return;
}
//---- PrintLineLine --------------------------------------------------------------------------+
void PrintLineLine(string text)
{
int start_pos;
int position = -1;
while(position < StringLen(text))
{
start_pos = position + 1;
position = StringFind(text,"\n",start_pos);
if(position == -1)
{
Print(StringSubstr(text,start_pos));
return;
}
Print(StringSubstr(text,start_pos,position-start_pos));
}
}
//---- DrawLine -------------------------------------------------------------------------------+
void DrawLine(string sName, double dPrice, color cLineClr = CLR_NONE)
{
if(ObjectFind(sName) == -1) ObjectCreate(sName,OBJ_HLINE,0,0,0);
ObjectSet(sName,OBJPROP_PRICE1,dPrice);
ObjectSet(sName,OBJPROP_COLOR, cLineClr);
}
//---- GetHLineValue --------------------------------------------------------------------------+
double GetHLineValue(string name)
{
if(ObjectFind(name) == -1) return(-1);
else return(ObjectGet(name,OBJPROP_PRICE1));
}
//---- strtf ----------------------------------------------------------------------------------+
string strtf(int tf)
{
switch(tf)
{
case PERIOD_M1: return("M1");
case PERIOD_M5: return("M5");
case PERIOD_M15: return("M15");
case PERIOD_M30: return("M30");
case PERIOD_H1: return("H1");
case PERIOD_H4: return("H4");
case PERIOD_D1: return("D1");
case PERIOD_W1: return("W1");
case PERIOD_MN1: return("MN1");
default: return("Unknown timeframe");
}
}
//---- GetLots --------------------------------------------------------------------------------+
double GetLots()
{
if(!UseMM) double lots = Lots;
else
{
double money = AccountBalance() * AccountLeverage() * risk;
lots = NormalizeDouble(money / MarketInfo(symbol,MODE_LOTSIZE),lots_digits);
}
if(lots < minlots) lots = minlots;
else if(lots > maxlots) lots = maxlots;
return(lots);
}
//---- ErrorDescription -----------------------------------------------------------------------+
string ErrorDescription(int error_code)
{
switch(error_code)
{
case 0:
case 1: string error_string="no error"; break;
case 2: error_string="common error"; break;
case 3: error_string="invalid trade parameters"; break;
case 4: error_string="trade server is busy"; break;
case 5: error_string="old version of the client terminal"; break;
case 6: error_string="no connection with trade server"; break;
case 7: error_string="not enough rights"; break;
case 8: error_string="too frequent requests"; break;
case 9: error_string="malfunctional trade operation (never returned error)"; break;
case 64: error_string="account disabled"; break;
case 65: error_string="invalid account"; break;
case 128: error_string="trade timeout"; break;
case 129: error_string="invalid price"; break;
case 130: error_string="invalid stops"; break;
case 131: error_string="invalid trade volume"; break;
case 132: error_string="market is closed"; break;
case 133: error_string="trade is disabled"; break;
case 134: error_string="not enough money"; break;
case 135: error_string="price changed"; break;
case 136: error_string="off quotes"; break;
case 137: error_string="broker is busy (never returned error)"; break;
case 138: error_string="requote"; break;
case 139: error_string="order is locked"; break;
case 140: error_string="long positions only allowed"; break;
case 141: error_string="too many requests"; break;
case 145: error_string="modification denied because order too close to market"; break;
case 146: error_string="trade context is busy"; break;
case 147: error_string="expirations are denied by broker"; break;
case 148: error_string="amount of open and pending orders has reached the limit"; break;
case 149: error_string="hedging is prohibited"; break;
case 150: error_string="prohibited by FIFO rules"; break;
case 4000: error_string="no error (never generated code)"; break;
case 4001: error_string="wrong function pointer"; break;
case 4002: error_string="array index is out of range"; break;
case 4003: error_string="no memory for function call stack"; break;
case 4004: error_string="recursive stack overflow"; break;
case 4005: error_string="not enough stack for parameter"; break;
case 4006: error_string="no memory for parameter string"; break;
case 4007: error_string="no memory for temp string"; break;
case 4008: error_string="not initialized string"; break;
case 4009: error_string="not initialized string in array"; break;
case 4010: error_string="no memory for array\' string"; break;
case 4011: error_string="too long string"; break;
case 4012: error_string="remainder from zero divide"; break;
case 4013: error_string="zero divide"; break;
case 4014: error_string="unknown command"; break;
case 4015: error_string="wrong jump (never generated error)"; break;
case 4016: error_string="not initialized array"; break;
case 4017: error_string="dll calls are not allowed"; break;