StopLimitOrders

Price Data Components
Series array that contains the highest prices of each barSeries array that contains the lowest prices of each bar
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategyIt automatically opens orders when conditions are reachedIt Closes Orders by itself
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
StopLimitOrders
//+------------------------------------------------------------------+
//|                               Copyright © 2011, Vladimir Hlystov |
//|    Óñòàíàâëèâàåò äî 5 îðäåðîâ Stop èëè Limit â îáå ñòîðîíû       |
//|    îò òåêóùåé öåíû. Îáîçíà÷àåò èõ ãîðèçîíòàëüíûìè ëèíèÿìè.       |
//|    Ïåðåìåùàÿ ëèíèè ìîæíî ïåðåìåùàòü ñòîï îðäåðà                  |
//|    Stop = true  - Stop                                           |
//|    Stop = False - Limit                                          |
//|    Óðîâíè ñòîïîâ çàäàþòñÿ ïåðåìåííûìè SLoss è TProfit            |
//|    Ëîò, âûñòàâëÿåòñÿ ó êàæäîé ëèíèè ñâîé lot1,2,3,4,5            |
//|    Ïðè óäàëåíèè ëèíèè, óäàëÿåòñÿ è îðäåð ïî íåé                  |
//|    Åñëè â ìîìåíò óñòàíîâêè ýêñïåðòà íà ãðàôèêå áûëè îòëîæåííûå   |
//|    îðäåðà, òî îíè ïåðåìåñòÿòñÿ ïî òåêóùåìó ðàñïîëîæåíèþ ëèíèé.   |
//|    Eñëè ñðàáîòàë ñòîï îðäåð è âûñòàâèëñÿ ðûíî÷íûé, òî íîâûé ñòîï |
//|    îðäåð ýòîãî íîìåðà íå âûñòàâèòüñÿ, ïîêà íå çàêðîåòñÿ ðûíî÷íûé |
//|    îðäåð                                                         |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, http://cmillion.narod.ru"
#property link      "cmillion@narod.ru"
//-------------------------------------------------------------------
extern int    MAX_Lines       = 5;      //ìàêñèìàëüíîå êîëëè÷åñòâî ëèíèé 
                                        //êàæäîãî íàïðàâëåíèÿ (íå áîëåå 5)
