-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrade_MQL4.mqh
1086 lines (850 loc) · 30.7 KB
/
Trade_MQL4.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
//+------------------------------------------------------------------+
//| Trade.mqh |
//+------------------------------------------------------------------+
#property copyright ""
#property link ""
#property description "Trading classes and functions"
#property strict
#include <stdlib.mqh>
#define MAX_RETRIES 3 // Max retries on error
#define RETRY_DELAY 3000 // Retry delay in ms
//+------------------------------------------------------------------+
//| Trading class |
//+------------------------------------------------------------------+
class CTrade
{
private:
static int _magicNumber;
static int _slippage;
enum CLOSE_MARKET_TYPE
{
CLOSE_BUY,
CLOSE_SELL,
CLOSE_ALL_MARKET
};
enum CLOSE_PENDING_TYPE
{
CLOSE_BUY_LIMIT,
CLOSE_SELL_LIMIT,
CLOSE_BUY_STOP,
CLOSE_SELL_STOP,
CLOSE_ALL_PENDING
};
int OpenMarketOrder(string pSymbol, int pType, double pVolume, string pComment, color pArrow);
int OpenPendingOrder(string pSymbol, int pType, double pVolume, double pPrice, double pStop, double pProfit, string pComment, datetime pExpiration, color pArrow);
bool CloseMultipleOrders(CLOSE_MARKET_TYPE pCloseType);
bool DeleteMultipleOrders(CLOSE_PENDING_TYPE pDeleteType);
public:
int OpenBuyOrder(string pSymbol, double pVolume, string pComment = "Buy order", color pArrow = clrGreen);
int OpenSellOrder(string pSymbol, double pVolume, string pComment = "Sell order", color pArrow = clrRed);
int OpenBuyStopOrder(string pSymbol, double pVolume, double pPrice, double pStop, double pProfit, string pComment = "Buy stop order", datetime pExpiration = 0, color pArrow = clrBlue);
int OpenSellStopOrder(string pSymbol, double pVolume, double pPrice, double pStop, double pProfit, string pComment = "Sell stop order", datetime pExpiration = 0, color pArrow = clrIndigo);
int OpenBuyLimitOrder(string pSymbol, double pVolume, double pPrice, double pStop, double pProfit, string pComment = "Buy limit order", datetime pExpiration = 0, color pArrow = clrCornflowerBlue);
int OpenSellLimitOrder(string pSymbol, double pVolume, double pPrice, double pStop, double pProfit, string pComment = "Sell limit order", datetime pExpiration = 0, color pArrow = clrMediumSlateBlue);
bool CloseMarketOrder(int pTicket, double pVolume = 0, color pArrow = clrRed);
bool CloseAllBuyOrders();
bool CloseAllSellOrders();
bool CloseAllMarketOrders();
bool DeletePendingOrder(int pTicket, color pArrow = clrRed);
bool DeleteAllBuyStopOrders();
bool DeleteAllSellStopOrders();
bool DeleteAllBuyLimitOrders();
bool DeleteAllSellLimitOrders();
bool DeleteAllPendingOrders();
static void SetMagicNumber(int pMagic);
static int GetMagicNumber();
static void SetSlippage(int pSlippage);
};
int CTrade::_magicNumber = 0;
int CTrade::_slippage = 10;
//+------------------------------------------------------------------+
//| Market order functions |
//+------------------------------------------------------------------+
int CTrade::OpenMarketOrder(string pSymbol, int pType, double pVolume, string pComment, color pArrow)
{
int retryCount = 0;
int ticket = 0;
int errorCode = 0;
double orderPrice = 0;
string orderType;
string errDesc;
// Order retry loop
while(retryCount <= MAX_RETRIES)
{
while(IsTradeContextBusy()) Sleep(10);
// Get current bid/ask price
if(pType == OP_BUY) orderPrice = MarketInfo(pSymbol,MODE_ASK);
else if(pType == OP_SELL) orderPrice = MarketInfo(pSymbol,MODE_BID);
// Place market order
ticket = OrderSend(pSymbol,pType,pVolume,orderPrice,_slippage,0,0,pComment,_magicNumber,0,pArrow);
// Error handling
if(ticket == -1)
{
errorCode = GetLastError();
errDesc = ErrorDescription(errorCode);
bool checkError = RetryOnError(errorCode);
orderType = OrderTypeToString(pType);
// Unrecoverable error
if(checkError == false)
{
Alert("Open ",orderType," order: Error ",errorCode," - ",errDesc);
Print("Symbol: ",pSymbol,", Volume: ",pVolume,", Price: ",orderPrice);
break;
}
// Retry on error
else
{
Print("Server error detected, retrying...");
Sleep(RETRY_DELAY);
retryCount++;
}
}
// Order successful
else
{
orderType = OrderTypeToString(pType);
Comment(orderType," order #",ticket," opened on ",pSymbol);
Print(orderType," order #",ticket," opened on ",pSymbol);
break;
}
}
// Failed after retry
if(retryCount > MAX_RETRIES)
{
Alert("Open ",orderType," order: Max retries exceeded. Error ",errorCode," - ",errDesc);
Print("Symbol: ",pSymbol,", Volume: ",pVolume,", Price: ",orderPrice);
}
return(ticket);
}
int CTrade::OpenBuyOrder(string pSymbol,double pVolume,string pComment="Buy order",color pArrow=32768)
{
int ticket = OpenMarketOrder(pSymbol, OP_BUY, pVolume, pComment, pArrow);
return(ticket);
}
int CTrade::OpenSellOrder(string pSymbol,double pVolume,string pComment="Sell order",color pArrow=255)
{
int ticket = OpenMarketOrder(pSymbol, OP_SELL, pVolume, pComment, pArrow);
return(ticket);
}
//+------------------------------------------------------------------+
//| Pending order functions |
//+------------------------------------------------------------------+
int CTrade::OpenPendingOrder(string pSymbol,int pType,double pVolume,double pPrice,double pStop,double pProfit,string pComment,datetime pExpiration,color pArrow)
{
int retryCount = 0;
int ticket = 0;
int errorCode = 0;
string orderType;
string errDesc;
// Order retry loop
while(retryCount <= MAX_RETRIES)
{
while(IsTradeContextBusy()) Sleep(10);
ticket = OrderSend(pSymbol, pType, pVolume, pPrice, _slippage, pStop, pProfit, pComment, _magicNumber, pExpiration, pArrow);
// Error handling
if(ticket == -1)
{
errorCode = GetLastError();
errDesc = ErrorDescription(errorCode);
bool checkError = RetryOnError(errorCode);
orderType = OrderTypeToString(pType);
// Unrecoverable error
if(checkError == false)
{
Alert("Open ",orderType," order: Error ",errorCode," - ",errDesc);
Print("Symbol: ",pSymbol,", Volume: ",pVolume,", Price: ",pPrice,", SL: ",pStop,", TP: ",pProfit,", Expiration: ",pExpiration);
break;
}
// Retry on error
else
{
Print("Server error detected, retrying...");
Sleep(RETRY_DELAY);
retryCount++;
}
}
// Order successful
else
{
orderType = OrderTypeToString(pType);
Comment(orderType," order #",ticket," opened on ",pSymbol);
Print(orderType," order #",ticket," opened on ",pSymbol);
break;
}
}
// Failed after retry
if(retryCount > MAX_RETRIES)
{
Alert("Open ",orderType," order: Max retries exceeded. Error ",errorCode," - ",errDesc);
Print("Symbol: ",pSymbol,", Volume: ",pVolume,", Price: ",pPrice,", SL: ",pStop,", TP: ",pProfit,", Expiration: ",pExpiration);
}
return(ticket);
}
int CTrade::OpenBuyStopOrder(string pSymbol,double pVolume,double pPrice,double pStop,double pProfit,string pComment="Buy stop order",datetime pExpiration=0,color pArrow=16711680)
{
int ticket = OpenPendingOrder(pSymbol, OP_BUYSTOP, pVolume, pPrice, pStop, pProfit, pComment, pExpiration, pArrow);
return(ticket);
}
int CTrade::OpenSellStopOrder(string pSymbol,double pVolume,double pPrice,double pStop,double pProfit,string pComment="Sell stop order",datetime pExpiration=0,color pArrow=8519755)
{
int ticket = OpenPendingOrder(pSymbol, OP_SELLSTOP, pVolume, pPrice, pStop, pProfit, pComment, pExpiration, pArrow);
return(ticket);
}
int CTrade::OpenBuyLimitOrder(string pSymbol,double pVolume,double pPrice,double pStop,double pProfit,string pComment="Buy limit order",datetime pExpiration=0,color pArrow=15570276)
{
int ticket = OpenPendingOrder(pSymbol, OP_BUYLIMIT, pVolume, pPrice, pStop, pProfit, pComment, pExpiration, pArrow);
return(ticket);
}
int CTrade::OpenSellLimitOrder(string pSymbol,double pVolume,double pPrice,double pStop,double pProfit,string pComment="Sell limit order",datetime pExpiration=0,color pArrow=15624315)
{
int ticket = OpenPendingOrder(pSymbol, OP_SELLLIMIT, pVolume, pPrice, pStop, pProfit, pComment, pExpiration, pArrow);
return(ticket);
}
//+------------------------------------------------------------------+
//| Close market orders |
//+------------------------------------------------------------------+
bool CTrade::CloseMarketOrder(int pTicket,double pVolume=0.000000,color pArrow=255)
{
int retryCount = 0;
int errorCode = 0;
double closePrice = 0;
double closeVolume = 0;
bool result;
string errDesc;
// Select ticket
result = OrderSelect(pTicket,SELECT_BY_TICKET);
// Exit with error if order select fails
if(result == false)
{
errorCode = GetLastError();
errDesc = ErrorDescription(errorCode);
Alert("Close order: Error selecting order #",pTicket,". Error ",errorCode," - ",errDesc);
return(result);
}
// Close entire order if pVolume not specified, or if pVolume is greater than order volume
if(pVolume == 0 || pVolume > OrderLots()) closeVolume = OrderLots();
else closeVolume = pVolume;
// Order retry loop
while(retryCount <= MAX_RETRIES)
{
while(IsTradeContextBusy()) Sleep(10);
// Get current bid/ask price
if(OrderType() == OP_BUY) closePrice = MarketInfo(OrderSymbol(),MODE_BID);
else if(OrderType() == OP_SELL) closePrice = MarketInfo(OrderSymbol(),MODE_ASK);
result = OrderClose(pTicket,closeVolume,closePrice,_slippage,pArrow);
if(result == false)
{
errorCode = GetLastError();
errDesc = ErrorDescription(errorCode);
bool checkError = RetryOnError(errorCode);
// Unrecoverable error
if(checkError == false)
{
Alert("Close order #",pTicket,": Error ",errorCode," - ",errDesc);
Print("Price: ",closePrice,", Volume: ",closeVolume);
break;
}
// Retry on error
else
{
Print("Server error detected, retrying...");
Sleep(RETRY_DELAY);
retryCount++;
}
}
// Order successful
else
{
Comment("Order #",pTicket," closed");
Print("Order #",pTicket," closed");
break;
}
}
// Failed after retry
if(retryCount > MAX_RETRIES)
{
Alert("Close order #",pTicket,": Max retries exceeded. Error ",errorCode," - ",errDesc);
Print("Price: ",closePrice,", Volume: ",closeVolume);
}
return(result);
}
bool CTrade::CloseMultipleOrders(CLOSE_MARKET_TYPE pCloseType)
{
bool error = false;
bool closeOrder = false;
// Loop through open order pool from oldest to newest
for(int order = 0; order <= OrdersTotal() - 1; order++)
{
// Select order
bool result = OrderSelect(order,SELECT_BY_POS);
int orderType = OrderType();
int orderMagicNumber = OrderMagicNumber();
int orderTicket = OrderTicket();
double orderVolume = OrderLots();
// Determine if order type matches pCloseType
if( (pCloseType == CLOSE_ALL_MARKET && (orderType == OP_BUY || orderType == OP_SELL))
|| (pCloseType == CLOSE_BUY && orderType == OP_BUY)
|| (pCloseType == CLOSE_SELL && orderType == OP_SELL) )
{
closeOrder = true;
}
else closeOrder = false;
// Close order if pCloseType and magic number match currently selected order
if(closeOrder == true && orderMagicNumber == _magicNumber)
{
result = CloseMarketOrder(orderTicket,orderVolume);
if(result == false)
{
Print("Close multiple orders: ",OrderTypeToString(orderType)," #",orderTicket," not closed");
error = true;
}
else order--;
}
}
return(error);
}
bool CTrade::CloseAllBuyOrders(void)
{
bool result = CloseMultipleOrders(CLOSE_BUY);
return(result);
}
bool CTrade::CloseAllSellOrders(void)
{
bool result = CloseMultipleOrders(CLOSE_SELL);
return(result);
}
bool CTrade::CloseAllMarketOrders(void)
{
bool result = CloseMultipleOrders(CLOSE_ALL_MARKET);
return(result);
}
//+------------------------------------------------------------------+
//| Delete pending orders |
//+------------------------------------------------------------------+
bool CTrade::DeletePendingOrder(int pTicket,color pArrow=255)
{
int retryCount = 0;
int errorCode = 0;
bool result = false;
string errDesc;
// Order retry loop
while(retryCount <= MAX_RETRIES)
{
while(IsTradeContextBusy()) Sleep(10);
result = OrderDelete(pTicket,pArrow);
if(result == false)
{
errorCode = GetLastError();
errDesc = ErrorDescription(errorCode);
bool checkError = RetryOnError(errorCode);
// Unrecoverable error
if(checkError == false)
{
Alert("Delete pending order #",pTicket,": Error ",errorCode," - ",errDesc);
break;
}
// Retry on error
else
{
Print("Server error detected, retrying...");
Sleep(RETRY_DELAY);
retryCount++;
}
}
// Order successful
else
{
Comment("Pending order #",pTicket," deleted");
Print("Pending order #",pTicket," deleted");
break;
}
}
// Failed after retry
if(retryCount > MAX_RETRIES)
{
Alert("Delete pending order #",pTicket,": Max retries exceeded. Error ",errorCode," - ",errDesc);
}
return(result);
}
bool CTrade::DeleteMultipleOrders(CLOSE_PENDING_TYPE pDeleteType)
{
bool error = false;
bool deleteOrder = false;
// Loop through open order pool from oldest to newest
for(int order = 0; order <= OrdersTotal() - 1; order++)
{
// Select order
bool result = OrderSelect(order,SELECT_BY_POS);
int orderType = OrderType();
int orderMagicNumber = OrderMagicNumber();
int orderTicket = OrderTicket();
double orderVolume = OrderLots();
// Determine if order type matches pCloseType
if( (pDeleteType == CLOSE_ALL_PENDING && orderType != OP_BUY && orderType != OP_SELL)
|| (pDeleteType == CLOSE_BUY_LIMIT && orderType == OP_BUYLIMIT)
|| (pDeleteType == CLOSE_SELL_LIMIT && orderType == OP_SELLLIMIT)
|| (pDeleteType == CLOSE_BUY_STOP && orderType == OP_BUYSTOP)
|| (pDeleteType == CLOSE_SELL_STOP && orderType == OP_SELLSTOP) )
{
deleteOrder = true;
}
else deleteOrder = false;
// Close order if pCloseType and magic number match currently selected order
if(deleteOrder == true && orderMagicNumber == _magicNumber)
{
result = DeletePendingOrder(orderTicket);
if(result == false)
{
Print("Delete multiple orders: ",OrderTypeToString(orderType)," #",orderTicket," not deleted");
error = true;
}
else order--;
}
}
return(error);
}
bool CTrade::DeleteAllBuyLimitOrders(void)
{
bool result = DeleteMultipleOrders(CLOSE_BUY_LIMIT);
return(result);
}
bool CTrade::DeleteAllBuyStopOrders(void)
{
bool result = DeleteMultipleOrders(CLOSE_BUY_STOP);
return(result);
}
bool CTrade::DeleteAllSellLimitOrders(void)
{
bool result = DeleteMultipleOrders(CLOSE_SELL_LIMIT);
return(result);
}
bool CTrade::DeleteAllSellStopOrders(void)
{
bool result = DeleteMultipleOrders(CLOSE_SELL_STOP);
return(result);
}
bool CTrade::DeleteAllPendingOrders(void)
{
bool result = DeleteMultipleOrders(CLOSE_ALL_PENDING);
return(result);
}
//+------------------------------------------------------------------+
//| Set trade properties |
//+------------------------------------------------------------------+
static void CTrade::SetMagicNumber(int pMagic)
{
if(_magicNumber != 0)
{
Alert("Magic number changed! Any orders previously opened by this expert advisor will no longer be handled!");
}
_magicNumber = pMagic;
}
static int CTrade::GetMagicNumber(void)
{
return(_magicNumber);
}
static void CTrade::SetSlippage(int pSlippage)
{
_slippage = pSlippage;
}
//+------------------------------------------------------------------+
//| Internal functions |
//+------------------------------------------------------------------+
bool RetryOnError(int pErrorCode)
{
// Retry on these error codes
switch(pErrorCode)
{
case ERR_BROKER_BUSY:
case ERR_COMMON_ERROR:
case ERR_NO_ERROR:
case ERR_NO_CONNECTION:
case ERR_NO_RESULT:
case ERR_SERVER_BUSY:
case ERR_NOT_ENOUGH_RIGHTS:
case ERR_MALFUNCTIONAL_TRADE:
case ERR_TRADE_CONTEXT_BUSY:
case ERR_TRADE_TIMEOUT:
case ERR_REQUOTE:
case ERR_TOO_MANY_REQUESTS:
case ERR_OFF_QUOTES:
case ERR_PRICE_CHANGED:
case ERR_TOO_FREQUENT_REQUESTS:
return(true);
}
return(false);
}
string OrderTypeToString(int pType)
{
string orderType;
if(pType == OP_BUY) orderType = "Buy";
else if(pType == OP_SELL) orderType = "Sell";
else if(pType == OP_BUYSTOP) orderType = "Buy stop";
else if(pType == OP_BUYLIMIT) orderType = "Buy limit";
else if(pType == OP_SELLSTOP) orderType = "Sell stop";
else if(pType == OP_SELLLIMIT) orderType = "Sell limit";
else orderType = "Invalid order type";
return(orderType);
}
//+------------------------------------------------------------------+
//| Modify orders |
//+------------------------------------------------------------------+
bool ModifyOrder(int pTicket, double pPrice, double pStop = 0, double pProfit = 0, datetime pExpiration = 0, color pArrow = clrOrange)
{
int retryCount = 0;
int errorCode = 0;
bool result = false;
string errDesc;
// Order retry loop
while(retryCount <= MAX_RETRIES)
{
while(IsTradeContextBusy()) Sleep(10);
result = OrderModify(pTicket, pPrice, pStop, pProfit, pExpiration, pArrow);
errorCode = GetLastError();
// Error handling - Ignore error code 1
if(result == false && errorCode != ERR_NO_RESULT)
{
errDesc = ErrorDescription(errorCode);
bool checkError = RetryOnError(errorCode);
// Unrecoverable error
if(checkError == false)
{
Alert("Modify order #",pTicket,": Error ",errorCode," - ",errDesc);
Print("Price: ",pPrice,", SL: ",pStop,", TP: ",pProfit,", Expiration: ",pExpiration);
break;
}
// Retry on error
else
{
Print("Server error detected, retrying...");
Sleep(RETRY_DELAY);
retryCount++;
}
}
// Order successful
else
{
Comment("Order #",pTicket," modified");
Print("Order #",pTicket," modified");
break;
}
}
// Failed after retry
if(retryCount > MAX_RETRIES)
{
Alert("Modify order #",pTicket,": Max retries exceeded. Error ",errorCode," - ",errDesc);
Print("Price: ",pPrice,", SL: ",pStop,", TP: ",pProfit,", Expiration: ",pExpiration);
}
return(result);
}
bool ModifyStopsByPoints(int pTicket, int pStopPoints, int pProfitPoints = 0, int pMinPoints = 10)
{
if(pStopPoints == 0 && pProfitPoints == 0) return false;
bool result = OrderSelect(pTicket,SELECT_BY_TICKET);
if(result == false)
{
Print("Modify stops: #",pTicket," not found!");
return false;
}
double orderType = OrderType();
double orderOpenPrice = OrderOpenPrice();
string orderSymbol = OrderSymbol();
double stopLoss = 0;
double takeProfit = 0;
if(orderType == OP_BUY)
{
stopLoss = BuyStopLoss(orderSymbol,pStopPoints,orderOpenPrice);
if(stopLoss != 0) stopLoss = AdjustBelowStopLevel(orderSymbol,stopLoss,pMinPoints);
takeProfit = BuyTakeProfit(orderSymbol,pProfitPoints,orderOpenPrice);
if(takeProfit != 0) takeProfit = AdjustAboveStopLevel(orderSymbol,takeProfit,pMinPoints);
}
else if(orderType == OP_SELL)
{
stopLoss = SellStopLoss(orderSymbol,pStopPoints,orderOpenPrice);
if(stopLoss != 0) stopLoss = AdjustAboveStopLevel(orderSymbol,stopLoss,pMinPoints);
takeProfit = SellTakeProfit(orderSymbol,pProfitPoints,orderOpenPrice);
if(takeProfit != 0) takeProfit = AdjustBelowStopLevel(orderSymbol,takeProfit,pMinPoints);
}
result = ModifyOrder(pTicket,0,stopLoss,takeProfit);
return(result);
}
bool ModifyStopsByPrice(int pTicket, double pStopPrice, double pProfitPrice = 0, int pMinPoints = 10)
{
if(pStopPrice == 0 && pProfitPrice == 0) return false;
bool result = OrderSelect(pTicket,SELECT_BY_TICKET);
if(result == false)
{
Print("Modify stops: #",pTicket," not found!");
return false;
}
double orderType = OrderType();
string orderSymbol = OrderSymbol();
double stopLoss = 0;
double takeProfit = 0;
if(orderType == OP_BUY)
{
if(pStopPrice != 0) stopLoss = AdjustBelowStopLevel(orderSymbol,pStopPrice,pMinPoints);
if(pProfitPrice != 0) takeProfit = AdjustAboveStopLevel(orderSymbol,pProfitPrice,pMinPoints);
}
else if(orderType == OP_SELL)
{
if(pStopPrice != 0) stopLoss = AdjustAboveStopLevel(orderSymbol,pStopPrice,pMinPoints);
if(pProfitPrice != 0) takeProfit = AdjustBelowStopLevel(orderSymbol,pProfitPrice,pMinPoints);
}
result = ModifyOrder(pTicket,0,stopLoss,takeProfit);
return(result);
}
//+------------------------------------------------------------------+
//| Stop loss & take profit calculation |
//+------------------------------------------------------------------+
double BuyStopLoss(string pSymbol,int pStopPoints, double pOpenPrice = 0)
{
if(pStopPoints <= 0) return(0);
double openPrice;
if(pOpenPrice > 0) openPrice = pOpenPrice;
else openPrice = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLoss = openPrice - (pStopPoints * point);
long digits = SymbolInfoInteger(pSymbol,SYMBOL_DIGITS);
stopLoss = NormalizeDouble(stopLoss,(int)digits);
return(stopLoss);
}
double SellStopLoss(string pSymbol,int pStopPoints, double pOpenPrice = 0)
{
if(pStopPoints <= 0) return(0);
double openPrice;
if(pOpenPrice > 0) openPrice = pOpenPrice;
else openPrice = SymbolInfoDouble(pSymbol,SYMBOL_BID);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLoss = openPrice + (pStopPoints * point);
long digits = SymbolInfoInteger(pSymbol,SYMBOL_DIGITS);
stopLoss = NormalizeDouble(stopLoss,(int)digits);
return(stopLoss);
}
double BuyTakeProfit(string pSymbol,int pProfitPoints, double pOpenPrice = 0)
{
if(pProfitPoints <= 0) return(0);
double openPrice;
if(pOpenPrice > 0) openPrice = pOpenPrice;
else openPrice = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double takeProfit = openPrice + (pProfitPoints * point);
long digits = SymbolInfoInteger(pSymbol,SYMBOL_DIGITS);
takeProfit = NormalizeDouble(takeProfit,(int)digits);
return(takeProfit);
}
double SellTakeProfit(string pSymbol,int pProfitPoints, double pOpenPrice = 0)
{
if(pProfitPoints <= 0) return(0);
double openPrice;
if(pOpenPrice > 0) openPrice = pOpenPrice;
else openPrice = SymbolInfoDouble(pSymbol,SYMBOL_BID);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double takeProfit = openPrice - (pProfitPoints * point);
long digits = SymbolInfoInteger(pSymbol,SYMBOL_DIGITS);
takeProfit = NormalizeDouble(takeProfit,(int)digits);
return(takeProfit);
}
//+------------------------------------------------------------------+
//| Stop level verification |
//+------------------------------------------------------------------+
// Check stop level
bool CheckAboveStopLevel(string pSymbol, double pPrice, int pPoints = 10)
{
double currPrice = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLevel = SymbolInfoInteger(pSymbol,SYMBOL_TRADE_STOPS_LEVEL) * point;
double stopPrice = currPrice + stopLevel;
double addPoints = pPoints * point;
if(pPrice >= stopPrice + addPoints) return(true);
else return(false);
}
bool CheckBelowStopLevel(string pSymbol, double pPrice, int pPoints = 10)
{
double currPrice = SymbolInfoDouble(pSymbol,SYMBOL_BID);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLevel = SymbolInfoInteger(pSymbol,SYMBOL_TRADE_STOPS_LEVEL) * point;
double stopPrice = currPrice - stopLevel;
double addPoints = pPoints * point;
if(pPrice <= stopPrice - addPoints) return(true);
else return(false);
}
// Adjust price to stop level
double AdjustAboveStopLevel(string pSymbol, double pPrice, int pPoints = 10)
{
double currPrice = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLevel = SymbolInfoInteger(pSymbol,SYMBOL_TRADE_STOPS_LEVEL) * point;
double stopPrice = currPrice + stopLevel;
double addPoints = pPoints * point;
if(pPrice > stopPrice + addPoints) return(pPrice);
else
{
double newPrice = stopPrice + addPoints;
Print("Price adjusted above stop level to "+DoubleToString(newPrice));
return(newPrice);
}
}
double AdjustBelowStopLevel(string pSymbol, double pPrice, int pPoints = 10)
{
double currPrice = SymbolInfoDouble(pSymbol,SYMBOL_BID);
double point = SymbolInfoDouble(pSymbol,SYMBOL_POINT);
double stopLevel = SymbolInfoInteger(pSymbol,SYMBOL_TRADE_STOPS_LEVEL) * point;
double stopPrice = currPrice - stopLevel;
double addPoints = pPoints * point;
if(pPrice < stopPrice - addPoints) return(pPrice);
else
{
double newPrice = stopPrice - addPoints;
Print("Price adjusted below stop level to "+DoubleToString(newPrice));
return(newPrice);
}
}
//+------------------------------------------------------------------+
//| Order counts |
//+------------------------------------------------------------------+
class CCount
{
private:
enum COUNT_ORDER_TYPE
{
COUNT_BUY,
COUNT_SELL,
COUNT_BUY_STOP,
COUNT_SELL_STOP,
COUNT_BUY_LIMIT,
COUNT_SELL_LIMIT,
COUNT_MARKET,
COUNT_PENDING,
COUNT_ALL
};
int CountOrders(COUNT_ORDER_TYPE pType);
public:
int Buy();
int Sell();
int BuyStop();
int SellStop();
int BuyLimit();
int SellLimit();
int TotalMarket();
int TotalPending();
int TotalOrders();
};
int CCount::CountOrders(COUNT_ORDER_TYPE pType)
{
// Order counts
int buy = 0, sell = 0, buyStop = 0, sellStop = 0,
buyLimit = 0, sellLimit = 0, totalOrders = 0;
// Loop through open order pool from oldest to newest
for(int order = 0; order <= OrdersTotal() - 1; order++)
{
// Select order
bool result = OrderSelect(order,SELECT_BY_POS);
int orderType = OrderType();
int orderMagicNumber = OrderMagicNumber();
// Add to order count if magic number matches
if(orderMagicNumber == CTrade::GetMagicNumber())
{
switch(orderType)
{
case OP_BUY:
buy++;
break;
case OP_SELL:
sell++;
break;
case OP_BUYLIMIT:
buyLimit++;
break;
case OP_SELLLIMIT:
sellLimit++;
break;
case OP_BUYSTOP:
buyStop++;
break;
case OP_SELLSTOP:
sellStop++;
break;
}
totalOrders++;
}
}
// Return order count based on pType
int returnTotal = 0;
switch(pType)
{
case COUNT_BUY:
returnTotal = buy;
break;
case COUNT_SELL:
returnTotal = sell;
break;