cm-Gread_MA

Author: Copyright � 2014, mqlgold@narod.ru
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself It automatically opens orders when conditions are reached
Indicators Used
Moving average indicator
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
cm-Gread_MA
//+------------------------------------------------------------------+
#property copyright "Copyright © 2014, mqlgold@narod.ru"
#property link      "mqlgold@narod.ru"
//--------------------------------------------------------------------*/
extern int     period               = 35;       //Ïåðèîä óñðåäíåíèÿ äëÿ âû÷èñëåíèÿ âòîðîé MA.
extern int     Stoploss             = 0;        //ñòîïëîññ îðäåðîâ
extern int     Takeprofit           = 500;      //òåéêïðîôèò îðäåðîâ
extern int     TrailingStop         = 50;       //òðåéëèíãñòîï, åñëè 0, òî íåò òðåéëèíãà
extern int     Step                 = 50;       //øàã ìåæäó îðåðàìè
extern double  Lot                  = 0.1;
extern double  CloseProfitPercent   = 1.0;      //çàêðûòèå âñåõ îðäåðîâ ïðè äîñòèæåíèè ïðèáûëè â ïðîöåíòàõ îò äåïîçèòà
extern int     Magic                = 1000;     //óíèêàëüíûé íîìåð îðäåðîâ ýòîãî ñîâåòíèêà
extern int     Slippage             = 3;        //óíèêàëüíûé íîìåð îðäåðîâ ýòîãî ñîâåòíèêà
extern bool    ReversClose          = false;
//--------------------------------------------------------------------
int init()
{
   return(0);
}
//--------------------------------------------------------------------
int start()
{
   if (!IsTradeAllowed()) 
   {
      DrawLABEL("infoIsTradeAllowed","Òîðãîâëÿ çàïðåùåíà",5,0,Red,1);
      return(0);
   }
   else DrawLABEL("infoIsTradeAllowed","Òîðãîâëÿ ðàçðåøåíà",5,0,Lime,1);
 
   //---
 
   double MAs = iMA(NULL,0,period,0,MODE_EMA,PRICE_OPEN,0);
   double MAs1 = iMA(NULL,0,period,0,MODE_EMA,PRICE_OPEN,1);
   
   //---
   
   int OT,b,s,STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);
   double OSL,OTP,OOP,SL,TP,Profit,StLo;
   bool BUY,SELL;
   for (int i=0; i<OrdersTotal(); i++)
   {    
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      {
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
         { 
            OT  = OrderType(); 
            OSL = NormalizeDouble(OrderStopLoss(),Digits);
            OTP = NormalizeDouble(OrderTakeProfit(),Digits);
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            Profit+=OrderProfit()+OrderSwap()+OrderCommission();
            SL=OSL;TP=OTP;
            if (OT==OP_BUY)
            {
               if (MathAbs(Ask - OOP)<Step*Point) BUY=true;
               b++;
               if (OSL==0 && Stoploss>=STOPLEVEL && Stoploss!=0)
               {
                  SL = NormalizeDouble(OOP - Stoploss   * Point,Digits);
               } 
               if (OTP==0 && Takeprofit>=STOPLEVEL && Takeprofit!=0)
               {
                  TP = NormalizeDouble(OOP + Takeprofit * Point,Digits);
               } 
               if (MAs1>MAs && TrailingStop>=STOPLEVEL && TrailingStop!=0)
               {
                  StLo = NormalizeDouble(Bid - TrailingStop*Point,Digits); 
                  if (StLo > OSL) SL = StLo;
               }
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            }
            if (OT==OP_SELL)
            {
               if (MathAbs(Bid - OOP)<Step*Point) SELL=true;
               s++;
               if (OSL==0 && Stoploss>=STOPLEVEL && Stoploss!=0)
               {
                  SL = NormalizeDouble(OOP + Stoploss   * Point,Digits);
               }
               if (OTP==0 && Takeprofit>=STOPLEVEL && Takeprofit!=0)
               {
                  TP = NormalizeDouble(OOP - Takeprofit * Point,Digits);
               }
               if (MAs1<MAs && TrailingStop>=STOPLEVEL && TrailingStop!=0)
               {
                  StLo = NormalizeDouble(Ask + TrailingStop*Point,Digits); 
                  if (StLo < OSL || OSL==0) SL = StLo;
               }
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            }
         }
      }
   } 
   double AB = AccountBalance();
   if (Profit>AB/100*CloseProfitPercent) CloseAll(-1);
   //---
   DrawLABEL("infoBalance",StringConcatenate("Balance ",DoubleToStr(AB,2)),10,30,Aqua,1);
   DrawLABEL("infoEquity",StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2)),10,50,Aqua,1);
   DrawLABEL("infoFreeMargin",StringConcatenate("Free ",DoubleToStr(AccountFreeMargin(),2)),10,70,Aqua,1);
   DrawLABEL("infoProfit",StringConcatenate("Profit ",DoubleToStr(Profit,2)),10,90,Color(Profit>=0,Lime,Red),1);
 
   DrawLABEL("infoÎðäåðîâ Buy" ,StringConcatenate("Buy ",b),10,110,Aqua,1);
   DrawLABEL("infoÎðäåðîâ Sell",StringConcatenate("Sell ",s),10,130,Aqua,1);
   
   //---
   
   if (MAs1<MAs)
   {
      DrawARROW("infoMA",Time[0],Bid,236,Blue,1);
      if (!BUY) SendOrder(OP_BUY,Lot,NormalizeDouble(Ask,Digits));
      if (ReversClose && s>0) CloseAll(OP_SELL);
   }
 
   //---
 
   if (MAs1>MAs)
   {
      DrawARROW("infoMA",Time[0],Bid,238,Red,1);
      if (!SELL) SendOrder(OP_SELL,Lot,NormalizeDouble(Bid,Digits));
      if (ReversClose && b>0) CloseAll(OP_BUY);
   }
 
   return(0);
}
//--------------------------------------------------------------------
bool CloseAll(int tip)
{
   bool error=true;
   int err,nn,OT,OMN;
   while(true)
   {
      for (int j = OrdersTotal()-1; j >= 0; j--)
      {
         if (OrderSelect(j, SELECT_BY_POS))
         {
            OMN = OrderMagicNumber();
            if (OrderSymbol() == Symbol() && OMN == Magic)
            {
               OT = OrderType();
               if (OT!=tip && tip!=-1) continue;
               if (OT==OP_BUY) 
               {
                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),Slippage,Blue);
                  if (error) Comment("Çàêðûò îðäåð N ",OrderTicket(),"  ïðèáûëü ",OrderProfit(),
                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));
               }
               if (OT==OP_SELL) 
               {
                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),Slippage,Red);
                  if (error) Comment("Çàêðûò îðäåð N ",OrderTicket(),"  ïðèáûëü ",OrderProfit(),
                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));
               }
               if (!error) 
               {
                  err = GetLastError();
                  if (err==129) 
                  {  Comment("Íåïðàâèëüíàÿ öåíà ",TimeToStr(TimeCurrent(),TIME_SECONDS));
                     RefreshRates();
                     continue;
                  }
                  if (err==146) 
                  {
                     if (IsTradeContextBusy()) Sleep(2000);
                     continue;
                  }
                  Comment("Îøèáêà ",err," çàêðûòèÿ îðäåðà N ",OrderTicket(),
                          "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));
               }
            }
         }
      }
      int n=0;
      for (j = 0; j < OrdersTotal(); j++)
      {
         if (OrderSelect(j, SELECT_BY_POS))
         {
            OMN = OrderMagicNumber();
            if (OrderSymbol() == Symbol() && OMN == Magic)
            {
               OT = OrderType();
               if (OT!=tip && tip!=-1) continue;
               if (OT==OP_BUY || OT==OP_SELL) n++;
            }
         }  
      }
      if (n==0) break;
      nn++;
      if (nn>10) {Alert(Symbol()," Íå óäàëîñü çàêðûòü âñå ñäåëêè, îñòàëîñü åùå ",n);return(0);}
      Sleep(1000);
      RefreshRates();
   }
   return(1);
}
//--------------------------------------------------------------------
 