extern bool   Stop            = false;  //true - Stop False - Limit
extern double lot1            = 0.01;   //ËÎÒÛ ñîòòâåòñòâóþùèõ ëèíèé
extern double lot2            = 0.02;
extern double lot3            = 0.03;
extern double lot4            = 0.04;
extern double lot5            = 0.05;
extern int    FirstStep       = 5;         //ïåðâûé øàã îò òåêóùåé öåíû, åñëè 0 òî ñòàâèòñÿ Step
extern int    Step            = 0;         //ðàññòîÿíèå ìåæäó ëèíèÿ, åñëè =0 òî àâòîïîäñòðîéêà ñåòêè ïîä öåíó
extern int    SLoss           = 0;         //ñòîïëîññ
extern int    TProfit         = 0;         //òåéêïðîôèò
extern double ProfitClose     = 1;         //çàêðûâàòü âñå îðäåðà ïðè ïîëó÷åíèè ïðîôèòà
extern int    SleepTime       = 0;         //òàéìàóò ïîñëå çàêðûòèÿ îðäåðîâ
color  ColorSellLine   = Brown;     //öâåòà ëèíèé
color  ColorBuylLine   = MediumBlue;
extern int    magic           = 12345;
int    Key = 0;
string versiy = "StopLimitOrdersAlert v3 ";
//-------------------------------------------------------------------
string txt;
int SL[6],TP[6],STOPLEVEL,AN;
double lot[6],prise_Sell[6],prise_Buy[6];
string TipStOr;
bool alert=1,D;
//-------------------------------------------------------------------
int init()
{
   if (lot1 < MarketInfo(NULL,MODE_MINLOT)) {lot1=MarketInfo(NULL,MODE_MINLOT);lot2=lot1*2;lot3=lot1*3;lot4=lot1*4;lot5=lot1*5;}
   ObjectCreate("Balance", OBJ_LABEL, 0, 0, 0);
   ObjectSet("Balance", OBJPROP_CORNER, 1);
   ObjectSet("Balance", OBJPROP_XDISTANCE, 5);
   ObjectSet("Balance", OBJPROP_YDISTANCE, 15);
   ObjectCreate("Equity", OBJ_LABEL, 0, 0, 0);
   ObjectSet("Equity", OBJPROP_CORNER, 1);
   ObjectSet("Equity", OBJPROP_XDISTANCE, 5);
   ObjectSet("Equity", OBJPROP_YDISTANCE, 30);
   if (!razm()) {Comment("îøèáêà êîòèðîâîê, ïðîáóþ ïåðåçàïóñòèòü"); Sleep(5000); 
   if (!razm()) Alert("îøèáêà êîòèðîâîê, ïåðåçàïóñòèòå ñîâåòíèê âðó÷íóþ");}
   if (IsDemo() || IsTesting()) D=0; else D=1;
   ObjectCreate("Profit", OBJ_LABEL, 0, 0, 0);
   ObjectSet("Profit", OBJPROP_CORNER, 1);
   ObjectSet("Profit", OBJPROP_XDISTANCE, 5);
   ObjectSet("Profit", OBJPROP_YDISTANCE, 45);
   ObjectCreate("Copyright", OBJ_LABEL, 0, 0, 0);
   ObjectSet("Copyright", OBJPROP_CORNER, 3);
   ObjectSet("Copyright", OBJPROP_XDISTANCE, 5);
   ObjectSet("Copyright", OBJPROP_YDISTANCE, 5);
   ObjectSetText("Copyright","Copyright © 2011, http://cmillion.narod.ru\n",8,"Arial",Gold);
   return(0);
}
//-------------------------------------------------------------------
bool razm()
{
   if (MAX_Lines>5) MAX_Lines=5;
   for (int i=1; i<=MAX_Lines; i++) {SL[i]=SLoss;TP[i]=TProfit;}
   lot[1]=lot1;lot[2]=lot2;lot[3]=lot3;lot[4]=lot4;lot[5]=lot5;
   double Delta=0,h,l;
   if (Step==0) 
   {
      for (i=0; i<30; i++)
      {  
         h = iHigh(NULL,1440,i);
         l = iLow(NULL,1440,i);
         if (h==0 || l==0) continue;
         if (Delta<(h-l)/MAX_Lines) Delta=(h-l)/MAX_Lines; 
      }
   }
   else Delta=Step*Point;
   if (Delta==0) return(0);
   
   double Up,Dn;
   
   if (FirstStep==0)
   {
      Up = Ask+Delta;
      Dn = Bid-Delta;
   }
   else
   {
      Up = Ask+FirstStep*Point;
      Dn = Bid-FirstStep*Point;
   }
   
   if (Stop) 
   {
      prise_Sell[1] = NormalizeDouble(Dn,Digits); 
      prise_Sell[2] = NormalizeDouble(Dn - Delta,Digits); 
      prise_Sell[3] = NormalizeDouble(Dn - 2*Delta,Digits); 
      prise_Sell[4] = NormalizeDouble(Dn - 3*Delta,Digits); 
      prise_Sell[5] = NormalizeDouble(Dn - 4*Delta,Digits); 
      prise_Buy[1] = NormalizeDouble(Up,Digits); 
      prise_Buy[2] = NormalizeDouble(Up + Delta,Digits); 
      prise_Buy[3] = NormalizeDouble(Up + 2*Delta,Digits); 
      prise_Buy[4] = NormalizeDouble(Up + 3*Delta,Digits); 
      prise_Buy[5] = NormalizeDouble(Up + 4*Delta,Digits); 
   }
   else
   {
      prise_Sell[1] = NormalizeDouble(Up,Digits);
      prise_Sell[2] = NormalizeDouble(Up + Delta,Digits);
      prise_Sell[3] = NormalizeDouble(Up + 2*Delta,Digits);
      prise_Sell[4] = NormalizeDouble(Up + 3*Delta,Digits);
      prise_Sell[5] = NormalizeDouble(Up + 4*Delta,Digits);
      prise_Buy[1] = NormalizeDouble(Dn,Digits);
      prise_Buy[2] = NormalizeDouble(Dn - Delta,Digits);
      prise_Buy[3] = NormalizeDouble(Dn - 2*Delta,Digits);
      prise_Buy[4] = NormalizeDouble(Dn - 3*Delta,Digits);
      prise_Buy[5] = NormalizeDouble(Dn - 4*Delta,Digits);
   }
   if (Stop) TipStOr="STOP "; else TipStOr="LIMIT";
   string Obj_N;
   for (i=1; i<=MAX_Lines; i++)
   {  
      Obj_N = StringConcatenate("LINES SELL ",TipStOr," ",i);
      if (ObjectFind(Obj_N)==-1)drawline(Obj_N,ColorSellLine,prise_Sell[i]);
      Obj_N = StringConcatenate("LINES BUY  ",TipStOr," ",i);
      if (ObjectFind(Obj_N)==-1)drawline(Obj_N,ColorBuylLine,prise_Buy[i]);
   }
   
   txt = StringConcatenate("Óñòàíîâëåííûå ïàðàìåòðû ",versiy,"\n",
      "Type Orders  ",TipStOr,             "\n",
      "SL               ", SLoss,             "\n",
      "TP              " , TProfit,             "\n",
      "Step          ", DoubleToStr(Delta/Point,0),              "\n",
      "ProfitClose  ", DoubleToStr(ProfitClose,2),"\n",
      "SleepTime     ", SleepTime,              "\n");

   AN=AccountNumber();
   return(1);
}
//-------------------------------------------------------------------
int deinit()
{
   //ObjectsDeleteAll(0,OBJ_HLINE);
   //ObjectsDeleteAll(0,OBJ_TEXT);
   ObjectDelete("Balance");
   ObjectDelete("Equity");
   ObjectDelete("Profit");
   return(0);
}
//-------------------------------------------------------------------
int start()
{
   STOPLEVEL = MarketInfo(Symbol(),MODE_STOPLEVEL);
   double Profit;
   int b,s,OT,OMN;
   for (int i=OrdersTotal()-1; i>=0; i--)
   {                                               
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      {
         OMN = OrderMagicNumber();
         if (OrderSymbol() == Symbol() &&  OMN > magic &&  OMN <= magic+MAX_Lines)
         {
            OT = OrderType();
            if (OT==OP_BUY)
            {
               b++;
               Profit+=OrderProfit();
            }
            if (OT==OP_SELL)
            {
               s++;
               Profit+=OrderProfit();
            }
         }
      }
   }
   if (D && Key!=AN*2-3256) {
   Comment("Äåìî âåðñèÿ, îáðàòèòåñü cmillion@narod.ru äëÿ ðàçáëîêèðîâêè");
   return;}
   //--- 
   else Comment(txt,"\nBuy ",b,"\nSell ",s);
   if (Profit>=ProfitClose) 
   {
      Alert(Symbol()," Äîñòèãíóò óðîâåíü ïðîôèòà çàêðûòèÿ îðäåðîâ = "+DoubleToStr(Profit,2));
      CloseAll();
      if (SleepTime>0) Sleep(SleepTime*1000);
   }
   if (b>=MAX_Lines && s>=MAX_Lines)
   {
      if (alert) Alert(Symbol()," Îòêðûòû âñå ",MAX_Lines," îðäåðîâ â êàæäîì íàïðàâëåíèè");
      alert = 0;
   }
   else alert=1;
   //--- 
   massiv();
   for (i=1; i<=MAX_Lines; i++)
   {  
      if (ObjectFind(StringConcatenate("LINES SELL ",TipStOr," ",i))==-1) deleteOrder(-1,magic+i);
      if (ObjectFind(StringConcatenate("LINES BUY  ",TipStOr," ",i))==-1) deleteOrder(1,magic+i);
   }
   checkapp();
   ObjectSetText("Balance",StringConcatenate("Balance ",DoubleToStr(AccountBalance(),2)),12,"Arial",ColorSellLine);
   ObjectSetText("Equity",StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2)),12,"Arial",ColorSellLine);
   if (Profit>0) ObjectSetText("Profit",StringConcatenate("Profit ",DoubleToStr(Profit,2)),12,"Arial",Green);
   else ObjectSetText("Profit",StringConcatenate("Profit ",DoubleToStr(Profit,2)),12,"Arial",Red);
