bleh
[mqlkit.git] / SpeedTrainNeuNeu.mq4
blob5a33ca1109fac374a1cc96ab94a71efffb6d5c38
1 #property copyright "Zarko Asenov"\r
2 #property link      "jaltoh.6x.to"\r
3 \r
4 \r
5 #define RETRIES 5\r
6 #define SLIPPAGE 3\r
7 \r
8 \r
9 /* General functionality settings */\r
10 extern string       _ = " General Settings ";\r
11 extern double       Lot_Size = 0.12;\r
12 extern double       Pip_Step = 0; // On variable spread brokers keep it over average spread, 0 automatic step\r
13 extern bool         Add_Spread_to_Pip_Step = false; // For fixed spread brokers - be sure about this!\r
14 extern bool         Add_Min_Stop_to_Pip_Step = false;\r
15 extern double       Order_Lifetime_Hours = 1; // Pending order life time\r
16 extern double       Max_spread = 22; // dont send orders with prices above this spread\r
17 extern double       Hours_Bring_Even = 0; // wait for N hours before an active order stop loss is pushed up\r
18 extern bool         Debug_Print = true;\r
19 extern double       Panic_Profit = -200.0;\r
20 extern int          Midprice_Time_Frame = PERIOD_H1;\r
21 extern double       Calmdown_Hours = 2;\r
22 extern double       Go_After = 0.4; // periods\r
23 extern int          Magic_Number =  775225426;\r
25 /* Grid Bandwidth */\r
26 extern string       __ = " Market noise bandwidth ";\r
27 extern int          BW_Back_Period = 39;\r
28 extern int          BW_Time_Frame = 0;\r
30 /* Sentiment */\r
31 extern string       ___ = " Sentiment";\r
32 extern double       Sentiment_Threshold = 0.15;\r
33 extern int          Sentiment_MA_Bars = 12;\r
34 extern double       Sentiment_Time_Frame = 0;\r
35 extern int          Sentiment_Bars_Check = 1;\r
36 extern double       Sentiment_Time_Factor = 0.01;\r
38 /* Average True Range */\r
39 extern string       ____ = " ATR";\r
40 extern double       ATR_Threshold = 1.5;\r
41 extern int          ATR_Time_Frame = PERIOD_H1;\r
42 extern int          ATR_Period = 6;\r
43 extern int          ATR_Period_Long = 22;\r
44 extern int          ATR_MA_Bars = 6;\r
45 extern int          ATR_Bars_Check = 2;\r
48 /* Global variables */\r
49 double current_atr = 0.0;\r
51 double start_price = 0.0;\r
52 bool init_done = false;\r
53 double spread;\r
55 double pipstep_adjusted;\r
56 double pipstep_pt;\r
58 int order_lifetime;\r
59 double time_bring_even;\r
61 double tick_value;\r
62 double tick_value_pt;\r
64 double min_stop;\r
65 double min_stop_pt;\r
67 double total_spread_loss;\r
68 int start_bin;\r
69 double inv_sentiment_threshold;\r
70 double calmdown_period;\r
72 int num_orders;\r
73 double auto_step;\r
74 datetime prev_bar_time;\r
81 int init()\r
82 {\r
83      if (RefreshRates() == false) \r
84           Print("Refresh rates failed!");\r
85      \r
87      order_lifetime = MathRound(Order_Lifetime_Hours * 3600);\r
88      time_bring_even = 3600 * Hours_Bring_Even;\r
89      \r
90      min_stop = MarketInfo(Symbol(), MODE_STOPLEVEL);\r
91      min_stop_pt = Point * MarketInfo(Symbol(), MODE_STOPLEVEL);\r
92      \r
93      tick_value = MarketInfo(Symbol(), MODE_TICKVALUE); \r
94      tick_value_pt = Point * MarketInfo(Symbol(), MODE_TICKVALUE); \r
96      pipstep_pt = Pip_Step * Point;\r
98      inv_sentiment_threshold = -1.0 * Sentiment_Threshold;\r
99      calmdown_period = Calmdown_Hours * 3600;\r
101      num_orders = count_orders();\r
102      auto_step = 0;\r
103      prev_bar_time = 0;\r
104     \r
105      Print(\r
106           "Min stop: " + min_stop + \r
107           ", Tick Value: " + tick_value + \r
108           ", Number of our orders: " + num_orders + \r
109           ", Grid height: " + pipstep_pt);\r
110    \r
111      return(0);\r
115 bool end_is_neigh(int cur_period)\r
117   return (true);\r
119   if ( (TimeCurrent() - Time[0]) < (cur_period * 60. * Go_After) ) return (false);\r
120   else return (true);\r
121 }  \r
123 double\r
124 calc_profit()\r
126     double presult = 0.0;\r
127     total_spread_loss = 0.0;\r
128     tick_value = MarketInfo(Symbol(), MODE_TICKVALUE);\r
129     \r
130     for (int i = 0; i < OrdersTotal(); i++) {\r
131         OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
132         \r
133         if ((OrderSymbol() != Symbol() || OrderMagicNumber() != Magic_Number) && \r
134           OrderType() != OP_BUY && OrderType() != OP_SELL) continue;\r
136         double spread_loss = tick_value * OrderLots() * spread;\r
137         presult += (OrderProfit() - spread_loss);\r
138         total_spread_loss += spread_loss;\r
139     }\r
141     return (presult);   \r
144 datetime last_go_time = 0;\r
146 void\r
147 close_all_orders()\r
149      close_all_orders_type(OP_BUY);\r
150      close_all_orders_type(OP_SELL);\r
153 void\r
154 close_all_orders_type(int order_type)\r
156      for (int i = 0; i < OrdersTotal(); i++) {\r
157         \r
158           OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
159             \r
160           if (OrderSymbol() != Symbol() || OrderMagicNumber() != Magic_Number) continue;\r
161          \r
162           if (OrderType() != order_type) continue;\r
163          \r
164           switch ( OrderType() ) {\r
165             \r
166           case OP_BUY:\r
167                OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), SLIPPAGE, Blue);\r
168                break;\r
169                     \r
170           case OP_SELL:\r
171                OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), SLIPPAGE, Red);\r
172                break;\r
173                     \r
174           case OP_SELLSTOP: \r
175           case OP_BUYSTOP:\r
176                OrderDelete( OrderTicket() );\r
177                break;\r
178                     \r
179           default:\r
180                if (Debug_Print) Print("Uknown order type " + OrderType() + " of order #" + OrderTicket() );\r
181           }\r
182      }\r
185 int\r
186 count_orders()\r
188      int count = 0;\r
189      for (int i = 0; i < OrdersTotal(); i++) {\r
190         \r
191           OrderSelect(i, SELECT_BY_POS, MODE_TRADES);\r
192             \r
193           if ( (OrderSymbol() != Symbol()) || (OrderMagicNumber() != Magic_Number) ) continue;\r
195           count++;         \r
196      }\r
197      \r
198      return (count);\r
202 bool\r
203 atr_is_go(int num_pos)\r
205     for (int i = 0; i < num_pos; i++) {\r
206         current_atr = iCustom(Symbol(), ATR_Time_Frame, "ATR ratio", ATR_Period, ATR_Period_Long, 0.0, 1.0, ATR_MA_Bars, false, 1, i);\r
207         double ma_atr = iCustom(Symbol(), ATR_Time_Frame, "ATR ratio", ATR_Period, ATR_Period_Long, 0.0, 1.0, ATR_MA_Bars, false, 0, i);\r
208         \r
209         if (current_atr < ma_atr || current_atr < ATR_Threshold) return (false);\r
210     }\r
211         \r
212    return (true);\r
215 bool\r
216 in_trend()\r
218      return ( atr_is_go(ATR_Bars_Check) );\r
222 #define NEUTRAL 0\r
223 #define BULLISH 1\r
224 #define BEARISH 2\r
226 int sentiment = NEUTRAL;\r
228 double\r
229 get_grid()\r
231      return ( \r
232                1.2 * iCustom(\r
233                          Symbol(), BW_Time_Frame, "Bandwidth", \r
234                          0, BW_Back_Period, 1, "", false, PRICE_WEIGHTED, \r
235                          2, 0) \r
236              );\r
239 double\r
240 get_sentiment(int index, int bar)\r
242      return ( \r
243                iCustom(\r
244                     Symbol(), Sentiment_Time_Frame, "jmarket_sentiment", \r
245                     Sentiment_MA_Bars, Sentiment_MA_Bars, 0, Sentiment_MA_Bars, Sentiment_Time_Factor, 0.9, 0, "", "", "", NEUTRAL, "", "", "", \r
246                     index, bar) \r
247             );\r
250 bool\r
251 go_buy()\r
253      double threshold_adjusted = Sentiment_Threshold;\r
255      for (int ix = 0; ix < Sentiment_Bars_Check; ix++) {\r
256           if (get_sentiment(0, ix) < threshold_adjusted) return (false);\r
257      }    \r
258      \r
259      sentiment = BULLISH;\r
260      return (true);\r
263 bool\r
264 go_sell()\r
266      double inv_threshold_adjusted = inv_sentiment_threshold;\r
268      for (int ix = 0; ix < Sentiment_Bars_Check; ix++) {\r
269           if (get_sentiment(0, ix) > inv_threshold_adjusted) return (false);\r
270      }\r
271      \r
272      sentiment = BEARISH;\r
273      return (true);\r
276 double\r
277 get_auto_step()\r
279      // init auto step\r
280      if (auto_step == 0) auto_step = get_grid();\r
281      \r
282      // return previous unchaged step if already trading\r
283      if (num_orders > 0) return (auto_step);\r
285      // same bar same step\r
286      if (Time[0] == prev_bar_time) return (auto_step);\r
287      \r
289      // Lets see ..\r
290      \r
291      // get recommended grid height\r
292      double _step = get_grid();\r
293      \r
294      // if errored out stick with previous one\r
295      if (_step == 0) {\r
296           Print("Fatal, got zero auto step. Returning old step " + auto_step);\r
297           return (auto_step);\r
298      } else {\r
299           auto_step = _step;\r
300      }\r
301      \r
302      if (Debug_Print == true) Print("New step set to: " + auto_step);\r
303      \r
304      prev_bar_time = Time[0];\r
305      return (auto_step);\r
308 int \r
309 start()\r
311     num_orders = count_orders();\r
312     if (num_orders < 1) {\r
313           init_done = false; // reinit!\r
314           last_go_time = 0;\r
315     }\r
318     RefreshRates();       \r
319     spread = Point * MarketInfo(Symbol(), MODE_SPREAD);\r
320         \r
321     if (\r
322      (last_go_time != 0) && \r
323      ((TimeCurrent() - last_go_time) > calmdown_period) \r
324      ) \r
325     {\r
326           close_all_orders();\r
327           last_go_time = 0;\r
328     }\r
330     if (pipstep_pt != 0) pipstep_adjusted = pipstep_pt;\r
331     else pipstep_adjusted = get_auto_step();\r
332     \r
333     /* nothing to do with step 0 */\r
334     if (pipstep_adjusted == 0) {\r
335           Print("Fatal, pipstep is zero! Skipping tick.");\r
336           return (0);\r
337     }\r
338     \r
339     if (Add_Spread_to_Pip_Step) pipstep_adjusted += spread;\r
340     if (Add_Min_Stop_to_Pip_Step) pipstep_adjusted += min_stop_pt;\r
341     \r
342     \r
343     if ( init_done == false ) {\r
344     /* fire up new grid */\r
345            \r
346         if ( go_buy() ) {\r
347             start_price = Ask;\r
348             start_bin = MathFloor(start_price / pipstep_adjusted);\r
349             if (Debug_Print) Print("Init go long, start price: " + start_price + " bin: " + start_bin);\r
350             \r
351             place_pending_buy(start_price, order_lifetime + TimeCurrent() );\r
352             //place_pending_sell(start_price, order_lifetime + TimeCurrent() );\r
353             place_buy(start_price);\r
354             \r
355             last_go_time = TimeCurrent();\r
356             init_done = true;\r
357         } else if ( go_sell() ) {\r
358             start_price = Bid;\r
359             start_bin = MathFloor(start_price / pipstep_adjusted);\r
360             if (Debug_Print) Print("Init go short, start price: " + start_price + " bin: " + start_bin);\r
361             \r
362     //place_pending_buy(start_price, order_lifetime + TimeCurrent() );\r
363             place_sell(start_price);\r
364             place_pending_sell(start_price, order_lifetime + TimeCurrent() );\r
365             \r
366             last_go_time = TimeCurrent();\r
367             init_done = true;\r
368         }\r
369         \r
370     } else if (start_price != 0) {\r
371     /* in trend */\r
373          if ( Ask > (start_price + pipstep_adjusted) ) {\r
374     \r
375                start_price = Ask;\r
376                int bin = MathFloor(start_price / pipstep_adjusted);\r
377         \r
378                if (Debug_Print) Print("Go buy new start_price:" + start_price + " bin: " + bin);\r
379     \r
380                /* things to do once per bin */\r
381                if (start_bin != bin) {\r
382                     move_up_buys_sl();\r
383                     start_bin = bin;\r
384                }\r
385                        \r
386                // place buy stops\r
387                if ( go_buy() ) {\r
388                     close_all_orders_type(OP_SELL);\r
389                     place_pending_buy(start_price, order_lifetime + TimeCurrent());\r
390                     place_pending_sell(start_price, order_lifetime + TimeCurrent());\r
391                     last_go_time = TimeCurrent();\r
392                } else if ( go_sell() ) {\r
393                     close_all_orders_type(OP_BUY);\r
394                     place_pending_sell(start_price, order_lifetime + TimeCurrent());\r
395                     place_pending_buy(start_price, order_lifetime + TimeCurrent());\r
396                     last_go_time = TimeCurrent();\r
397                }\r
398           } else if ( Bid < (start_price - pipstep_adjusted) ) {\r
399     \r
400                start_price = Bid;\r
401                bin = MathFloor(start_price / pipstep_adjusted);\r
402         \r
403                if (Debug_Print) Print("Go sell new start_price: " + start_price + " bin: " + bin);\r
405                /* things to do once per bin */\r
406                if (start_bin != bin) {\r
407                     move_down_sells_sl();\r
408                     start_bin = bin;\r
409                }          \r
410         \r
411                // place sell stops\r
412                if ( go_sell() ) {\r
413                     close_all_orders_type(OP_BUY);\r
414                     place_pending_sell(start_price, order_lifetime + TimeCurrent());\r
415                     place_pending_buy(start_price, order_lifetime + TimeCurrent());\r
416                     last_go_time = TimeCurrent();\r
417                } else if ( go_buy() ) {\r
418                     close_all_orders_type(OP_SELL);\r
419                     place_pending_buy(start_price, order_lifetime + TimeCurrent());\r
420                     place_pending_sell(start_price, order_lifetime + TimeCurrent());\r
421                     last_go_time = TimeCurrent();\r
422                }\r
423          }\r
424          \r
425           \r
426     }\r
427     \r
428     if (Debug_Print) {\r
429         Comment(\r
430             "SpeedTrain Forte\nby DrZed 2011\n" +\r
431             "Symbol: " + Symbol() + "\n" +\r
432             "Spread: " + spread + "\n" +\r
433             "ATR value: " + current_atr + "\n" +\r
434             "Pipstep adjusted: " + pipstep_adjusted + "\n" +\r
435             "Last orders price: " + start_price + "\n" +\r
436             "Current close M15 price: " + iClose(NULL, PERIOD_M15, 0) + "\n" +\r
437             "Total spread loss: " + total_spread_loss + " USD\n"\r
438             );\r
439     }\r
442 void \r
443 place_pending_buy(double base_price, datetime lifetime)\r
445      double buy_price = base_price + pipstep_adjusted;\r
446      double stop_loss = base_price;\r
447      double take_profit = 0;\r
448           \r
449      if (Debug_Print) Print("Placing buy stop order at " + buy_price + " with SL at " + stop_loss);\r
450          \r
451      int ticket = -1;\r
452      int retrct = 0;\r
453      while (ticket < 0 && retrct < RETRIES) {\r
454          \r
455           ticket = OrderSend(\r
456                                Symbol(), \r
457                                OP_BUYSTOP, \r
458                                Lot_Size, \r
459                                NormalizeDouble(buy_price, Digits),\r
460                                SLIPPAGE, \r
461                                NormalizeDouble(stop_loss, Digits), \r
462                                NormalizeDouble(take_profit, Digits), \r
463                                "",\r
464                                Magic_Number, \r
465                                lifetime, \r
466                                Blue);\r
467           retrct++;\r
468     }\r
469                                       \r
470     if (ticket < 0) {\r
471         Print("Long OrderSend failed with error #", GetLastError()); \r
472         return;\r
473     }\r
474           \r
475     if (Debug_Print) Print("Buy stop order placed with ticket " + ticket + " at " + buy_price);\r
477     \r
478 void \r
479 place_pending_sell(double base_price, datetime lifetime)\r
481      double sell_price = base_price - pipstep_adjusted;\r
482      double stop_loss = base_price;\r
483      double take_profit = 0.0;\r
484           \r
485      if (Debug_Print) Print("Placing sell stop order at " + sell_price + " with SL at " + stop_loss);\r
486          \r
487      int ticket = -1;\r
488      int retrct = 0;\r
489      while (ticket < 0 && retrct < RETRIES) {\r
490          \r
491           ticket = OrderSend(\r
492                          Symbol(), \r
493                          OP_SELLSTOP, \r
494                          Lot_Size, \r
495                          NormalizeDouble(sell_price, Digits),\r
496                          SLIPPAGE, \r
497                          NormalizeDouble(stop_loss, Digits), \r
498                          NormalizeDouble(take_profit, Digits), \r
499                          "", \r
500                          Magic_Number, \r
501                          lifetime, \r
502                          Red);\r
503           retrct++;\r
504     }\r
505                                       \r
506     if (ticket < 0) {\r
507         Print("Short OrderSend failed with error #", GetLastError()); \r
508         return;\r
509     }\r
510           \r
511     if (Debug_Print) Print(\r
512                          "Sell stop order placed with ticket " + ticket + " at " + sell_price);\r
514       \r
515 void \r
516 place_buy(double base_price)\r
518      double stop_loss = base_price - pipstep_adjusted;\r
520      if (Debug_Print) Print("Placing long order at " + base_price + " with SL at " + stop_loss);\r
521          \r
522      int ticket = -1;\r
523      int retrct = 0;\r
524      while (ticket < 0 && retrct < RETRIES) {\r
525           ticket = OrderSend(\r
526                     Symbol(),\r
527                     OP_BUY, \r
528                     Lot_Size, \r
529                     NormalizeDouble(base_price, Digits),\r
530                     SLIPPAGE, \r
531                     NormalizeDouble(stop_loss, Digits), \r
532                     0, \r
533                     "", \r
534                     Magic_Number, \r
535                     0, \r
536                     Blue);\r
537           retrct++;\r
538     }\r
539             \r
540     if (Debug_Print == false) return;\r
542     if (ticket < 0) Print("Long OrderSend failed with error #", GetLastError()); \r
543     else \r
544         Print("Buy stop order placed with ticket " + ticket + "  at " + Ask);\r
546       \r
547       \r
548 void \r
549 place_sell(double base_price)\r
551      double stop_loss = base_price + pipstep_adjusted;\r
552           \r
553      if (Debug_Print) Print("Placing short order at " + base_price + " with SL at " + stop_loss);\r
555      int ticket = -1;\r
556      int retrct = 0;\r
557      while (ticket < 0 && retrct < RETRIES) {\r
558          \r
559           ticket = OrderSend(\r
560                     Symbol(), \r
561                     OP_SELL, \r
562                     Lot_Size, \r
563                     NormalizeDouble(base_price, Digits), \r
564                     SLIPPAGE, \r
565                     NormalizeDouble(stop_loss, Digits), \r
566                     0, \r
567                     "", \r
568                     Magic_Number, \r
569                     0, \r
570                     Red);\r
571           retrct++;\r
572           \r
573     }\r
574                                       \r
575     if (ticket < 0) {\r
576           if (Debug_Print) Print("Short OrderSend failed with error #", GetLastError());\r
577           return;\r
578     }\r
579           \r
580     if (Debug_Print) Print("Sell stop order placed with ticket " + ticket + "  at " + base_price);\r
583 void\r
584 move_up_buys_sl()\r
586     for(int j = 0; j < OrdersTotal(); j++)\r
587     {\r
588         OrderSelect(j, SELECT_BY_POS, MODE_TRADES);\r
589             \r
590         if (\r
591           (OrderMagicNumber() == Magic_Number) && \r
592           (OrderType() == OP_BUY) &&\r
593           (TimeCurrent() - OrderOpenTime()) > time_bring_even) {\r
594           \r
595                 double stop_loss = OrderStopLoss();\r
597                 for (\r
598                     int new_stop_loss_bin = MathRound( (Ask - min_stop_pt - stop_loss) / pipstep_adjusted );\r
599                     new_stop_loss_bin > 0;\r
600                     new_stop_loss_bin--) {\r
601                 \r
602                     double new_stop_loss = NormalizeDouble(stop_loss + (new_stop_loss * pipstep_adjusted), Digits);\r
603                 \r
604                     if (Debug_Print) Print(\r
605                                    "Moving long ticket " + OrderTicket() + " stop loss " + stop_loss + \r
606                                    " to " + new_stop_loss + ", current ask price " + Ask);\r
607             \r
608                     bool res = false;\r
609                     int retrct = 0;\r
610                     while (res == false && retrct < RETRIES) {\r
611                          res = OrderModify(\r
612                               OrderTicket(),                                \r
613                               OrderOpenPrice(), \r
614                               new_stop_loss, \r
615                               OrderTakeProfit(), \r
616                               OrderExpiration(), \r
617                               Blue);\r
618                          retrct++;\r
619                     }\r
620                \r
621                     // Order modify failed.\r
622                     if (res == false) Print("Failed moving order " + OrderTicket() + " stop loss to " + new_stop_loss);\r
623                     else break;\r
624                }\r
625                \r
626                if (OrderProfit() < Panic_Profit) OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), SLIPPAGE, Blue);\r
627          }\r
629     }\r
631       \r
632 void \r
633 move_down_sells_sl()\r
635     for(int j = 0; j < OrdersTotal(); j++)\r
636     {\r
637         OrderSelect(j, SELECT_BY_POS, MODE_TRADES);\r
638             \r
639         if (\r
640           (OrderMagicNumber() == Magic_Number) && \r
641           (OrderType() == OP_SELL) &&\r
642           ((TimeCurrent() - OrderOpenTime()) > time_bring_even)) {\r
643             \r
644                 double stop_loss = OrderStopLoss();\r
645                 \r
646                 for (\r
647                     int new_stop_loss_bin = MathRound( (stop_loss - min_stop_pt - Bid) / pipstep_adjusted );\r
648                     new_stop_loss_bin > 0;\r
649                     new_stop_loss_bin--) {\r
650                     \r
651                     double new_stop_loss = NormalizeDouble(stop_loss - (new_stop_loss_bin * pipstep_adjusted), Digits);\r
652                     if (Debug_Print) Print(\r
653                                    "Moving short SL @ " + OrderOpenPrice() + " SL " + stop_loss + \r
654                                    " to " + new_stop_loss + " current BID " + Bid);\r
656                     bool res = false;\r
657                     int retrct = 0;\r
658                     while (res == false && retrct < RETRIES) {\r
659  \r
660                          res = OrderModify(\r
661                               OrderTicket(),\r
662                               OrderOpenPrice(),\r
663                               new_stop_loss,\r
664                               OrderTakeProfit(),\r
665                               OrderExpiration(), \r
666                               Red);\r
667                          retrct++;\r
668                     }\r
669                     \r
670                     // Order modify failed.\r
671                     if (res == false) Print("Failed moving order " + OrderTicket() + " stop loss to " + new_stop_loss);\r
672                     else break;\r
673                }\r
675  \r
676                if (OrderProfit() < Panic_Profit) OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), SLIPPAGE, Red);\r
677         }\r
679     }\r