int deinit()
{
   if (!IsTesting()) remove_objects("info");
   return(0);
}
//-----------------------------------------------------------------
color Color(bool P,color a,color b)
{
   if (P) return(a);
   else return(b);
}
//------------------------------------------------------------------
bool SendOrder(int tip, double lot, double p)
{
   int nn;
   while(true)
   {
      RefreshRates();
      if (OrderSend(Symbol(),tip,lot,p,Slippage,0,0,NULL,Magic,0)==-1)
      {
         Print("OrderSend Error ",GetLastError()," Lot ",lot);
         Sleep(1000);
      }
      else return(1);
      nn++;
      if (nn>10) return(0);
   }
   return(0);
}
//--------------------------------------------------------------------
void DrawLABEL(string name, string Name, int X, int Y, color clr, int C)
{
   if (ObjectFind(name)==-1)
   {
      ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
      ObjectSet(name, OBJPROP_CORNER, C);
      ObjectSet(name, OBJPROP_XDISTANCE, X);
      ObjectSet(name, OBJPROP_YDISTANCE, Y);
   }
   ObjectSetText(name,Name,10,"Arial",clr);
}
//--------------------------------------------------------------------
int remove_objects(string PreName)
{
   for(int k=ObjectsTotal()-1; k>=0; k--) 
   {
      string Obj_Name=ObjectName(k);
      string Head=StringSubstr(Obj_Name,0,StringLen(PreName));
 
      if (Head==PreName)
      {
         ObjectDelete(Obj_Name);
      }                  
   }
   Comment("");
   return(0);
}
//--------------------------------------------------------------------+
void DrawARROW(string name, datetime T, double P, int CODE, color clr, int WIDTH)
{
   if (ObjectFind(name)!=-1) ObjectDelete(name);
   ObjectCreate(name,OBJ_ARROW,0,T,P,0,0,0,0);                     
   ObjectSet   (name,OBJPROP_ARROWCODE,CODE);
   ObjectSet   (name,OBJPROP_COLOR, clr);
   ObjectSet   (name,OBJPROP_WIDTH, WIDTH);
}
//+------------------------------------------------------------------+

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 ---