forked from vzhomeexperiments/Include
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DSS_Functions.mqh
2955 lines (2552 loc) · 140 KB
/
DSS_Functions.mqh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//+-------------------------------------------------------------------+
//| DSS_Functions.mqh |
//| Copyright 2021, Vladimir Zhbanko |
//+-------------------------------------------------------------------+
#property copyright "Copyright 2021, Vladimir Zhbanko"
#property link "https://vladdsm.github.io/myblog_attempt/"
#property strict
// Functions library to DSS_Bot, DSS_Rule, DSS_Hybrid robots
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//| FUNCTIONS LIBRARY
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
Content:
1) EntrySignal
2.1) ExitSignal
2.2) ExitSignalOnTimerMagic
2.3) ExitSignalOnTimerTicket
2.4) ExitSignalOnAI
3) GetLot
4) CheckLot
5) CountPosOrders
6) IsMaxPositionsReached
7) OpenPositionMarket
8) OpenPositionPending
9) CloseOrderPosition
10) GetP
11) GetYenAdjustFactor
12) VolBasedStopLoss
13) VolBasedTakeProfit
14) Crossed1 / Crossed2
15) IsLossLimitBreached
16) IsVolLimitBreached
17) SetStopLossHidden
18) TriggerStopLossHidden
19) SetTakeProfitHidden
20) TriggerTakeProfitHidden
21) BreakevenStopAll
22) UpdateHiddenBEList
23) SetAndTriggerBEHidden
24) TrailingStopAll
25) UpdateHiddenTrailingList
26) SetAndTriggerHiddenTrailing
27) UpdateVolTrailingList
28) SetVolTrailingStop
29) ReviewVolTrailingStop
30) UpdateHiddenVolTrailingList
31) SetHiddenVolTrailing
32) TriggerAndReviewHiddenVolTrailing
33) HandleTradingEnvironment
34) GetErrorDescription
35) GetTradeFlagCondition
36) GetTradePrediction
*/
//+------------------------------------------------------------------+
//| ENTRY SIGNAL |
//+------------------------------------------------------------------+
int EntrySignal(int CrossOccurred)
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for entry signals
int entryOutput=0;
if(CrossOccurred==1)
{
entryOutput=1;
}
if(CrossOccurred==2)
{
entryOutput=2;
}
return(entryOutput);
}
//+------------------------------------------------------------------+
//| End of ENTRY SIGNAL |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL |
//+------------------------------------------------------------------+
int ExitSignal(int CrossOccurred)
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for exit signals
int ExitOutput=0;
if(CrossOccurred==1)
{
ExitOutput=1;
}
if(CrossOccurred==2)
{
ExitOutput=2;
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL ON TIMER MAGIC |
//+------------------------------------------------------------------+
int ExitSignalOnTimerMagic(int CrossOccurred, int Magic, int MaxOrderCloseTimer)
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for exit signals using a magic number. Note that function will close multiple orders
int ExitOutput=0;
int CurrOrderHoldTime;
double CurrOrderProfit;
if(CrossOccurred==1)
{
//checking the orders time before closing them
for(int i=OrdersTotal()-1; i>=0; i--)
{
CurrOrderHoldTime = 0;
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_SELL)
//Calculating order current time in minutes, used for closing orders
CurrOrderHoldTime = int((TimeCurrent() - OrderOpenTime())/60);
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
//if(CurrOrderHoldTime >= MaxOrderCloseTimer && CurrOrderProfit > 0) ExitOutput=1;
if(CurrOrderHoldTime >= MaxOrderCloseTimer) ExitOutput=1;
}
}
if(CrossOccurred==2)
{
//checking the orders time before closing them
for(int i=OrdersTotal()-1; i>=0; i--)
{
CurrOrderHoldTime = 0;
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType() == OP_BUY)
//Calculating order current time in minutes, used for closing orders
CurrOrderHoldTime = int((TimeCurrent() - OrderOpenTime())/60);
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
if(CurrOrderHoldTime >= MaxOrderCloseTimer && CurrOrderProfit > 0 ) ExitOutput=2;
if(CurrOrderHoldTime >= MaxOrderCloseTimer) ExitOutput=2;
}
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL ON TIMER
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL ON AI |
//+------------------------------------------------------------------+
int ExitSignalOnAI(int CrossOccurred, int Magic, double CurrPrediction)
{
// Type: Customisable
// Modify this function to suit your trading robot
// CrossOccurred - identifies type of position 2 buy; 1 sell
// CurrPrediction - current prediction from AI
// This function checks for exit signals
int ExitOutput=0;
double CurrOrderProfit;
if(CrossOccurred==1) //condition for sell orders
{
//checking the orders time before closing them
for(int i=OrdersTotal()-1; i>=0; i--)
{
CurrOrderProfit = 0;
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_SELL)
//Calculating order current profit
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
if(CurrOrderProfit > 0 && CurrPrediction > 0) ExitOutput=1;
}
}
if(CrossOccurred==2) //condition for buy orders
{
//checking the orders time before closing them
for(int i=OrdersTotal()-1; i>=0; i--)
{
CurrOrderProfit = 0;
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType() == OP_BUY)
//Calculating order current profit
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
if(CurrOrderProfit > 0 && CurrPrediction < 0) ExitOutput=2;
}
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL ON AI
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL ON TIMER TICKET |
//+------------------------------------------------------------------+
int ExitSignalOnTimerTicket(int CrossOccurred, int Magic, int & infoArray [][])
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for exit signals for each open order separately using the ticket
// If this will output 2 then one or more BUY orders shall be closed
// 1 then one or more SELL orders shall be closed
int ExitOutput=0;
int CurrOrderHoldTime;
double CurrOrderProfit;
if(CrossOccurred==1) //checking sell orders only
{
//check the order time using ticket from array
CurrOrderHoldTime = 0;
for(int j=0;j<ArrayRange(infoArray,0);j++)
{
Print("Info Array Ticket Number: " + (string)infoArray[j][0]);
if(OrderSelect(infoArray[j][0],SELECT_BY_TICKET,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_SELL)
//Calculating order current time in minutes, used for closing orders
CurrOrderHoldTime = int((TimeCurrent() - OrderOpenTime())/60);
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
//if(CurrOrderHoldTime >= infoArray[j][1] && CurrOrderProfit > 0) ExitOutput=1;
if(CurrOrderHoldTime >= infoArray[j][1]) { ExitOutput=1; break;}
}
}
if(CrossOccurred==2) //checking buy orders only
{
//checking the orders time using ticket from array
CurrOrderHoldTime = 0;
for(int j=0;j<ArrayRange(infoArray,0);j++)
{
if(OrderSelect(infoArray[j][0],SELECT_BY_TICKET,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_BUY)
//Calculating order current time in minutes, used for closing orders
CurrOrderHoldTime = int((TimeCurrent() - OrderOpenTime())/60);
CurrOrderProfit = NormalizeDouble(OrderProfit() + OrderSwap() + OrderCommission(),2);
//if(CurrOrderHoldTime >= infoArray[j][1] && CurrOrderProfit > 0) ExitOutput=2;
if(CurrOrderHoldTime >= infoArray[j][1]) { ExitOutput=2; break;}
}
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL ON TIMER TICKET
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL ON TIMER TICKET |
//+------------------------------------------------------------------+
int ExitSignalOnTimerTicketBars(int CrossOccurred, int Magic, int BarTimeframeMin, int & infoArray [][])
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for exit signals for each open order separately using the ticket
// If this will output 2 then one or more BUY orders shall be closed
// 1 then one or more SELL orders shall be closed
// This function will calculate order open time in BARS!
int ExitOutput=0;
int RequiredOrderTimeBars;
int CurrOrderHoldTimeBars = 0;
if(CrossOccurred==1) //checking sell orders only
{
//check the order time using ticket from array
for(int j=0;j<ArrayRange(infoArray,0);j++)
{
//Print("Info Array Ticket Number: " + (string)infoArray[j][0]);
if(OrderSelect(infoArray[j][0],SELECT_BY_TICKET,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_SELL)
//Calculating order open time shift in bars to avoid closing order after the weekend
CurrOrderHoldTimeBars = iBarShift(Symbol(), BarTimeframeMin,OrderOpenTime(),true);
RequiredOrderTimeBars = infoArray[j][1]/BarTimeframeMin;
if(CurrOrderHoldTimeBars >= RequiredOrderTimeBars) { ExitOutput=1; break;}
}
}
if(CrossOccurred==2) //checking buy orders only
{
//checking the orders time using ticket from array
for(int j=0;j<ArrayRange(infoArray,0);j++)
{
if(OrderSelect(infoArray[j][0],SELECT_BY_TICKET,MODE_TRADES)==true &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==Magic &&
OrderType()==OP_BUY)
//Calculating order open time shift in bars to avoid closing order after the weekend
CurrOrderHoldTimeBars = iBarShift(Symbol(), BarTimeframeMin,OrderOpenTime(),true);
RequiredOrderTimeBars = infoArray[j][1]/BarTimeframeMin;
if(CurrOrderHoldTimeBars >= RequiredOrderTimeBars) { ExitOutput=2; break;}
}
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL ON TIMER TICKET
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Position Sizing Algo
//+------------------------------------------------------------------+
// Type: Customisable
// Modify this function to suit your trading robot
// This is our sizing algorithm
double GetLot(bool IsSizingOnTrigger,double FixedLots,double RiskPerTrade,int YenAdjustment,double STOP,int K)
{
double output;
if(IsSizingOnTrigger==true)
{
output=RiskPerTrade*0.01*AccountBalance()/(MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_TICKVALUE)*STOP*K*Point); // Sizing Algo based on account size
output=output*YenAdjustment; // Adjust for Yen Pairs
} else {
output=FixedLots;
}
output=NormalizeDouble(output,2); // Round to 2 decimal place
return(output);
}
//+------------------------------------------------------------------+
//| End of Position Sizing Algo
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CHECK LOT
//+------------------------------------------------------------------+
double CheckLot(double Lot,bool Journaling)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function checks if our Lots to be trade satisfies any broker limitations
double LotToOpen=0;
LotToOpen=NormalizeDouble(Lot,2);
LotToOpen=MathFloor(LotToOpen/MarketInfo(Symbol(),MODE_LOTSTEP))*MarketInfo(Symbol(),MODE_LOTSTEP);
if(LotToOpen<MarketInfo(Symbol(),MODE_MINLOT))LotToOpen=MarketInfo(Symbol(),MODE_MINLOT);
if(LotToOpen>MarketInfo(Symbol(),MODE_MAXLOT))LotToOpen=MarketInfo(Symbol(),MODE_MAXLOT);
LotToOpen=NormalizeDouble(LotToOpen,2);
if(Journaling && LotToOpen!=Lot)Print("EA Journaling: Trading Lot has been changed by CheckLot function. Requested lot: "+(string)Lot+". Lot to open: "+(string)LotToOpen);
return(LotToOpen);
}
//+------------------------------------------------------------------+
//| End of CHECK LOT
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| COUNT POSITIONS
//+------------------------------------------------------------------+
int CountPosOrders(int Magic,int TYPE)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function counts number of positions/orders of OrderType TYPE
int Orders=0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
Orders++;
}
return(Orders);
}
//+------------------------------------------------------------------+
//| End of COUNT POSITIONS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| MAX ORDERS
//+------------------------------------------------------------------+
bool IsMaxPositionsReached(int MaxPositions,int Magic,bool Journaling)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function checks the number of positions we are holding against the maximum allowed
bool result=False;
if(CountPosOrders(Magic,OP_BUY)+CountPosOrders(Magic,OP_SELL)>MaxPositions)
{
result=True;
if(Journaling)Print("Max Orders Exceeded");
} else if(CountPosOrders(Magic,OP_BUY)+CountPosOrders(Magic,OP_SELL)==MaxPositions) {
result=True;
}
return(result);
/* Definitions: Position vs Orders
Position describes an opened trade
Order is a pending trade
How to use in a sentence: Jim has 5 buy limit orders pending 10 minutes ago. The market just crashed. The orders were executed and he has 5 losing positions now lol.
*/
}
//+------------------------------------------------------------------+
//| End of MAX ORDERS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| OPEN FROM MARKET
//+------------------------------------------------------------------+
int OpenPositionMarket(int TYPE,double LOT,double SL,double TP,int Magic,int Slip,bool Journaling,int K,bool ECN,int Max_Retries_Per_Tick,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function submits new orders
int tries=0;
string symbol=Symbol();
int cmd=TYPE;
double volume=CheckLot(LOT,Journaling);
if(MarketInfo(symbol,MODE_MARGINREQUIRED)*volume>AccountFreeMargin())
{
Print("Can not open a trade. Not enough free margin to open "+(string)volume+" on "+symbol);
return(-1);
}
int slippage=Slip*K; // Slippage is in points. 1 point = 0.0001 on 4 digit broker and 0.00001 on a 5 digit broker
string comment=" "+(string)TYPE+"(#"+(string)Magic+")";
int magic=Magic;
datetime expiration=0;
color arrow_color=0;if(TYPE==OP_BUY)arrow_color=Blue;if(TYPE==OP_SELL)arrow_color=Green;
double stoploss=0;
double takeprofit=0;
double initTP = TP;
double initSL = SL;
int Ticket=-1;
double price=0;
if(!ECN)
{
while(tries<Max_Retries_Per_Tick) // Edits stops and take profits before the market order is placed
{
RefreshRates();
if(TYPE==OP_BUY)price=Ask;if(TYPE==OP_SELL)price=Bid;
// Sets Take Profits and Stop Loss. Check against Stop Level Limitations.
if(TYPE==OP_BUY && SL!=0)
{
stoploss=NormalizeDouble(Ask-SL*K*Point,Digits);
if(Bid-stoploss<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_SELL && SL!=0)
{
stoploss=NormalizeDouble(Bid+SL*K*Point,Digits);
if(stoploss-Ask<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_BUY && TP!=0)
{
takeprofit=NormalizeDouble(Ask+TP*K*Point,Digits);
if(takeprofit-Bid<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_SELL && TP!=0)
{
takeprofit=NormalizeDouble(Bid-TP*K*Point,Digits);
if(Ask-takeprofit<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(Journaling)Print("EA Journaling: Trying to place a market order...");
HandleTradingEnvironment(Journaling,Retry_Interval);
Ticket=OrderSend(symbol,cmd,volume,price,slippage,stoploss,takeprofit,comment,magic,expiration,arrow_color);
if(Ticket>0)break;
tries++;
}
}
if(ECN) // Edits stops and take profits after the market order is placed
{
HandleTradingEnvironment(Journaling,Retry_Interval);
if(TYPE==OP_BUY)price=Ask;if(TYPE==OP_SELL)price=Bid;
if(Journaling)Print("EA Journaling: Trying to place a market order...");
Ticket=OrderSend(symbol,cmd,volume,price,slippage,0,0,comment,magic,expiration,arrow_color);
if(Ticket>0)
if(Ticket>0 && OrderSelect(Ticket,SELECT_BY_TICKET)==true && (SL!=0 || TP!=0))
{
// Sets Take Profits and Stop Loss. Check against Stop Level Limitations.
if(TYPE==OP_BUY && SL!=0)
{
stoploss=NormalizeDouble(OrderOpenPrice()-SL*K*Point,Digits);
if(Bid-stoploss<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string((OrderOpenPrice()-stoploss)/(K*Point))+" pips");
}
}
if(TYPE==OP_SELL && SL!=0)
{
stoploss=NormalizeDouble(OrderOpenPrice()+SL*K*Point,Digits);
if(stoploss-Ask<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string((stoploss-OrderOpenPrice())/(K*Point))+" pips");
}
}
if(TYPE==OP_BUY && TP!=0)
{
takeprofit=NormalizeDouble(OrderOpenPrice()+TP*K*Point,Digits);
if(takeprofit-Bid<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string((takeprofit-OrderOpenPrice())/(K*Point))+" pips");
}
}
if(TYPE==OP_SELL && TP!=0)
{
takeprofit=NormalizeDouble(OrderOpenPrice()-TP*K*Point,Digits);
if(Ask-takeprofit<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string((OrderOpenPrice()-takeprofit)/(K*Point))+" pips");
}
}
bool ModifyOpen=false;
while(!ModifyOpen)
{
HandleTradingEnvironment(Journaling,Retry_Interval);
ModifyOpen=OrderModify(Ticket,OrderOpenPrice(),stoploss,takeprofit,expiration,arrow_color);
if(Journaling && !ModifyOpen)Print("EA Journaling: Take Profit and Stop Loss not set. Error Description: "+GetErrorDescription(GetLastError()));
}
}
}
if(Journaling && Ticket<0)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Ticket>0)
{
Print("EA Journaling: Order successfully placed. Ticket: "+(string)Ticket);
}
return(Ticket);
}
//+------------------------------------------------------------------+
//| End of OPEN FROM MARKET
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| OPEN PENDING ORDERS
//+------------------------------------------------------------------+
int OpenPositionPending(int TYPE,double OpenPrice,datetime expiration,double LOT,double SL,double TP,int Magic,int Slip,bool Journaling,int K,bool ECN,int Max_Retries_Per_Tick,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function submits new pending orders
OpenPrice= NormalizeDouble(OpenPrice,Digits);
int tries=0;
string symbol=Symbol();
int cmd=TYPE;
double volume=CheckLot(LOT,Journaling);
if(MarketInfo(symbol,MODE_MARGINREQUIRED)*volume>AccountFreeMargin())
{
Print("Can not open a trade. Not enough free margin to open "+(string)volume+" on "+symbol);
return(-1);
}
int slippage=Slip*K; // Slippage is in points. 1 point = 0.0001 on 4 digit broker and 0.00001 on a 5 digit broker
string comment=" "+(string)TYPE+"(#"+(string)Magic+")";
int magic=Magic;
color arrow_color=0;if(TYPE==OP_BUYLIMIT || TYPE==OP_BUYSTOP)arrow_color=Blue;if(TYPE==OP_SELLLIMIT || TYPE==OP_SELLSTOP)arrow_color=Green;
double stoploss=0;
double takeprofit=0;
double initTP = TP;
double initSL = SL;
int Ticket=-1;
double price=0;
while(tries<Max_Retries_Per_Tick) // Edits stops and take profits before the market order is placed
{
RefreshRates();
// We are able to send in TP and SL when we open our orders even if we are using ECN brokers
// Sets Take Profits and Stop Loss. Check against Stop Level Limitations.
if((TYPE==OP_BUYLIMIT || TYPE==OP_BUYSTOP) && SL!=0)
{
stoploss=NormalizeDouble(OpenPrice-SL*K*Point,Digits);
if(OpenPrice-stoploss<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(OpenPrice-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string((OpenPrice-stoploss)/(K*Point))+" pips");
}
}
if((TYPE==OP_BUYLIMIT || TYPE==OP_BUYSTOP) && TP!=0)
{
takeprofit=NormalizeDouble(OpenPrice+TP*K*Point,Digits);
if(takeprofit-OpenPrice<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(OpenPrice+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string((takeprofit-OpenPrice)/(K*Point))+" pips");
}
}
if((TYPE==OP_SELLLIMIT || TYPE==OP_SELLSTOP) && SL!=0)
{
stoploss=NormalizeDouble(OpenPrice+SL*K*Point,Digits);
if(stoploss-OpenPrice<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(OpenPrice+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from " + (string)initSL + " to " + string((stoploss-OpenPrice)/(K*Point)) + " pips");
}
}
if((TYPE==OP_SELLLIMIT || TYPE==OP_SELLSTOP) && TP!=0)
{
takeprofit=NormalizeDouble(OpenPrice-TP*K*Point,Digits);
if(OpenPrice-takeprofit<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(OpenPrice-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from " + (string)initTP + " to " + string((OpenPrice-takeprofit)/(K*Point)) + " pips");
}
}
if(Journaling)Print("EA Journaling: Trying to place a pending order...");
HandleTradingEnvironment(Journaling,Retry_Interval);
//Note: We did not modify Open Price if it breaches the Stop Level Limitations as Open Prices are sensitive and important. It is unsafe to change it automatically.
Ticket=OrderSend(symbol,cmd,volume,OpenPrice,slippage,stoploss,takeprofit,comment,magic,expiration,arrow_color);
if(Ticket>0)break;
tries++;
}
if(Journaling && Ticket<0)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Ticket>0)
{
Print("EA Journaling: Order successfully placed. Ticket: "+(string)Ticket);
}
return(Ticket);
}
//+------------------------------------------------------------------+
//| End of OPEN PENDING ORDERS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
bool CloseOrderPosition(int TYPE,bool Journaling,int Magic,int Slip,int K,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function closes all positions of type TYPE or Deletes pending orders of type TYPE
int ordersPos=OrdersTotal();
for(int i=ordersPos-1; i>=0; i--)
{
// Note: Once pending orders become positions, OP_BUYLIMIT AND OP_BUYSTOP becomes OP_BUY, OP_SELLLIMIT and OP_SELLSTOP becomes OP_SELL
if(TYPE==OP_BUY || TYPE==OP_SELL)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
{
bool Closing=false;
double Price=0;
color arrow_color=0;if(TYPE==OP_BUY)arrow_color=Blue;if(TYPE==OP_SELL)arrow_color=Green;
if(Journaling)Print("EA Journaling: Trying to close position "+(string)OrderTicket()+" ...");
HandleTradingEnvironment(Journaling,Retry_Interval);
if(TYPE==OP_BUY)Price=Bid; if(TYPE==OP_SELL)Price=Ask;
Closing=OrderClose(OrderTicket(),OrderLots(),Price,Slip*K,arrow_color);
if(Journaling && !Closing)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Closing)Print("EA Journaling: Position successfully closed.");
}
}
else
{
bool Delete=false;
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
{
if(Journaling)Print("EA Journaling: Trying to delete order "+(string)OrderTicket()+" ...");
HandleTradingEnvironment(Journaling,Retry_Interval);
Delete=OrderDelete(OrderTicket(),CLR_NONE);
if(Journaling && !Delete)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Delete)Print("EA Journaling: Order successfully deleted.");
}
}
}
if(CountPosOrders(Magic, TYPE)==0)return(true); else return(false);
}
//+------------------------------------------------------------------+
//| End of CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
void CloseOrderPositionTimer(int TYPE,bool Journaling,int Magic, int & infoArray [][], int Slip,int K,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function closes all 'expired' positions of type TYPE
for(int i=0;i<ArrayRange(infoArray,0);i++)
{
// We check only tickets that have a ticket!
if((TYPE==OP_BUY || TYPE==OP_SELL) && infoArray[i][0] != 0)
{
if(OrderSelect(infoArray[i][0],SELECT_BY_TICKET,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
{
//bringing more info from this order to decide if this should be closed
int CurrOrderHoldTime = int((TimeCurrent() - OrderOpenTime())/60);
if(CurrOrderHoldTime >= infoArray[i][1])
{
bool Closing=false;
double Price=0;
color arrow_color=0;if(TYPE==OP_BUY)arrow_color=Blue;if(TYPE==OP_SELL)arrow_color=Green;
if(Journaling)Print("EA Journaling: Trying to close position "+(string)OrderTicket()+" ...");
HandleTradingEnvironment(Journaling,Retry_Interval);
if(TYPE==OP_BUY)Price=Bid; if(TYPE==OP_SELL)Price=Ask;
Closing=OrderClose(OrderTicket(),OrderLots(),Price,Slip*K,arrow_color);
if(Journaling && !Closing)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Closing)Print("EA Journaling: Position successfully closed.");
}
}
}
}
}
//+------------------------------------------------------------------+
//| End of CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
void CloseOrderPositionTimerBars(int TYPE,bool Journaling,int Magic, int BarTimeframeMin, int & infoArray [][], int Slip,int K,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function closes all 'expired' positions of type TYPE
int RequiredOrderTimeBars;
int CurrOrderHoldTimeBars = 0;
for(int i=0;i<ArrayRange(infoArray,0);i++)
{
RequiredOrderTimeBars = infoArray[i][1]/BarTimeframeMin;
// We check only tickets that have a ticket!
if((TYPE==OP_BUY || TYPE==OP_SELL) && infoArray[i][0] != 0)
{
if(OrderSelect(infoArray[i][0],SELECT_BY_TICKET,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
{
//bringing more info from this order to decide if this should be closed
CurrOrderHoldTimeBars = iBarShift(Symbol(), BarTimeframeMin,OrderOpenTime(),true);
if(CurrOrderHoldTimeBars >= RequiredOrderTimeBars)
{
bool Closing=false;
double Price=0;
color arrow_color=0;if(TYPE==OP_BUY)arrow_color=Blue;if(TYPE==OP_SELL)arrow_color=Green;
if(Journaling)Print("EA Journaling: Trying to close position "+(string)OrderTicket()+" ...");
HandleTradingEnvironment(Journaling,Retry_Interval);
if(TYPE==OP_BUY)Price=Bid; if(TYPE==OP_SELL)Price=Ask;
Closing=OrderClose(OrderTicket(),OrderLots(),Price,Slip*K,arrow_color);
if(Journaling && !Closing)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Closing)Print("EA Journaling: Position successfully closed.");
}
}
}
}
}
//+------------------------------------------------------------------+
//| End of CLOSE/DELETE ORDERS AND POSITIONS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Check for 4/5 Digits Broker
//+------------------------------------------------------------------+
int GetP()
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function returns P, which is used for converting pips to decimals/points
int output;
if(Digits==5 || Digits==3) output=10;else output=1;
return(output);
/* Some definitions: Pips vs Point
1 pip = 0.0001 on a 4 digit broker and 0.00010 on a 5 digit broker
1 point = 0.0001 on 4 digit broker and 0.00001 on a 5 digit broker
*/
}
//+------------------------------------------------------------------+
//| End of Check for 4/5 Digits Broker
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Yen Adjustment Factor
//+------------------------------------------------------------------+
int GetYenAdjustFactor()
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function returns a constant factor, which is used for position sizing for Yen pairs
int output= 1;
if(Digits == 3|| Digits == 2) output = 100;
return(output);
}
//+------------------------------------------------------------------+
//| End of Yen Adjustment Factor
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Volatility-Based Stop Loss
//+------------------------------------------------------------------+
double VolBasedStopLoss(bool isVolatilitySwitchOn,double fixedStop,double VolATR,double volMultiplier,int K)
{ // K represents our P multiplier to adjust for broker digits
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function calculates stop loss amount based on volatility
double StopL;
if(!isVolatilitySwitchOn)
{
StopL=fixedStop; // If Volatility Stop Loss not activated. Stop Loss = Fixed Pips Stop Loss
} else {
StopL=volMultiplier*VolATR/(K*Point); // Stop Loss in Pips
}
return(StopL);
}
//+------------------------------------------------------------------+
//| End of Volatility-Based Stop Loss
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Volatility-Based Take Profit
//+------------------------------------------------------------------+
double VolBasedTakeProfit(bool isVolatilitySwitchOn,double fixedTP,double VolATR,double volMultiplier,int K)
{ // K represents our P multiplier to adjust for broker digits
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function calculates take profit amount based on volatility
double TakeP;
if(!isVolatilitySwitchOn)
{
TakeP=fixedTP; // If Volatility Take Profit not activated. Take Profit = Fixed Pips Take Profit
} else {
TakeP=volMultiplier*VolATR/(K*Point); // Take Profit in Pips
}
return(TakeP);
}
//+------------------------------------------------------------------+
//| End of Volatility-Based Take Profit
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// Cross1
//+------------------------------------------------------------------+
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function determines if a cross happened between 2 lines/data set
/*
If Output is 0: No cross happened
If Output is 1: Line 1 crossed Line 2 from Bottom
If Output is 2: Line 1 crossed Line 2 from top
*/
int Crossed1(double line1,double line2)
{
static int CurrentDirection1=0;
static int LastDirection1=0;
static bool FirstTime1=true;
//----
if(line1>line2)
CurrentDirection1=1; // line1 above line2
if(line1<line2)
CurrentDirection1=2; // line1 below line2
//----
if(FirstTime1==true) // Need to check if this is the first time the function is run
{
FirstTime1=false; // Change variable to false
LastDirection1=CurrentDirection1; // Set new direction
return (0);
}
if(CurrentDirection1!=LastDirection1 && FirstTime1==false) // If not the first time and there is a direction change
{
LastDirection1=CurrentDirection1; // Set new direction
return(CurrentDirection1); // 1 for up, 2 for down
}
else
{
return(0); // No direction change
}
}
//+------------------------------------------------------------------+
// End of Cross
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// Cross2
//+------------------------------------------------------------------+
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function determines if a cross happened between 2 lines/data set
/*
If Output is 0: No cross happened
If Output is 1: Line 1 crossed Line 2 from Bottom
If Output is 2: Line 1 crossed Line 2 from top
*/
int Crossed2(double line1,double line2)
{
static int CurrentDirection1=0;
static int LastDirection1=0;
static bool FirstTime1=true;
//----
if(line1>line2)
CurrentDirection1=1; // line1 above line2
if(line1<line2)
CurrentDirection1=2; // line1 below line2
//----
if(FirstTime1==true) // Need to check if this is the first time the function is run
{
FirstTime1=false; // Change variable to false
LastDirection1=CurrentDirection1; // Set new direction
return (0); // there is no cross happened
}
if(CurrentDirection1!=LastDirection1 && FirstTime1==false) // If not the first time and there is a direction change
{