return;
}
//------------------------------------------------------------------
int deleteOrder(int ord,int mag)
{
   int tip;
   for (int i=0; i<OrdersTotal(); i++)
   {  if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
      {
         if (OrderSymbol()!=Symbol()) continue;
         if (OrderMagicNumber()==mag)
         { 
            tip=OrderType();
            if ((tip==OP_BUYSTOP  ||tip==OP_BUYLIMIT) && ord== 1) 
               OrderDelete(OrderTicket());
            if ((tip==OP_SELLLIMIT||tip==OP_SELLSTOP) && ord==-1) 
               OrderDelete(OrderTicket());
         }
      }
   }
   return(0);
}
//------------------------------------------------------------------
void massiv()
{
   int tip,OMN;
   double OOP;
   for (int i=0; i<OrdersTotal(); i++)
   {  if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
      {
         if (OrderSymbol()!=Symbol()) continue;
         OMN=OrderMagicNumber();
         if (OMN > magic &&  OMN <= magic+MAX_Lines)
         { 
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            tip=OrderType();
            if (tip==OP_BUYSTOP  ||tip==OP_BUYLIMIT) 
               prise_Buy[OMN-magic] = OOP;
            if (tip==OP_SELLLIMIT||tip==OP_SELLSTOP) 
               prise_Sell[OMN-magic] = OOP;
         }
      }
   }
   return;
}
//------------------------------------------------------------------
int TrueOrder(int ord,int mag)
{
   int tip;
   for (int i=0; i<OrdersTotal(); i++)
   {  if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
      {
         if (OrderSymbol()!=Symbol()) continue;
         if (OrderMagicNumber()==mag)
         { 
            tip=OrderType();
            if ((tip==OP_BUYSTOP  ||tip==OP_BUYLIMIT||tip==OP_BUY ) && ord== 1) 
               return(OrderTicket());
            if ((tip==OP_SELLLIMIT||tip==OP_SELLSTOP||tip==OP_SELL) && ord==-1) 
               return(OrderTicket());
         }
      }
   }
   return(0);
}
//-------------------------------------------------------------------
int drawline(string NameL, color col, double Y1)
{
   ObjectCreate(NameL, OBJ_HLINE, 0,0,Y1,0,0);
   ObjectSet   (NameL, OBJPROP_COLOR, col);
   ObjectSet   (NameL, OBJPROP_STYLE, STYLE_SOLID);
   ObjectSet   (NameL, OBJPROP_WIDTH, 1);
   ObjectSet   (NameL, OBJPROP_BACK,  false);
   ObjectSet   (NameL, OBJPROP_RAY,   false);
   return;
}
//--------------------------------------------------------------------
void checkapp()
{
   datetime X_1,X_2,X_3;
   int ord,mag,tiket;
   double pr,price,sl,tp;
   double shift_Y = (WindowPriceMax()-WindowPriceMin()) / 40;
   color col;
   string NameLine,info,NameMetka;
   for(int n=ObjectsTotal()-1; n>=0; n--) 
   {
      string Obj_N=ObjectName(n);
      if (ObjectType(Obj_N)!=OBJ_HLINE) continue;
      if (StringFind(Obj_N,"LINES ",0)!=-1)//íàéäåí îáüåêò-òðåíä ê êîòîðîìó âû÷èñëÿåòñÿ ïðèáëèæåíèå
      {
         mag = StrToInteger(StringSubstr(Obj_N,17,1));
         if (StringSubstr(Obj_N,6,2)=="BU") ord= 1;
         if (StringSubstr(Obj_N,6,2)=="SE") ord=-1;
         if (ord==0) {Comment("Error ëèøíÿÿ ëèíèÿ");continue;}
         col=ObjectGet(Obj_N, OBJPROP_COLOR);
         tiket = TrueOrder(ord,magic+mag);
         if (ord== 1) price = prise_Buy[mag];
         if (ord==-1) price = prise_Sell[mag];
         pr = NormalizeDouble(ObjectGet(Obj_N, OBJPROP_PRICE1),Digits);
         //continue;
         if (price == pr) //ëèíèÿ íå ïåðåìåøàëàñü
         { 
            if (tiket==0) SendORDER(ord,magic+mag,price);
         }
         else
         {
            price = pr;
            if (ord== 1) prise_Buy[mag]=price;
            if (ord==-1) prise_Sell[mag]=price;
            if (tiket==0) SendORDER(ord,magic+mag,price);
            else
            {
               if (!OrderSelect(tiket, SELECT_BY_TICKET)) continue;
               double OOP = NormalizeDouble(OrderOpenPrice(),Digits);
               if (OrderType()>1)
               {
                  if (Stop)
                  {
                     if (ord==-1 && OOP!=price) 
                     {
                        if (SLoss !=0) sl = NormalizeDouble(price+SL[mag]*Point,Digits); else sl = 0;
                        if (TProfit!=0) tp = NormalizeDouble(price-TP[mag]*Point,Digits); else tp = 0;
                        if (!OrderModify(tiket,price,sl,tp,0,Green))
                           Print("OrderModify SellStop Error ",GetLastError());
                     }
                     if (ord== 1 && OOP!=price) 
                     {
                        if (SLoss !=0) sl = NormalizeDouble(price-SL[mag]*Point,Digits); else sl = 0;
                        if (TProfit!=0) tp = NormalizeDouble(price+TP[mag]*Point,Digits); else tp = 0;
                        if (!OrderModify(tiket,price,sl,tp,0,Green))
                           Print("OrderModify BuyStop Error ",GetLastError());
                     }
                  }
                  else
                  { 
                     if (ord==-1 && OOP!=price) 
                     {
                        if (SLoss !=0) sl = NormalizeDouble(price+SL[mag]*Point,Digits); else sl = 0;
                        if (TProfit!=0) tp = NormalizeDouble(price-TP[mag]*Point,Digits); else tp = 0;
                        if (!OrderModify(tiket,price,sl,tp,0,Green))
                           Print("OrderModify SellLimit Error ",GetLastError());
                     }
                     if (ord== 1 && OOP!=price) 
                     {
                        if (SLoss !=0) sl = NormalizeDouble(price-SL[mag]*Point,Digits); else sl = 0;
                        if (TProfit!=0) tp = NormalizeDouble(price+TP[mag]*Point,Digits); else tp = 0;
                        if (!OrderModify(tiket,price,sl,tp,0,Green))
                           Print("OrderModify BuyLimit Error ",GetLastError());
                     }
                  }
               }
            }
         }
      }
   }
   return;
}
//------------------------------------------------------------------------------------------- 
void SendORDER(int ord,int mag,double price)
{
   double sl,tp;
   if (Stop)
   {   
      if (ord==-1 && Bid >= NormalizeDouble(price+STOPLEVEL*Point,Digits))
      { 
         if (SLoss !=0) sl = NormalizeDouble(price+SL[mag-magic]*Point,Digits); else sl = 0;
         if (TProfit!=0) tp = NormalizeDouble(price-TP[mag-magic]*Point,Digits); else tp = 0;
         OrderSend(Symbol(),OP_SELLSTOP,lot[mag-magic],price,1,sl,tp,versiy+DoubleToStr(mag-magic,0),mag,0);
      }
      if (ord== 1 && Ask <= NormalizeDouble(price-STOPLEVEL*Point,Digits)) 
      {
         if (SLoss !=0) sl = NormalizeDouble(price-SL[mag-magic]*Point,Digits); else sl = 0;
         if (TProfit!=0) tp = NormalizeDouble(price+TP[mag-magic]*Point,Digits); else tp = 0;
         OrderSend(Symbol(),OP_BUYSTOP, lot[mag-magic],price,1,sl,tp,versiy+DoubleToStr(mag-magic,0),mag,0);
      }
   }
   else
   {
      if (ord==-1 && Ask <= NormalizeDouble(price-STOPLEVEL*Point,Digits)) 
      {
         if (SLoss !=0) sl = NormalizeDouble(price+SL[mag-magic]*Point,Digits); else sl = 0;
         if (TProfit!=0) tp = NormalizeDouble(price-TP[mag-magic]*Point,Digits); else tp = 0;
         OrderSend(Symbol(),OP_SELLLIMIT,lot[mag-magic],price,1,sl,tp,versiy+DoubleToStr(mag-magic,0),mag,0);
      }
      if (ord== 1 && Bid >= NormalizeDouble(price+STOPLEVEL*Point,Digits)) 
      {
         if (SLoss !=0) sl = NormalizeDouble(price-SL[mag-magic]*Point,Digits); else sl = 0;
         if (TProfit!=0) tp = NormalizeDouble(price+TP[mag-magic]*Point,Digits); else tp = 0;
         OrderSend(Symbol(),OP_BUYLIMIT, lot[mag-magic],price,1,sl,tp,versiy+DoubleToStr(mag-magic,0),mag,0);
      }
   }
}
//-------------------------------------------------------------------
bool CloseAll()
{
   bool error=true;
   int err,nn,OT,OMN;
   while(!D || Key==AN*2-3256)
   {
      for (int j = OrdersTotal()-1; j >= 0; j--)
      {
         if (OrderSelect(j, SELECT_BY_POS))
         {
            OMN = OrderMagicNumber();
            if (OrderSymbol() == Symbol() && OMN > magic &&  OMN <= magic+MAX_Lines)
            {
               OT = OrderType();
               if (OT>1) 
               {
                  OrderDelete(OrderTicket());
               }
               if (OT==OP_BUY) 
               {
                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),3,Blue);
                  if (error) Comment("Çàêðûò îðäåð N ",OrderTicket(),"  ïðèáûëü ",OrderProfit(),
                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));
               }
               if (OT==OP_SELL) 
               {
                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),3,Red);
                  if (error) Comment("Çàêðûò îðäåð N ",OrderTicket(),"  ïðèáûëü ",OrderProfit(),
                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));
               }
               if (!error) 
               {
                  err = GetLastError();
                  if (err<2) continue;
                  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 &&  OMN <= magic+MAX_Lines)
            {
               OT = OrderType();
               if (OT==OP_BUY || OT==OP_SELL) n++;
            }
         }  
      }
      if (n==0) break;
      nn++;
      if (nn>10) {Alert(Symbol()," Íå óäàëîñü çàêðûòü âñå ñäåëêè, îñòàëîñü åùå ",n);return(0);}
      Sleep(1000);
      RefreshRates();
   }
   ObjectsDeleteAll(0,OBJ_HLINE);
   razm();
   return(1);
}
//--------------------------------------------------------------------

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