Middle_Moving_Average_v2

Author: Copyright 2016, DLim0n4IK.DK
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reached
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites
Middle_Moving_Average_v2
ÿþ//+------------------------------------------------------------------+

//|                                     Middle Moving Average v2.mq4 |

//|                                   "Copyright 2016, DLim0n4IK.DK" |

//|                       https://www.mql5.com/ru/users/dlim0n4ik.dk |

//+------------------------------------------------------------------+

#property copyright "Copyright 2016, DLim0n4IK.DK"

#property link      "https://www.mql5.com/ru/users/dlim0n4ik.dk"

#property version   "161.214"

#property description "@>AB>9 A>25B=8: >A=>20=K9 =0 Moving Average"

#property strict

#define MAGICMA  20161214

extern double  Lots           =0.01;   // 07<5@ ;>B0

extern double  MaximumRisk    =0.02;   //0:A8<0;L=K9 @8A:

extern double  DecreaseFactor =3;      //DF

extern double  StopLoss       = 0;     //#@>25=L C1KB:>2 (2 ?C=:B0E)

extern double  TakeProfit     = 0;     //#@>25=L ?@81K;8 (2 ?C=:B0E)

//--------------------------------------------------------------------

extern string              hMA_Info          = "0AB@>9:8 hMA";   //0@0<5B@K

extern ENUM_TIMEFRAMES     hMA_TimeFrame     = PERIOD_CURRENT;    //"09<D@59<

extern int                 hMA_Period        = 20;                //5@8>4

extern int                 hMA_Shift         = 0;                 //!<5I5=85 

extern ENUM_MA_METHOD      hMA_Method        = MODE_EMA;          //5B>B @0AG5B0 

extern ENUM_APPLIED_PRICE  hMA_Applied_Price = PRICE_HIGH;        //Applied price

//--------------------------------------------------------------------

extern string              cMA_Info          = "0AB@>9:8 cMA";   //0@0<5B@K

extern ENUM_TIMEFRAMES     cMA_TimeFrame     = PERIOD_CURRENT;    //"09<D@59<

extern int                 cMA_Period        = 20;                //5@8>4

extern int                 cMA_Shift         = 0;                 //!<5I5=85 

extern ENUM_MA_METHOD      cMA_Method        = MODE_EMA;          //5B>B @0AG5B0 

extern ENUM_APPLIED_PRICE  cMA_Applied_Price = PRICE_CLOSE;        //Applied price

//--------------------------------------------------------------------

extern string              oMA_Info          = "0AB@>9:8 oMA";   //0@0<5B@K

extern ENUM_TIMEFRAMES     oMA_TimeFrame     = PERIOD_CURRENT;    //"09<D@59<

extern int                 oMA_Period        = 20;                //5@8>4

extern int                 oMA_Shift         = 0;                 //!<5I5=85 

extern ENUM_MA_METHOD      oMA_Method        = MODE_EMA;          //5B>B @0AG5B0 

extern ENUM_APPLIED_PRICE  oMA_Applied_Price = PRICE_OPEN;        //Applied price

//--------------------------------------------------------------------

extern string              lMA_Info          = "0AB@>9:8 lMA";   //0@0<5B@K

extern ENUM_TIMEFRAMES     lMA_TimeFrame     = PERIOD_CURRENT;    //"09<D@59<

extern int                 lMA_Period        = 20;                //5@8>4

extern int                 lMA_Shift         = 0;                 //!<5I5=85 

extern ENUM_MA_METHOD      lMA_Method        = MODE_EMA;          //5B>B @0AG5B0 

extern ENUM_APPLIED_PRICE  lMA_Applied_Price = PRICE_LOW;        //Applied price

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

{

//---



//---

return(INIT_SUCCEEDED);

}

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

{

//---



//---

}

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

