bleh
[mqlkit.git] / SpeedTrainOrig.mq4
blob87eb486369c010d1a90f944f37718af79de7178d
1 //+------------------------------------------------------------------+\r
2 //|                                                      EMA Cut.mq4 |\r
3 //|                                                            Jasus |\r
4 //|                                                                  |\r
5 //+------------------------------------------------------------------+\r
6 #property copyright "roundrock"\r
7 #property link      ""\r
8 \r
9 #include <stderror.mqh>\r
10 #include <stdlib.mqh>\r
14 extern int    Slippage         =       3;\r
19 extern double     LotSize= 0.1;\r
21 extern string PipStep_Remarks="------ Pip Distance. 30 pips is 30 pips for all brokers -------";\r
22 extern double     PipStep= 50;\r
24 extern string MoveSL2BE_Remarks="------ Move Prev order SL to BE ------";\r
25 extern bool  MoveSL2BE = true;\r
27 extern string InitialBuyOrder_Remarks="------ First Order on start, if true its LONG ------";\r
28 extern bool  InitialBuyOrder = true;\r
30 extern string UseTradingHours_Remarks="------ Place orders only during these hours. however closing can happen any time ------";\r
31 extern bool   UseTradingHours     =    false;\r
32 extern int    StartHour           =       7;\r
33 extern int    FinishHour          =      19;\r
35 extern string ProfitPct_Remarks="------ Profit Percentage ------";\r
36 extern double     ProfitPct= 1.0;\r
39 extern int    MagicNumber         =  1771611;\r
41 int longOrderCount=0;\r
42 int shortOrderCount=0;\r
43 double DollarProfitTarget;\r
44 double valLastFlatEq;\r
45 double valTargetFlatEq;\r
46 bool CloseAll;\r
47 bool longBias=false;\r
48 int totalOrders=0;\r
49 //double currentPL=0;\r
51 double startPrice=0.0;\r
53 double avgEntryPrice=0.0;\r
55 int    digits=4;\r
56 double pip = 0;\r
58 bool initOrdersDone=false;\r
60 int init()\r
61   {\r
62    digits=MarketInfo(Symbol(),MODE_DIGITS); \r
63  \r
64   if (digits < 4)\r
65     pip = 0.01;\r
66   else\r
67     pip = 0.0001;\r
68     \r
69    resetAccountCalc();\r
70    \r
71    return(0);\r
72   }\r
74 int deinit()\r
75   {\r
76 //---- TODO: add your code here\r
77    deleteAll();\r
78 //----\r
79    return(0);\r
80   }\r
81   \r
83 void deleteAll(){ \r
84  \r
85   for(int j = 0; j <= 10000; j++){\r
86       ObjectDelete("Comment" + j);     \r
87       \r
88    } \r
89      \r
90   }\r
93 int start()\r
94   {\r
95         //DollarProfitTarget = StrToDouble(DoubleToStr(AccountEquity()*ProfitPct/100.0,2));\r
96         if(startPrice ==0.0) {\r
97             startPrice=iOpen( NULL, PERIOD_M15, 0);\r
98             Print("----- startPrice ...... "+startPrice);\r
99         }\r
100         \r
101         if(!initOrdersDone && inTradingHours()){\r
102          \r
103           \r
104           placeBuyStopOrder();\r
105           placeSellStopOrder();\r
106           if(InitialBuyOrder) {\r
107             longBias=true;\r
108             placeInitBuyOrder();\r
109           }else{\r
110             placeInitSellOrder();\r
111             longBias=false;\r
112           }\r
113             \r
114           initOrdersDone=true;\r
115         }\r
116      \r
117       double currentPL = getEAPL();\r
118      \r
119      \r
120       //  if (!CloseAll && currentPL > DollarProfitTarget)\r
121         \r
122         if (!CloseAll && currentPL+AccountBalance() > valTargetFlatEq)\r
123          {           \r
124            Print("================ closing ================");\r
125            Print("currentPL "+currentPL+" AccountBalance "+AccountBalance()+" valTargetFlatEq "+valTargetFlatEq);\r
126             CloseAllTrades();\r
127             return(0);\r
128          }\r
129      \r
130         \r
131         if(inTradingHours()) { \r
132      \r
133             if(iClose( NULL, PERIOD_M15, 0) > (startPrice + PipStep*pip)){\r
134               longBias=true;\r
135               startPrice=iClose( NULL, PERIOD_M15, 0);\r
136                Print("----- moved to startPrice ...... "+startPrice);\r
137               // need to set the sl to BE of last order\r
138               if(MoveSL2BE)   moveSellOrderToBE();\r
139               CloseAllPendingOrders();\r
140               // place buy limit order\r
141               placeBuyStopOrder();  \r
142               placeSellStopOrder();      \r
143           \r
144            \r
145             }else if(iClose( NULL, PERIOD_M15, 0) < (startPrice - PipStep*pip)){\r
146              longBias=false;\r
147               startPrice=iClose( NULL, PERIOD_M15, 0);\r
148               Print("------ moved to startPrice ...... "+startPrice);\r
149               // need to set the sl to BE of last order\r
150              if(MoveSL2BE) moveBuyOrderToBE();  \r
151              CloseAllPendingOrders();\r
152               // place buy limit order\r
153               placeSellStopOrder();\r
154               placeBuyStopOrder();\r
155                  \r
156           \r
157             }\r
158         }\r
159         \r
160         printComment(currentPL);\r
161                \r
162         \r
163       \r
164     }\r
165     \r
166     bool inTradingHours(){\r
167     \r
168       bool returnVal=true;\r
169        \r
170        if (UseTradingHours)\r
171       {\r
172           if (TimeHour(iTime( NULL, 0, 0) ) < StartHour &&\r
173             ((TimeHour(iTime( NULL, 0, 0)) > FinishHour && FinishHour != 0) ||\r
174             (TimeHour(iTime( NULL, 0, 0)) < 24 && FinishHour == 0)))\r
175            {\r
176                returnVal=false;\r
177            }\r
178            \r
179        }\r
180     \r
181      return(returnVal);\r
182     }\r
183     \r
184     \r
185     void printComment(double currentPL){\r
186     \r
187         \r
188         double curPL = -valLastFlatEq + AccountBalance()+currentPL;\r
189         double drawdown = (curPL/valLastFlatEq)*100;\r
190      \r
191         string commentSt = "\nEquity "+DoubleToStr(valLastFlatEq,0) + " Dollar Profit "+DoubleToStr(DollarProfitTarget,2)+" PL " +DoubleToStr(curPL,2)\r
192         +" DD "+DoubleToStr(drawdown,2);\r
193         \r
194         ObjectCreate("CommentStr",OBJ_LABEL,0,0,0);\r
195          ObjectSet("CommentStr",OBJPROP_XDISTANCE,5);\r
196          ObjectSet("CommentStr",OBJPROP_YDISTANCE,40);\r
197          ObjectSet("CommentStr",OBJPROP_WIDTH,5);\r
198          ObjectSetText("CommentStr",commentSt,12,"Arial",DodgerBlue);\r
199          \r
200          string bias="Short";\r
201          double targetPrice=0;\r
202          if(longBias) {\r
203            bias="Long";\r
204            if(totalOrders>0) {\r
205            \r
206             //  Print("profit "+DollarProfitTarget+" totalOrders "+totalOrders+" LotSize "+LotSize+" qty "+MarketInfo(Symbol(), MODE_LOTSIZE) +" avgEntryPrice "+avgEntryPrice+\r
207              // " bottom "+totalOrders*LotSize*MarketInfo(Symbol(), MODE_LOTSIZE) +" top "+(DollarProfitTarget*pip));\r
208               \r
209                targetPrice = (DollarProfitTarget/(totalOrders*LotSize*MarketInfo(Symbol(), MODE_LOTSIZE)))+avgEntryPrice;\r
210             }\r
211           }else {\r
212               if(totalOrders>0) {\r
213             //  Print("totalOrders "+totalOrders+" LotSize "+LotSize+" qty "+MarketInfo(Symbol(), MODE_LOTSIZE) +" avgEntryPrice "+avgEntryPrice);\r
214               \r
215                targetPrice =  -(DollarProfitTarget/(totalOrders*LotSize*MarketInfo(Symbol(), MODE_LOTSIZE)))+avgEntryPrice;\r
216             }\r
217           }\r
218          \r
219          string commentSt1 = "\nBias "+bias + ", Orders "+totalOrders+", Target " +DoubleToStr(targetPrice,4) ;\r
220         \r
221         ObjectCreate("CommentStr1",OBJ_LABEL,0,0,0);\r
222          ObjectSet("CommentStr1",OBJPROP_XDISTANCE,5);\r
223          ObjectSet("CommentStr1",OBJPROP_YDISTANCE,60);\r
224          ObjectSet("CommentStr1",OBJPROP_WIDTH,5);\r
225          ObjectSetText("CommentStr1",commentSt1,12,"Arial",MediumSpringGreen);\r
226     \r
227     }\r
228     \r
229     \r
230     void resetAccountCalc(){\r
231       DollarProfitTarget = StrToDouble(DoubleToStr(AccountBalance()*ProfitPct/100.0,2)); \r
232       valLastFlatEq = AccountBalance(); \r
233       valTargetFlatEq =   valLastFlatEq +  DollarProfitTarget;\r
234       Print("\nDollarProfitTarget ...... "+DollarProfitTarget+" valLastFlatEq "+valLastFlatEq);\r
235     }\r
236     \r
237     \r
238 //+------------------------------------------------------------------+\r
239 //|                 Close all of the open trades.                    |\r
240 //+------------------------------------------------------------------+\r
242 void CloseAllTrades()\r
244  \r
245     for(int i = 0; i < OrdersTotal(); i++)\r
246     {\r
247       OrderSelect(i,SELECT_BY_POS,MODE_TRADES);\r
249       if (OrderMagicNumber() == MagicNumber)\r
250       {\r
251         if (OrderType() == OP_BUY)\r
252         {\r
253           Comment("In full closure mode.  Closing a ", OrderSymbol(), " buy trade...");\r
254           Print("======================================================== In full closure mode.  Closing a ", OrderSymbol(), " buy trade...");\r
255           bool closeStatus = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(), MODE_BID),Slippage,Blue);\r
256            if (!closeStatus) {\r
257              Print("Close Buy failed with error #",GetLastError());  \r
258               int check=GetLastError();\r
259                if(check!=0) Print("Close Buy failed with error: ",ErrorDescription(check));             \r
260           }\r
261           Sleep(100);\r
262         }    \r
263         else\r
264         if (OrderType() == OP_SELL)\r
265         {\r
266           Comment("In full closure mode.  Closing a ", OrderSymbol(), " sell trade...");\r
267           Print("============================================================In full closure mode.  Closing a ", OrderSymbol(), " sell trade...");\r
268           closeStatus = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(), MODE_ASK),Slippage,Red);\r
269            if (!closeStatus) {\r
270               Print("Close Sell failed with error #",GetLastError());    \r
271                check=GetLastError();\r
272                if(check!=0) Print("Close Sell failed with error: ",ErrorDescription(check));           \r
273           }\r
274           Sleep(100);\r
275         }else if (OrderType() == OP_BUYSTOP)\r
276         {\r
277           Comment("In full closure mode.  Closing pending order ", OrderSymbol(), " buy trade...");\r
278           Print("======================================================== In full closure mode.  Closing a ", OrderSymbol(), " buy trade...");\r
279           closeStatus = OrderDelete(OrderTicket(),Blue);\r
280           if (!closeStatus) {\r
281               Print("Close Buy Stop failed with error #",GetLastError());       \r
282                check=GetLastError();\r
283                if(check!=0) Print("Close Buy Stop failed with error: ",ErrorDescription(check));         \r
284           }\r
285           Sleep(100);\r
286         }    \r
287         else\r
288         if (OrderType() == OP_SELLSTOP)\r
289         {\r
290           Comment("In full closure mode.  Closing pending order ", OrderSymbol(), " sell trade...");\r
291           Print("============================================================In full closure mode.  Closing a ", OrderSymbol(), " sell trade...");\r
292           closeStatus=OrderDelete(OrderTicket(),Red);\r
293           if (!closeStatus) {\r
294               Print("Close Sell Stop with error #",GetLastError());   \r
295                check=GetLastError();\r
296                if(check!=0) Print("Close Sell Stop with error: ",ErrorDescription(check));             \r
297           }\r
298           Sleep(100);\r
299         }\r
300       }\r
301     }\r
302     Sleep(10000);\r
303     resetAccountCalc();\r
304     startPrice=iOpen( NULL, PERIOD_M15, 0);\r
305     Print("resetting startPrice ...... "+startPrice);\r
306    initOrdersDone=false;\r
307   \r
311 void CloseAllPendingOrders()\r
313  \r
314     for(int i = 0; i < OrdersTotal(); i++)\r
315     {\r
316       OrderSelect(i,SELECT_BY_POS,MODE_TRADES);\r
318       if (OrderMagicNumber() == MagicNumber)\r
319       {\r
320        // Print(" order type "+OrderType());\r
321          if (OrderType() == OP_BUYSTOP)\r
322         {\r
323           Comment("..... Closing pending order ", OrderSymbol(), " buy trade...");\r
324           Print("========================================================  Closing a ", OrderSymbol(), " buy stop order...");\r
325           bool closeStatus = OrderDelete(OrderTicket(),Blue);\r
326           if (!closeStatus) {\r
327               Print("Close Buy Stop failed with error #",GetLastError());       \r
328                int check=GetLastError();\r
329                if(check!=0) Print("Close Buy Stop failed with error: ",ErrorDescription(check));         \r
330           }\r
331           Sleep(100);\r
332         }    \r
333         else\r
334         if (OrderType() == OP_SELLSTOP)\r
335         {\r
336           Comment("..... Closing pending order ", OrderSymbol(), " sell trade...");\r
337           Print("=========================================================== Closing a ", OrderSymbol(), " sell stop order...");\r
338           closeStatus=OrderDelete(OrderTicket(),Red);\r
339           if (!closeStatus) {\r
340               Print("Close Sell Stop with error #",GetLastError());   \r
341                check=GetLastError();\r
342                if(check!=0) Print("Close Sell Stop with error: ",ErrorDescription(check));             \r
343           }\r
344           Sleep(100);\r
345         }\r
346       }\r
347     }\r
348      \r
351 double getEAPL()\r
353    double overallPL;\r
354    totalOrders=0;\r
355    \r
356    avgEntryPrice=0;\r
357    double totalEntryPrice=0.0;\r
358    \r
359    \r
360     for(int i = 0; i < OrdersTotal(); i++)\r
361     {\r
362       OrderSelect(i,SELECT_BY_POS,MODE_TRADES);\r
363      \r
364       if (OrderMagicNumber() == MagicNumber && ( (OrderType() == OP_BUY)||(OrderType() == OP_SELL)))\r
365       {      \r
366       \r
367        double curPL = OrderProfit() + OrderSwap() + OrderCommission();\r
368        double openPrice = OrderOpenPrice();\r
369      //  Print(" openPrice "+openPrice);\r
370        totalEntryPrice = totalEntryPrice + openPrice;\r
371       //  Print(" totalEntryPrice "+totalEntryPrice);\r
372        // Print("curPL "+curPL);\r
373        overallPL = overallPL + curPL;\r
374        totalOrders++;\r
375        \r
376        }\r
377     }\r
378     \r
379     if(totalOrders>0) {\r
380       avgEntryPrice = totalEntryPrice/totalOrders;\r
381       //Print(" avgEntryPrice "+avgEntryPrice+" totalOrders "+totalOrders+" totalEntryPrice "+totalEntryPrice);\r
382     }\r
383    \r
384   \r
385   return(overallPL);\r
388         \r
389      void placeSellStopOrder(){\r
390      \r
391           double bid = MarketInfo(Symbol(), MODE_BID) ; \r
392           \r
393           double sellPrice = bid - (PipStep*pip);          \r
394           double sellSL = bid;\r
395           \r
396           \r
397           Print("Placing sell stop order at "+sellPrice+" with SL at "+sellSL);\r
398          \r
399          int  ticketshort = OrderSend(Symbol(),OP_SELLSTOP,LotSize,NormalizeDouble(sellPrice, digits),\r
400                                       Slippage,NormalizeDouble(sellSL, digits),0,"Short Speed Train",MagicNumber,0,Red);\r
401                                       \r
402           if (ticketshort < 0) {\r
403             //  Print("Short OrderSend OP_SELLSTOP failed with error #",GetLastError()); \r
404               int check=GetLastError();\r
405                if(check!=0) Print("Short OrderSend OP_SELLSTOP failed with error: ",ErrorDescription(check));    \r
406               return;\r
407           }\r
408           \r
409           Print("Sell stop order placed with ticket "+ticketshort+"  at "+sellPrice);\r
410           \r
411           shortOrderCount++;\r
412             //Sleep(1000);          \r
413             \r
414          \r
415      \r
416      }\r
417        \r
418      void placeBuyStopOrder(){\r
419      \r
420           double ask = MarketInfo(Symbol(), MODE_ASK) ; \r
421           \r
422           double buyPrice = ask + (PipStep*pip);          \r
423           double buySL = ask;\r
424           \r
425           \r
426           Print("Placing buy stop order at "+buyPrice+" with SL at "+buySL);\r
427          \r
428          int  ticketlong = OrderSend(Symbol(),OP_BUYSTOP,LotSize,NormalizeDouble(buyPrice, digits),\r
429                                       Slippage,NormalizeDouble(buySL, digits),0,"Long Speed Train",MagicNumber,0,Blue);\r
430                                       \r
431           if (ticketlong < 0) {\r
432               //Print("Long OrderSend OP_BUYSTOP failed with error #",GetLastError()); \r
433               \r
434               int check=GetLastError();\r
435                if(check!=0) Print("Long OrderSend OP_BUYSTOP failed with error: ",ErrorDescription(check));\r
437               \r
438               return;\r
439           }\r
440           \r
441           Print("Buy stop order placed with ticket "+ticketlong+"  at "+buyPrice);\r
442           \r
443           longOrderCount++;\r
444            // Sleep(1000);          \r
445             \r
446          \r
447      \r
448      }\r
449       \r
450       \r
451       void placeInitBuyOrder(){\r
452      \r
453           double ask = MarketInfo(Symbol(), MODE_ASK) ; \r
454           \r
455           double buySL = ask - (PipStep*pip);          \r
456          \r
457           \r
458           \r
459           Print("Placing buy  order at "+ask+" with SL at "+buySL);\r
460          \r
461          int  ticketlong = OrderSend(Symbol(),OP_BUY,LotSize,Ask,\r
462                                       Slippage,0,0,"Long Speed Train",MagicNumber,0,Blue);\r
463                                       \r
464           if (ticketlong < 0) {\r
465              // Print("Long OrderSend OP_BUY failed with error #",GetLastError()); \r
466                int check=GetLastError();\r
467                if(check!=0) Print("Long OrderSend OP_BUY failed with error: ",ErrorDescription(check));  \r
468               return;\r
469           }\r
470           \r
471           Print("Buy stop order placed with ticket "+ticketlong+"  at "+ask);\r
472           \r
473            int ticketlong1 = OrderModify(ticketlong,OrderOpenPrice(),NormalizeDouble(buySL, digits),0,0,Blue);\r
474             Sleep(1000);\r
475             \r
476            // Print("ticketlong1 "+ticketlong1);\r
477           \r
478              if (ticketlong1 < 1) {\r
479              // Print("Long OrderModify failed with error #",GetLastError()); \r
480                check=GetLastError();\r
481               // Print("check "+check);\r
482                if(check!=0) Print("Long OrderModify failed with error: ",ErrorDescription(check));\r
483             }\r
484             \r
485           \r
486           longOrderCount++;        \r
487      \r
488      }\r
489       \r
490       \r
491       void placeInitSellOrder(){\r
492      \r
493           double bid = MarketInfo(Symbol(), MODE_BID) ; \r
494           \r
495           double sellSL = bid + (PipStep*pip);            \r
496           \r
497           Print("Placing sell  order at "+bid+" with SL at "+sellSL);\r
498          \r
499          int  ticketshort = OrderSend(Symbol(),OP_SELL,LotSize,NormalizeDouble(bid, digits),\r
500                                       Slippage,0,0,"Short Speed Train",MagicNumber,0,Red);\r
501                                       \r
502           if (ticketshort < 0) {\r
503               //Print("Short OrderSend OP_SELL failed with error #",GetLastError()); \r
504                int check=GetLastError();\r
505                if(check!=0) Print("Short OrderSend OP_SELL failed with error: ",ErrorDescription(check));\r
506               return;\r
507           }\r
508           \r
509           Print("Sell stop order placed with ticket "+ticketshort+"  at "+bid);\r
510           \r
511           int ticketshort1 = OrderModify(ticketshort,OrderOpenPrice(),NormalizeDouble(sellSL, digits),0,0,Red);\r
512             Sleep(1000);\r
513           \r
514              if (ticketshort1 < 1) {\r
515             //  Print("Short OrderModify failed with error #",GetLastError()); \r
516                check=GetLastError();\r
517                if(check!=0) Print("Short OrderModify failed with error: ",ErrorDescription(check));\r
518             }\r
519           \r
520           shortOrderCount++;        \r
521      \r
522      }\r
523       \r
524       \r
525       void moveBuyOrderToBE(){\r
526          int lastTicket=0;\r
527       \r
528          for(int j = 0; j < OrdersTotal(); j++)\r
529         {\r
530             OrderSelect(j,SELECT_BY_POS,MODE_TRADES);\r
531            // Print("order type "+OrderType());\r
532             \r
533             if (OrderMagicNumber() == MagicNumber && OrderType() == OP_BUYSTOP)\r
534                {\r
535                   int ticketId = OrderTicket() ;\r
536                   //Print("ticketId "+ticketId);\r
537                  if( ticketId>   lastTicket) lastTicket=ticketId;  \r
538                   \r
539                  //Print("lastTicket "+lastTicket);            \r
540                }      \r
541        }\r
542        \r
543        if(lastTicket >0) {             \r
544             Print(" ----------------------- Moving long order number "+lastTicket+ " to BE at  "+OrderOpenPrice());    \r
545        \r
546             int ticketlong = OrderModify(lastTicket,OrderOpenPrice(),OrderOpenPrice(),0,0,Blue);\r
547           \r
548                                       \r
549             if (ticketlong < 0) {\r
550                  //  Print("Long SL2BE order failed with error #",GetLastError()); \r
551                    int check=GetLastError();\r
552                if(check!=0) Print("Long SL2BE order failed with error: ",ErrorDescription(check));\r
553                    return;\r
554             }\r
555               \r
556            \r
557         }           \r
558          \r
559      \r
560      }\r
561      \r
562      \r
563      \r
564          \r
565       \r
566       \r
567       \r
568       void moveSellOrderToBE(){\r
569          int lastTicket=0;\r
570       \r
571          for(int j = 0; j < OrdersTotal(); j++)\r
572         {\r
573             OrderSelect(j,SELECT_BY_POS,MODE_TRADES);\r
575            // Print("order type "+OrderType());\r
576             if (OrderMagicNumber() == MagicNumber && OrderType() == OP_SELLSTOP)\r
577                {\r
578                   int ticketId = OrderTicket() ;\r
579                  // Print(" ticketId "+ticketId);    \r
580                   if( ticketId>   lastTicket) lastTicket=ticketId; \r
581                  // Print(" lastTicket "+lastTicket);             \r
582                }      \r
583        }\r
584        \r
585           \r
586        \r
587        \r
588        \r
589        if(lastTicket>0) {\r
590        \r
591             Print("------------ Moving short order number "+lastTicket+ " to BE at  "+OrderOpenPrice());\r
592             int ticketshort = OrderModify(lastTicket,OrderOpenPrice(),OrderOpenPrice(),0,0,Red);          \r
593                                       \r
594             if (ticketshort < 0) {\r
595                    //Print("Short SL2BE order failed with error #",GetLastError()); \r
596                      int check=GetLastError();\r
597                if(check!=0) Print("Short SL2BE order failed with error: ",ErrorDescription(check));\r
598                    return;\r
599             }\r
600              \r
601         }\r
602           \r
603                         \r
604          \r
605      \r
606      }\r
607       \r
608      \r
609   \r
610    \r