-
Notifications
You must be signed in to change notification settings - Fork 21
/
Falcon_S.mq4
2231 lines (1908 loc) · 106 KB
/
Falcon_S.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
//+------------------------------------------------------------------+
//| Falcon EA Template v2.0
//| Copyright 2015,Lucas Liew
//+------------------------------------------------------------------+
#include <01_GetHistoryOrder.mqh>
#include <02_OrderProfitToCSV.mqh>
#include <03_ReadCommandFromCSV.mqh>
#include <08_TerminalNumber.mqh>
#include <10_isNewBar.mqh>
#include <11_ReadSentiment.mqh>
#property copyright "Copyright 2015, Black Algo Technologies Pte Ltd"
#property copyright "Copyright 2018, Vladimir Zhbanko"
#property link "[email protected]"
#property link "https://vladdsm.github.io/myblog_attempt/"
#property version "1.001"
#property strict
/*
Falcon S:
- Using sentiment analysis as a trigger for trades
*/
//+------------------------------------------------------------------+
//| Setup
//+------------------------------------------------------------------+
extern string Header15="----------EA General Settings-----------";
extern int MagicNumber = 8136201;
extern int TerminalType = 1; //0 mean slave, 1 mean master
extern bool R_Management = true; //R_Management true will enable Decision Support Centre (using R)
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
extern string Header1="----------Trading Rules Variables-----------";
extern bool StartTradeHour08=TRUE;
extern bool StartTradeHour16=TRUE;
extern bool StartTradeHour24=TRUE;
extern int TradeMaxDurationHrs=7;
extern string Header2="----------Position Sizing Settings-----------";
extern string Lot_explanation="If IsSizingOn = true, Lots variable will be ignored";
extern double Lots=0.01;
extern bool IsSizingOn=False;
extern double Risk=1; // Risk per trade (in percentage)
extern string Header3="----------TP & SL Settings-----------";
extern bool UseFixedStopLoss=True; // If this is false and IsSizingOn = True, sizing algo will not be able to calculate correct lot size.
extern double FixedStopLoss=0; // Hard Stop in Pips. Will be overridden if vol-based SL is true
extern bool IsVolatilityStopOn=True;
extern double VolBasedSLMultiplier=6; // Stop Loss Amount in units of Volatility
extern bool UseFixedTakeProfit=True;
extern double FixedTakeProfit=0; // Hard Take Profit in Pips. Will be overridden if vol-based TP is true
extern bool IsVolatilityTakeProfitOn=True;
extern double VolBasedTPMultiplier=6; // Take Profit Amount in units of Volatility
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=0; // In pips
extern string Header6="----------Hidden Breakeven Stops Settings-----------";
extern bool UseHiddenBreakevenStops=False;
extern double BreakevenBuffer_Hidden=0; // In pips
extern string Header7="----------Trailing Stops Settings-----------";
extern bool UseTrailingStops=False;
extern double TrailingStopDistance=0; // In pips
extern double TrailingStopBuffer=0; // In pips
extern string Header8="----------Hidden Trailing Stops Settings-----------";
extern bool UseHiddenTrailingStops=False;
extern double TrailingStopDistance_Hidden=0; // In pips
extern double TrailingStopBuffer_Hidden=0; // In pips
extern string Header9="----------Volatility Trailing Stops Settings-----------";
extern bool UseVolTrailingStops=False;
extern double VolTrailingDistMultiplier=0; // In units of ATR
extern double VolTrailingBuffMultiplier=0; // In units of ATR
extern string Header10="----------Hidden Volatility Trailing Stops Settings-----------";
extern bool UseHiddenVolTrailing=False;
extern double VolTrailingDistMultiplier_Hidden=0; // In units of ATR
extern double VolTrailingBuffMultiplier_Hidden=0; // In units of ATR
extern string Header11="----------Volatility Measurement Settings-----------";
extern int atr_period=14;
extern string Header12="----------Max Orders-----------";
extern int MaxPositionsAllowed=1;
extern string Header13="----------Set Max Loss Limit-----------";
extern bool IsLossLimitActivated=False;
extern double LossLimitPercent=50;
extern string Header14="----------Set Max Volatility Limit-----------";
extern bool IsVolLimitActivated=False;
extern double VolatilityMultiplier=3; // In units of ATR
extern int ATRTimeframe=60; // In minutes
extern int ATRPeriod=14;
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;
int YenPairAdjustFactor;
int P;
double myATR;
double FastMA1, SlowMA1, Price1;
// TDL 3: Declaring Variables (and the extern variables above)
datetime timeexit;
int CrossTriggered1, CrossTriggered2, CrossTriggered3;
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
double HiddenTrailingList[][2]; // First dimension is for position ticket numbers, second is for the hidden trailing stop levels
double VolTrailingList[][2]; // First dimension is for position ticket numbers, second is for recording of volatility amount (one unit of ATR) at the time of trade
double HiddenVolTrailingList[][3]; // First dimension is for position ticket numbers, second is for the hidden trailing stop levels, third is for recording of volatility amount (one unit of ATR) at the time of trade
string InternalHeader3="----------Decision Support Variables-----------";
bool TradeAllowed = true;
bool FlagBuy, FlagSell; //boolean flags to limit direction of trades
datetime ReferenceTime; //used for order history
int DirectionNews; //used for trading entry from Sentiment Analysis
//+------------------------------------------------------------------+
//| End of Setup
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Initialization
//+------------------------------------------------------------------+
int init()
{
//------------- Decision Support Centre
// Write file to the sandbox if it's does not exist
//
ReferenceTime = TimeCurrent(); // record time for order history function
//write file system control to enable initial trading
TradeAllowed = ReadCommandFromCSV(MagicNumber);
if(TradeAllowed == false)
{
Comment("Trade is not allowed");
}
else if(TradeAllowed == true) // or file does not exist, create a new file
{
string fileName = "SystemControl"+string(MagicNumber)+".csv";//create the name of the file same for all symbols...
// open file handle
int handle = FileOpen(fileName,FILE_CSV|FILE_READ|FILE_WRITE); FileSeek(handle,0,SEEK_END);
string data = string(MagicNumber)+","+string(TerminalType);
FileWrite(handle,data); FileClose(handle);
//end of writing to file
Comment("Trade is allowed");
}
//---------
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, records form these arrays will be gone.
if(UseHiddenStopLoss) ArrayResize(HiddenSLList,MaxPositionsAllowed,0);
if(UseHiddenTakeProfit) ArrayResize(HiddenTPList,MaxPositionsAllowed,0);
if(UseHiddenBreakevenStops) ArrayResize(HiddenBEList,MaxPositionsAllowed,0);
if(UseHiddenTrailingStops) ArrayResize(HiddenTrailingList,MaxPositionsAllowed,0);
if(UseVolTrailingStops) ArrayResize(VolTrailingList,MaxPositionsAllowed,0);
if(UseHiddenVolTrailing) ArrayResize(HiddenVolTrailingList,MaxPositionsAllowed,0);
start();
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Initialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Deinitialization
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Deinitialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert start
//+------------------------------------------------------------------+
int start()
{
//only execute code on ever new bar!!!
if(!isNewBar())return(0);
//----------Order management through R - to avoid slow down the system only enable with external parameters
if(R_Management)
{
//code that only executed once a bar
OrderProfitToCSV(T_Num(MagicNumber)); //write previous orders profit results for auto analysis in R
TradeAllowed = ReadCommandFromCSV(MagicNumber); //read command from R to make sure trading is allowed
DirectionNews = ReadSentiment(Symbol(), -1); //get prediction from R for trade direction
}
//----------Variables to be Refreshed-----------
//added generic comment
Comment("MagicNum: " + (string)MagicNumber + " time to exit order: "+timeexit);
OrderNumber=0; // OrderNumber used in Entry Rules
//----------Entry & Exit Variables-----------
// buy or sell direction?
if(DirectionNews == 0) {FlagBuy = True; FlagSell= False;}
if(DirectionNews == 1) {FlagSell= True; FlagBuy = False;}
if(DirectionNews == -1){FlagBuy = False;FlagSell= False;}
// checking if this is the time to trade (not using function Crossed1)
if(StartTradeHour08 && Hour() == 9 && DirectionNews != -1) CrossTriggered1=2; //fresh news sentiment are delivered 07:50 CET 08:50 Broker/Server Time
if(StartTradeHour16 && Hour() == 17 && DirectionNews != -1) CrossTriggered1=2;
if(StartTradeHour24 && Hour() == 1 && DirectionNews != -1) CrossTriggered1=2;
//CrossTriggered2=Crossed2(Ask,KeltnerUpper1);
//CrossTriggered3=Crossed3(Bid,KeltnerLower1);
//----------TP, SL, Breakeven and Trailing Stops Variables-----------
myATR=iATR(NULL,Period(),atr_period,1);
if(UseFixedStopLoss==False)
{
Stop=0;
} else {
Stop=VolBasedStopLoss(IsVolatilityStopOn,FixedStopLoss,myATR,VolBasedSLMultiplier,P);
}
if(UseFixedTakeProfit==False)
{
Take=0;
} else {
Take=VolBasedTakeProfit(IsVolatilityTakeProfitOn,FixedTakeProfit,myATR,VolBasedTPMultiplier,P);
}
if(UseBreakevenStops) BreakevenStopAll(OnJournaling,RetryInterval,BreakevenBuffer,MagicNumber,P);
if(UseTrailingStops) TrailingStopAll(OnJournaling,TrailingStopDistance,TrailingStopBuffer,RetryInterval,MagicNumber,P);
if(UseVolTrailingStops) {
UpdateVolTrailingList(OnJournaling,RetryInterval,MagicNumber);
ReviewVolTrailingStop(OnJournaling,VolTrailingDistMultiplier,VolTrailingBuffMultiplier,RetryInterval,MagicNumber,P);
}
//----------(Hidden) TP, SL, Breakeven and Trailing 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);
}
if(UseHiddenTrailingStops) {
UpdateHiddenTrailingList(OnJournaling,RetryInterval,MagicNumber);
SetAndTriggerHiddenTrailing(OnJournaling,TrailingStopDistance_Hidden,TrailingStopBuffer_Hidden,Slippage,RetryInterval,MagicNumber,P);
}
if(UseHiddenVolTrailing) {
UpdateHiddenVolTrailingList(OnJournaling,RetryInterval,MagicNumber);
TriggerAndReviewHiddenVolTrailing(OnJournaling,VolTrailingDistMultiplier_Hidden,VolTrailingBuffMultiplier_Hidden,Slippage,RetryInterval,MagicNumber,P);
}
//----------Exit Rules (All Opened Positions)-----------
// TDL 2: Setting up Exit rules. Modify the ExitSignal() function to suit your needs.
if(CountPosOrders(MagicNumber,OP_BUY)>=1 && TimeCurrent() > timeexit)
{ // Close Long Positions
CloseOrderPosition(OP_BUY, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
if(CountPosOrders(MagicNumber,OP_SELL)>=1 && TimeCurrent() > timeexit)
{ // Close Short Positions
CloseOrderPosition(OP_SELL, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
//----------Entry Rules (Market and Pending) -----------
if(IsLossLimitBreached(IsLossLimitActivated,LossLimitPercent,OnJournaling,EntrySignal(CrossTriggered1))==False)
if(IsVolLimitBreached(IsVolLimitActivated,VolatilityMultiplier,ATRTimeframe,ATRPeriod)==False)
if(IsMaxPositionsReached(MaxPositionsAllowed,MagicNumber,OnJournaling)==False)
{
if(TradeAllowed && EntrySignal(CrossTriggered1)==2 && FlagBuy)
{ // 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,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
// Define Time-based Exit
timeexit = TimeCurrent() + TradeMaxDurationHrs * Period()*60; // Multiply by 60 to convert to seconds
}
if(TradeAllowed && EntrySignal(CrossTriggered1)==2 && FlagSell)
{ // 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,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
// Define Time-based Exit
timeexit = TimeCurrent() + TradeMaxDurationHrs * Period()*60; // Multiply by 60 to convert to seconds
}
}
//----------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) 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
*/
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 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=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 "+(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,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 "+(string)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
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+