{

//--- @>25@8< 4>AB0B>G=0 ;8 2 8AB>@88 10@>2 4;O 0=0;870 -------------

if(Bars<100 || IsTradeAllowed()==false) return;

//--- calculate open orders by current symbol

if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();

else                                    CheckForClose();

//---

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|   $C=:F8O @0AG5B0 :>;8G5AB20 >B:@KBKE >@5@>2                     |

//+------------------------------------------------------------------+

int CalculateCurrentOrders(string symbol)

{

int Count = 0;

for(int index = 0; index < OrdersTotal();index++)

   {

   if(OrderSelect(index,SELECT_BY_POS,MODE_TRADES)==false) break;

   if(OrderSymbol()==symbol && OrderMagicNumber()==MAGICMA)

      {

      if(OrderType()==OP_BUY || OrderType()==OP_SELL)  Count++;

      }

   }

return(Count);

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|    0AG5B >?B8<0;L=>3> @07<5@0 ;>B0                               |

//+------------------------------------------------------------------+

double LotsOptimized()

{

//--- =8F80;870F8O ?5@5<5=KE ----------------------------------------

string   symbol   /* <O A8<2>;0 */                      = Symbol();

int      orders   /* >;8G5AB2> >@45@>2 2 8AB>@88 */     = HistoryTotal();

int      losses   /* >;8G5AB2>C1KB>G=KE >@45@>2 */      = 0;

int      digits   /* >;8G5AB2> 7=0:>2 ?>A;5 70?OB>9 */  = 2;

double   lot      /*  07<5@ ;>B0 */                      = Lots;

//--------------------------------------------------------------------

lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,digits); //K15@5< @07<5@ ;>B0

//--- >4AG8B05< :>;8G5AB2> C1KB>G=KE >@45@>2 ------------------------

if(DecreaseFactor>0)

   {

   for(int index = orders-1; index >= 0; index--)

      {

      if(OrderSelect(index,SELECT_BY_POS,MODE_HISTORY)==false)

         {

         Print("Error in history!");

         break;

         }

      if(OrderSymbol()==symbol && OrderMagicNumber()==MAGICMA)

         {

         if(OrderType()==OP_BUY || OrderType()==OP_SELL)

            {

            if(OrderProfit()>0) break;

            if(OrderProfit()<0) losses++;

            }

         }

      }

   if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,digits);

   }

//--------------------------------------------------------------------

if(lot<0.01) lot=0.01;

return(lot);

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|   $C=:F8O @0ABG5B0 8 >?@545;5=8O A>>B25BAB28O CA;>289            |                                                                  |

//+------------------------------------------------------------------+

string Signal()

{

//--- =8F80;870F8O ?5@5<5=KE ----------------------------------------

string   symbol   /* <O A8<2>;0 */ = Symbol();

int  digits   = (int) SymbolInfoInteger(symbol,SYMBOL_DIGITS); //

int shift = 1;

//--------------------------------------------------------------------

double hMA = NormalizeDouble(iMA(symbol,hMA_TimeFrame,hMA_Period,hMA_Shift,hMA_Method,hMA_Applied_Price,shift),digits);

double cMA = NormalizeDouble(iMA(symbol,cMA_TimeFrame,cMA_Period,cMA_Shift,cMA_Method,cMA_Applied_Price,shift),digits);

double oMA = NormalizeDouble(iMA(symbol,oMA_TimeFrame,oMA_Period,oMA_Shift,oMA_Method,oMA_Applied_Price,shift),digits);

double lMA = NormalizeDouble(iMA(symbol,lMA_TimeFrame,lMA_Period,lMA_Shift,lMA_Method,lMA_Applied_Price,shift),digits);

double MA = NormalizeDouble((hMA+cMA+oMA+lMA) / 4,digits);

//--------------------------------------------------------------------

if (Open[1] < MA && Close[1] > MA)return("BUY");

if (Open[1] > MA && Close[1] < MA)return("SELL");

//--------------------------------------------------------------------

return("NO Signal");

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|   @>25@O5< CA;>28O =0 >B:@KB85 >@45@0                           |

//+------------------------------------------------------------------+

void CheckForOpen()

{

if(Volume[0]>1) return; //0G=5< B>@3>20BL =0 =>2>< 10@5

//--- @>25@O5< 8 >B:@K205< >@45@ =0 ?>:C?:C -------------------------

if(Signal()=="BUY")

   {

   OpenOrder("BUY");

   return;

   }

//--- @>25@O5< 8 >B:@K205< >@45@ =0 ?@>406C -------------------------

if(Signal()=="SELL")

   {

   OpenOrder("SELL");

   return;

   }

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|   @>25@O5< CA;>28O =0 70:@KB85 >@45@0                           |

//+------------------------------------------------------------------+

void CheckForClose()

{

//--- =8F80;870F8O ?5@5<5=KE ----------------------------------------

string   symbol   /* <O A8<2>;0 */ = Symbol();

if(Volume[0]>1) return;

for(int index = 0; index < OrdersTotal(); index++)

   {

   if(OrderSelect(index,SELECT_BY_POS,MODE_TRADES)==false) break;

   if(OrderSymbol()!=symbol || OrderMagicNumber()!=MAGICMA) continue;

//--------------------------------------------------------------------

   if(OrderType()==OP_BUY)

      {

      if(Signal()=="SELL")

         {

         if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))

               Print("OrderClose error ",GetLastError());

         }

      break;

      }

//--------------------------------------------------------------------

   if(OrderType()==OP_SELL)

      {

      if(Signal()=="BUY")

         {

         if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))

               Print("OrderClose error ",GetLastError());

         }

      break;

      }

   }

}

