-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathDarcie 2.00.mq4
1522 lines (1298 loc) · 75.3 KB
/
Darcie 2.00.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
//+------------------------------------------------------------------+
//| Darcie 2.00
//| Copyright 2015-2017, Black Algo Technologies Pte Ltd
//+------------------------------------------------------------------+
#property copyright "Copyright 2015-2017, Black Algo Technologies Pte Ltd"
#property link "blackalgotechnologies.com"
/*
DARCIE - RETRACEMENT BOT
DARCIE ENTRY RULES:
Market Long Order: Closing price touches bottom line of Donchian(24) and
SMA(24) is greater than SMA(72). This indicates that we are in a up trend.
Market Short Order: Closing price touches top line of Donchian(24) and
SMA(24) is less than SMA(72). This indicates that we are in a down trend.
DARCIE EXIT RULES:
TakeProfit Order: Place hard TakeProfit 0.5 * Donchian(24) width away from opening price when trade is first executed
(Definition: Donchian width = Donchian top line minus bottom line)
StopLoss Order: Place hard StopLoss order 2 * ATR(24) away from opening price when trade is first executed
DARCIE POSITION SIZING RULE:
2% of Capital risked per trade
Note: We have modified the code for our sizing algo. We will add a lecture about in Chapter "What A Mess - Managing Trades, Orders and Positions"
*/
//+------------------------------------------------------------------+
//| Setup
//+------------------------------------------------------------------+
extern string Header1 = "----------Trading Rules Variables-----------";
extern int Donchian_Period = 24;
extern int Donchian_Extremes = 3;
extern int Donchian_Margins = -2;
extern int Donchian_Advance = 0;
extern int Donchian_max_bars = 1000;
extern int Entry_SMA_Fast_Period = 24;
extern int Entry_SMA_Slow_Period = 72;
extern string Header2 = "----------Position Sizing Settings-----------";
extern string Lot_explanation = "If IsSizingOn = true, Lots variable will be ignored";
extern double Lots = 0;
extern bool IsSizingOn = True;
extern double Risk = 2; // Risk per trade (in percentage)
extern string Header3 = "----------TP & SL Settings-----------";
extern bool UseFixedStopLoss = True; // if False, Risk will be sized to ATR StopLoss and FixedStopLoss is ignored; if True, Risk will be sized to FixedStopLoss
extern double FixedStopLoss = 0; // Hard Stop in Pips. Will be overridden if Is_SL_ATR_On is true
extern bool Is_SL_ATR_On = True; // if this is True, UseFixedStopLoss must be set to True
extern double SL_ATR_Multiplier = 2;
extern int SL_ATR_Period = 24;
extern bool UseFixedTakeProfit = True;
extern double FixedTakeProfit = 0; // Hard Take Profit in Pips. Will be overridden if Is_TP_Donchian_On is true
extern bool Is_TP_Donchian_On = True;
extern double TP_Donchian_Multiplier = 0.5;
extern string Header4 = "----------Hidden TP & SL Settings-----------";
extern bool UseHiddenStopLoss = False;
extern double FixedStopLoss_Hidden = 0; // In Pips. Will be overridden if hidden vol-based SL is true
extern bool IsVolatilityStopLossOn_Hidden = False;
extern double VolBasedSLMultiplier_Hidden = 0; // Stop Loss Amount in units of Volatility
extern bool UseHiddenTakeProfit = False;
extern double FixedTakeProfit_Hidden = 0; // In Pips. Will be overridden if hidden vol-based TP is true
extern bool IsVolatilityTakeProfitOn_Hidden = False;
extern double VolBasedTPMultiplier_Hidden = 0; // Take Profit Amount in units of Volatility
extern string Header5 = "----------Breakeven Stops Settings-----------";
extern bool UseBreakevenStops = False;
extern double BreakevenBuffer = 20; // In pips
extern string Header6 = "----------Hidden Breakeven Stops Settings-----------";
extern bool UseHiddenBreakevenStops = False;
extern double BreakevenBuffer_Hidden = 20; // In pips
extern string Header7 = "----------Trailing Stops Settings-----------";
extern bool UseTrailingStops = False;
extern double TrailingStopDistance = 40; // In pips
extern double TrailingStopBuffer = 10; // In pips
/*
extern string Header8 = "----------Volatility Measurement Settings-----------";
extern int atr_period = 14;
*/
extern string Header9 = "----------Max Orders-----------";
extern int MaxPositionsAllowed = 1;
extern string Header10 = "----------Set Max Loss Limit-----------";
extern bool IsLossLimitActivated = False;
extern double LossLimitPercent = 50;
extern string Header11 = "----------EA General Settings-----------";
extern int MagicNumber = 12345;
extern int Slippage = 3; // In Pips
extern bool IsECNbroker = false; // Is your broker an ECN
extern bool OnJournaling = true; // Add EA updates in the Journal Tab
string InternalHeader1="----------Errors Handling Settings-----------";
int RetryInterval=100; // Pause Time before next retry (in milliseconds)
int MaxRetriesPerTick=10;
string InternalHeader2="----------Service Variables-----------";
double Stop, Take;
double StopHidden, TakeHidden;
double P, YenPairAdjustFactor;
double donchianTop1, donchianBottom1, donchianWidth1;
double smaFast1, smaSlow1;
double close1;
double ATR_SL, ATR_TP;
double LongEntryReversion, ShortEntryReversion;
int OrderNumber;
double HiddenSLList[][2]; // First dimension is for position ticket numbers, second is for the SL Levels
double HiddenTPList[][2]; // First dimension is for position ticket numbers, second is for the TP Levels
double HiddenBEList[]; // First dimension is for position ticket numbers
//+------------------------------------------------------------------+
//| End of Setup
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Initialization
//+------------------------------------------------------------------+
int init()
{
P = GetP(); // To account for 5 digit brokers. Used to convert pips to decimal place
YenPairAdjustFactor = GetYenAdjustFactor(); // Adjust for YenPair
//----------(Hidden) TP, SL and Breakeven Stops Variables-----------
// If EA disconnects abruptly and there are open positions from this EA, hidden SL, TP and BE records will be gone.
if (UseHiddenStopLoss) ArrayResize(HiddenSLList,MaxPositionsAllowed,0);
if (UseHiddenTakeProfit) ArrayResize(HiddenTPList,MaxPositionsAllowed,0);
if (UseHiddenBreakevenStops) ArrayResize(HiddenBEList,MaxPositionsAllowed,0);
start();
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Initialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Deinitialization
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Deinitialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert start
//+------------------------------------------------------------------+
int start()
{
//----------Variables to be Refreshed-----------
OrderNumber = 0; // OrderNumber used in Entry Rules
//----------Entry & Exit Variables-----------
donchianTop1 = iCustom(NULL, 0, "Donchian Channels", Donchian_Period, Donchian_Extremes, Donchian_Margins, Donchian_Advance, Donchian_max_bars, 1, 1);
donchianBottom1 = iCustom(NULL, 0, "Donchian Channels", Donchian_Period, Donchian_Extremes, Donchian_Margins, Donchian_Advance, Donchian_max_bars, 0, 1);
donchianWidth1 = donchianTop1 - donchianBottom1;
smaFast1 = iMA(NULL, 0, Entry_SMA_Fast_Period, 0, 0, 0, 1);
smaSlow1 = iMA(NULL, 0, Entry_SMA_Slow_Period, 0, 0, 0, 1);
close1 = iClose(NULL, 0, 1);
LongEntryReversion = Crossed1(close1, donchianBottom1);
ShortEntryReversion = Crossed2(close1, donchianTop1);
//----------TP, SL, Breakeven and Trailing Stops Variables-----------
ATR_SL = iATR(NULL, 0, SL_ATR_Period, 1);
if(UseFixedStopLoss == False) {
Stop = 0;
} else {
//Stop=VolBasedStopLoss(IsVolatilityStopOn, FixedStopLoss, myATR, VolBasedSLMultiplier, P);
Stop=ATRBasedStopLoss(Is_SL_ATR_On, FixedStopLoss, ATR_SL, SL_ATR_Multiplier, P);
}
if(UseFixedTakeProfit == False) {
Take = 0;
} else {
//Take=VolBasedTakeProfit(IsVolatilityTakeProfitOn, FixedTakeProfit, myATR, VolBasedTPMultiplier, P);
Take=DonchianBasedTakeProfit(Is_TP_Donchian_On, FixedTakeProfit, donchianWidth1, TP_Donchian_Multiplier, P);
}
if (UseBreakevenStops) BreakevenStopAll(OnJournaling, RetryInterval, BreakevenBuffer, MagicNumber, P);
if (UseTrailingStops) TrailingStopAll(OnJournaling, TrailingStopDistance, TrailingStopBuffer, RetryInterval, MagicNumber, P);
//----------(Hidden) TP, SL and Breakeven Stops Variables-----------
if (UseHiddenStopLoss) TriggerStopLossHidden(OnJournaling, RetryInterval, MagicNumber, Slippage, P);
if (UseHiddenTakeProfit) TriggerTakeProfitHidden(OnJournaling, RetryInterval, MagicNumber, Slippage, P);
if (UseHiddenBreakevenStops){
UpdateHiddenBEList(OnJournaling, RetryInterval, MagicNumber);
SetAndTriggerBEHidden(OnJournaling, BreakevenBuffer, MagicNumber, Slippage , P, RetryInterval);
}
//----------Exit Rules (All Opened Positions)-----------
/*
// Close Long Positions
if(CountPosOrders(MagicNumber, OP_BUY)>=1 && ExitSignal()==1){
CloseOrderPosition(OP_BUY, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
// Close Short Positions
if(CountPosOrders(MagicNumber, OP_SELL)>=1 && ExitSignal()==1){
CloseOrderPosition(OP_SELL, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
*/
//----------Entry Rules (Market and Pending) -----------
if(IsLossLimitBreached(IsLossLimitActivated, LossLimitPercent, OnJournaling, EntrySignal(smaFast1, smaSlow1, LongEntryReversion, ShortEntryReversion)) == False)
if(IsMaxPositionsReached(MaxPositionsAllowed, MagicNumber, OnJournaling) == False){
if(EntrySignal(smaFast1, smaSlow1, LongEntryReversion, ShortEntryReversion)==1){ // Open Long Positions
OrderNumber = OpenPositionMarket(OP_BUY, GetLot(IsSizingOn, Lots, Risk, YenPairAdjustFactor, Stop, P), Stop, Take, MagicNumber, Slippage, OnJournaling, P, IsECNbroker, MaxRetriesPerTick, RetryInterval);
// Set Stop Loss value for Hidden SL
if (UseHiddenStopLoss) SetStopLossHidden(OnJournaling, IsVolatilityStopLossOn_Hidden, FixedStopLoss_Hidden, ATR_SL, VolBasedSLMultiplier_Hidden, P, OrderNumber);
// Set Take Profit value for Hidden TP
if (UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling, IsVolatilityTakeProfitOn_Hidden, FixedTakeProfit_Hidden, ATR_TP, VolBasedTPMultiplier_Hidden, P, OrderNumber);
}
else if(EntrySignal(smaFast1, smaSlow1, LongEntryReversion, ShortEntryReversion)==2){ // Open Short Positions
OrderNumber = OpenPositionMarket(OP_SELL, GetLot(IsSizingOn, Lots, Risk, YenPairAdjustFactor, Stop, P), Stop, Take, MagicNumber, Slippage, OnJournaling, P, IsECNbroker, MaxRetriesPerTick, RetryInterval);
// Set Stop Loss value for Hidden SL
if (UseHiddenStopLoss) SetStopLossHidden(OnJournaling, IsVolatilityStopLossOn_Hidden, FixedStopLoss_Hidden, ATR_SL, VolBasedSLMultiplier_Hidden, P, OrderNumber);
// Set Take Profit value for Hidden TP
if (UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling, IsVolatilityTakeProfitOn_Hidden, FixedTakeProfit_Hidden, ATR_TP, VolBasedTPMultiplier_Hidden, P, OrderNumber);
}
}
//----------Pending Order Management-----------
/*
Not Applicable (See Desiree for example of pending order rules).
*/
//----
return(0);
}
//+------------------------------------------------------------------+
//| End of expert start function |
//+------------------------------------------------------------------+
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//| FUNCTIONS LIBRARY
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
Content:
1) EntrySignal
2) ExitSignal
3) GetLot
4) CheckLot
5) CountPosOrders
6) IsMaxPositionsReached
7) OpenPositionMarket
8) OpenPositionPending
9) CloseOrderPosition
10) GetP
11) GetYenAdjustFactor
12) VolBasedStopLoss
13) VolBasedTakeProfit
14) Crossed
15) isLossLimitedBreached
16) SetStopLossHidden
17) TriggerStopLossHidden
18) SetTakeProfitHidden
19) TriggerTakeProfitHidden
20) BreakevenStopAll
21) SetAndTriggerBEHidden
22) UpdateHiddenBEList
23) TrailingStopAll
24) HandleTradingEnvironment
25) GetErrorDescription
*/
//+------------------------------------------------------------------+
//| ENTRY SIGNAL |
//+------------------------------------------------------------------+
int EntrySignal(double p_smaFast1, double p_smaSlow1, int p_LongEntryReversion, int p_ShortEntryReversion){
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for entry signals
/*
DARCIE ENTRY RULES:
Market Long Order: Closing price touches bottom line of Donchian(24) and
SMA(24) is greater than SMA(72). This indicates that we are in a up trend.
Market Short Order: Closing price touches top line of Donchian(24) and
SMA(24) is less than SMA(72). This indicates that we are in a down trend.
*/
int entryOutput=0;
// Long Entry
if (p_LongEntryReversion == 2){
if (p_smaFast1 > p_smaSlow1){
entryOutput=1; // Return 1 for Buy Signals
}
}
// Short Entry
if (p_ShortEntryReversion == 1){
if (p_smaFast1 < p_smaSlow1){
entryOutput=2; // Return 2 for Short Signals
}
}
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 == 2)
{
ExitOutput=1; // Close Long Positions
}
if(CrossOccurred == 1)
{
ExitOutput=2; // Close Short Positions
}
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 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 * AccountEquity() / ((MarketInfo(Symbol(),MODE_TICKVALUE)/MarketInfo(Symbol(),MODE_TICKSIZE)) * STOP * K * Point);
} 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: "+Lot+". Lot to open: "+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=0; i<OrdersTotal(); 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
int 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 "+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=" " + TYPE + "(#" + 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 " + initSL + " to " + 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 " + initSL + " to " + 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(Bid+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from " + initTP + " to " + 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(Ask-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from " + initTP + " to " + 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 " + initSL + " to " + (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 " + initSL + " to " + (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(Bid+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from " + initTP + " to " + (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(Ask-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from " + initTP + " to " + (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: "+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 "+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=" " + TYPE + "(#" + 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 " + initSL + " to " + (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 " + initTP + " to " + (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 " + initSL + " to " + (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 " + initTP + " to " + (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: "+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 "+OrderTicket()+" ...");
HandleTradingEnvironment(Journaling, RetryInterval);
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 "+OrderTicket()+" ...");
HandleTradingEnvironment(Journaling, RetryInterval);
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
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+
*/
double ATRBasedStopLoss(bool p_Is_SL_ATR_On, double p_FixedStopLoss, double p_ATR_SL, double p_SL_ATR_Multiplier, int K){ // K represents our P multiplier to adjust for broker digits
if(!p_Is_SL_ATR_On){
return(p_FixedStopLoss); // If Volatility Stop Loss not activated. Stop Loss = Fixed Pips Stop Loss
}
else{
return(p_SL_ATR_Multiplier * p_ATR_SL / (K*Point)); // Stop Loss in Pips
}
}
/*
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+
*/
//+------------------------------------------------------------------+
//| Donchian-Based Take Profit
//+------------------------------------------------------------------+
double DonchianBasedTakeProfit(bool p_Is_TP_Donchian_On, double p_FixedTakeProfit, double p_donchianWidth1, double p_TP_Donchian_Multiplier, int K){ // K represents our P multiplier to adjust for broker digits
//TakeProfit Order: Place hard TakeProfit 0.5 * Donchian(24) width away from opening price when trade is first executed
// (Definition: Donchian width = Donchian top line minus bottom line)
if(!p_Is_TP_Donchian_On){
return(p_FixedTakeProfit); // If Volatility Stop Loss not activated. Stop Loss = Fixed Pips Stop Loss
}
else{
return(p_TP_Donchian_Multiplier * donchianWidth1 / (K*Point)); // Stop Loss in Pips
}
}
//+------------------------------------------------------------------+
// Cross
//+------------------------------------------------------------------+
// 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
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// Cross
//+------------------------------------------------------------------+
// 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);
}
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
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Is Loss Limit Breached
//+------------------------------------------------------------------+
bool IsLossLimitBreached(bool LossLimitActivated, double LossLimitPercentage, bool Journaling, int EntrySignalTrigger){
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function determines if our maximum loss threshold is breached
static bool firstTick = False;
static double initialCapital = 0;
double profitAndLoss = 0;
double profitAndLossPrint = 0;
bool output = False;
if(LossLimitActivated==False) return(output);
if(firstTick == False){
initialCapital = AccountEquity();
firstTick = True;
}
profitAndLoss = (AccountEquity()/initialCapital)-1;
if(profitAndLoss < -LossLimitPercentage/100){
output = True;
profitAndLossPrint = NormalizeDouble(profitAndLoss, 4)*100;
if(Journaling)if(EntrySignalTrigger != 0) Print("Entry trade triggered but not executed. Loss threshold breached. Current Loss: " + profitAndLossPrint + "%");
}
return(output);
}
//+------------------------------------------------------------------+
//| End of Is Loss Limit Breached
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Set Hidden Stop Loss
//+------------------------------------------------------------------+
void SetStopLossHidden(bool Journaling, bool isVolatilitySwitchOn, double fixedSL, double volATR, double volMultiplier, int K, int orderNum){ // 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 hidden stop loss amount and tags it to the appropriate order using an array
double StopL;
if(!isVolatilitySwitchOn){
StopL=fixedSL; // If Volatility Stop Loss not activated. Stop Loss = Fixed Pips Stop Loss
} else {