//+------------------------------------------------------------------+



//+------------------------------------------------------------------+

//|   $C=:F8O >B:@KB8O >@45@0                                        |

//|------------------------------------------------------------------|

//|   0@0<5B@K 70?@>A0:                                             |

//|   OpenOrder("BUY")  - B:@KB85 >@45@0 =0 ?>:C?:C (BUY)           |

//|   OpenOrder("SELL") - B:@KB85 >@45@0 =0 ?@>406C (SELL)          |

//+------------------------------------------------------------------+

void OpenOrder(string type)

{

//--- =8F80;870F8O ?5@5<5=KE ----------------------------------------

int               ticket      = 0;

string            symbol      /* C8<2>; */                  = Symbol();

ENUM_ORDER_TYPE   cmd         /* ">@3>20O >?5@0F8O */       = ORDER_TYPE_BUY; 

double            volume      /* >;8G5AB2> ;>B>2 */        = LotsOptimized();

double            price       /* &5=0 */                    = 0.0;

int               slippage    /* @>A:0;L7K20=85 */         = 3; 

double            stoploss    /* stop loss */               = 0;

double            takeprofit  /* take profit */             = 0;

string            comment     /* ><<5=B0@89 */             = NULL;

int               magic       /* 45=B8D8:0B>@ */           = MAGICMA;

datetime          expiration  /* C@>: 8AB5G5=8O >@45@0 */   = 0;

color             arrow_color /* &25B */                    = clrNONE;

//--- >;CG8< 8=D>@<0F8N ---------------------------------------------

double point   = MarketInfo(symbol,MODE_POINT);  // 0?@>A Point

int digits  = (int)MarketInfo(symbol,MODE_DIGITS);  // 0?@>A Digits

//--- >4AB028< 7=0G5=8O ?>4 A>>B25BAB2CNI89 B8? >@45@0 --------------

if (type == "BUY")

   {

   cmd = ORDER_TYPE_BUY;

   price = NormalizeDouble(Ask,digits);

   if (StopLoss > 0) stoploss = NormalizeDouble(Bid - StopLoss * point,digits);

   if (TakeProfit > 0) takeprofit = NormalizeDouble(Ask + TakeProfit * point,digits);

   arrow_color = Green;

   }

if (type == "SELL")

   {

   cmd = ORDER_TYPE_SELL;

   price = NormalizeDouble(Bid,digits);

   if (StopLoss > 0) stoploss = NormalizeDouble(Ask + StopLoss * point,digits); 

   if (TakeProfit > 0) takeprofit = NormalizeDouble(Bid - TakeProfit * point,digits);

   arrow_color = Red;

   }

//--- @>25@8< 4>AB0B>G=> ;8 A@54AB2 4;O >B:@KB8O >@45@0 -------------

double free_margin=AccountFreeMarginCheck(symbol,cmd,volume);

if(free_margin<0) //A;8 =0 AG5BC =5 E20B05B A@54AB2

   {

   string oper=(cmd==OP_BUY)? "Buy":"Sell";

   Print("Not enough money for ", oper," ",volume, " ", symbol, " Error code=",GetLastError());

   return;

   }

//--------------------------------------------------------------------

if(free_margin>0)

   {ticket = OrderSend(symbol,cmd,volume,price,slippage,stoploss,takeprofit,comment,magic,expiration,arrow_color);}

//--------------------------------------------------------------------

}

//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---