0
Использование лент Боллинджера позволило бы вам значительно повысить скорость оптимизации и точность входов, проще было бы добавить дополнительный фильтр сигналов. Добавил отключение закрытия по сигналу индикатора. Желательно в паре и по папкам, т.к. ваш индикатор я переименовал.


//+------------------------------------------------------------------+
//|                                                     Sluggish.mq4 |
//|                                              Copyright 2014, AM2 |
//|                                      http://www.forexsystems.biz |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, AM2"
#property link      "http://www.forexsystems.biz"
#property description "Simple expert advisor"

#define MAGIC  20141020
//--- Inputs
extern int    StopLoss     = 1000; // Стоплосс ордера  
extern int    TakeProfit   = 1000; // Тейкпрофит ордера
extern int    TrailingStop = 1000; // Трал ордера
extern int    Slip         = 3;    // Проскальзывание цены
extern int    ClosePos     = 0;    // 0-закрытие по ТП, 1-по сигналу индикатора
extern int    Risk         = 0;    // Риск на сделку в % от депо   
extern double Lots         = 0.1;  // Лот
//----
extern int    BBPer       = 20;    // Период индикатора
extern double BBDev       = 1;     // Отклонение индикатора
//----
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   int    res;
   double BBBuy=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,2,0);
   double BBSell=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,3,0);

//--- sell conditions
   if(BBSell>0)
     {
      res=OrderSend(Symbol(),OP_SELL,fLots(),Bid,Slip,Bid+StopLoss*Point,Bid-TakeProfit*Point,"",MAGIC,0,Red);
     }
//--- buy conditions
   if(BBBuy>0)
     {
      res=OrderSend(Symbol(),OP_BUY,fLots(),Ask,Slip,Ask-StopLoss*Point,Ask+TakeProfit*Point,"",MAGIC,0,Blue);
     }
   
   Comment("\nBuy ",BBBuy, "\nSell ",BBSell);
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double BBBuy=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,2,0);
   double BBSell=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,3,0);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGIC || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(BBSell>0)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,Slip,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(BBBuy>0)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,Slip,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
double fLots()
  {
   double lot=Lots;
   double  lot_min=MarketInfo( Symbol(),MODE_MINLOT); 
   double  lot_max=MarketInfo( Symbol(),MODE_MAXLOT); 
   if (Risk>0)
     {
      lot=fND(AccountBalance()*Risk/100000,2);      
     }
   if (lot<lot_min) lot=lot_min;
   if (lot>lot_max) lot=lot_max;
   return(lot);
  } 
//+------------------------------------------------------------------+
double fND(double d,int n=-1)
  {
   if(n<0) return(NormalizeDouble(d, Digits));
   return(NormalizeDouble(d, n));
  }
//--------------------------------------------------------------------
void Trailing()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
         if(OrderSymbol()==Symbol() || OrderMagicNumber()==MAGIC)
            if(OrderType()==OP_BUY)
              {
               if(TrailingStop>0)
                 {
                  if(Bid-OrderOpenPrice()>TrailingStop*Point)
                    {
                     if(OrderStopLoss()<Bid-TrailingStop*Point)
                       {
                        bool mod=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*Point,OrderTakeProfit(),0,Blue);
                       }
                    }
                 }
              }

      if(OrderType()==OP_SELL)
        {
         if(TrailingStop>0)
           {
            if((OrderOpenPrice()-Ask)>TrailingStop*Point)
              {
               if((OrderStopLoss()>(Ask+TrailingStop*Point)) || (OrderStopLoss()==0))
                 {
                  mod=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TrailingStop*Point,OrderTakeProfit(),0,Red);
                 }
              }
           }
        }
     }
  }  
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(OrdersTotal()<1) CheckForOpen();
   if(ClosePos>0) CheckForClose();
   if(TrailingStop!=0) Trailing();
//---
  }
//+------------------------------------------------------------------+

avatar

AM2

  • 24 января 2015, 21:13
0
Поправил. За день выставляет только один ордер. Посмотрите:



www.opentraders.ru/downloads/568/

avatar

AM2

  • 24 января 2015, 20:23
0
Сейчас увеличивает дополнительный лот:


//+------------------------------------------------------------------+
//|                                                        Reset.mq4 |
//|                                           Copyright © 2014, AM2  |
//|                                      http://www.forexsystems.biz |
//+------------------------------------------------------------------+

#property copyright "Copyright 2014, AM2"
#property link      "http://www.forexsystems.biz"
#property version   "1.00"
#property strict

#define MAGIC  20150121

extern int    StopLoss    = 1900;//Стоплосс всех ордеров
extern int    TakeProfit  = 350; //Тейкпрофит всех ордеров
extern int    StopLimit   = 1;   //Ставим стоповые(0) или лимитные(1) ордера
extern int    Distance    = 250; //Расстояние от цены для установки стопового ордера
extern int    Step        = 250; //Шаг установки стоповых ордеров
extern int    Count       = 10;  //Количество устанавливаемых ордеров стоповых или лимитных 
extern int    Expiration  = 14;  //Время истечения ордера
extern double Lots        = 0.1; //Лот
extern double PLot        = 0.1; //Плюс лот
extern double Lot         = 0.1; //Лот 2
extern double DopLot      = 0.1; //К закрытому лоту + DopLot

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   int res=0,i;
   double lot=Lots;
   datetime expiration=TimeCurrent()+3600*Expiration;
   if(Volume[0]>1) return 0;

//--------------------------------------------------------------------    
   if(OrdersTotal()<=Count)
     {
      for(i=1;i<=Count;i++)
        {
           {
            if(StopLimit==1)
              {
               res=OrderSend(Symbol(),OP_BUYLIMIT, lot,fND(Ask-(Distance*Point+i*Step*Point)),0,fND(Ask-(Distance*Point+i*Step*Point)-StopLoss*Point),fND(Ask-(Distance*Point+i*Step*Point)+TakeProfit*Point),"",MAGIC,expiration,Blue);
               res=OrderSend(Symbol(),OP_SELLLIMIT,lot,fND(Bid+(Distance*Point+i*Step*Point)),0,fND(Bid+(Distance*Point+i*Step*Point)+StopLoss*Point),fND(Bid+(Distance*Point+i*Step*Point)-TakeProfit*Point),"",MAGIC,expiration,Red);
               lot=lot+PLot;
              }
            if(StopLimit==0)
              {
               res=OrderSend(Symbol(),OP_BUYSTOP, lot,fND(Ask+(Distance*Point+i*Step*Point)),0,fND(Ask+(Distance*Point+i*Step*Point)-StopLoss*Point),fND(Ask+(Distance*Point+i*Step*Point)+TakeProfit*Point),"",MAGIC,expiration,Blue);
               res=OrderSend(Symbol(),OP_SELLSTOP,lot,fND(Bid-(Distance*Point+i*Step*Point)),0,fND(Bid-(Distance*Point+i*Step*Point)+StopLoss*Point),fND(Bid-(Distance*Point+i*Step*Point)-TakeProfit*Point),"",MAGIC,expiration,Red);
               lot=lot+PLot;
              }
           }
        }
      }      
//--------------------------------------------------------------------     
   PutResetOrder();
   
   return(0);
  }
//+------------------------------------------------------------------+
double fND(double d,int n=-1)
  {
   if(n<0) return(NormalizeDouble(d, Digits));
   return(NormalizeDouble(d, n));
  }
//+------------------------------------------------------------------+
double FindLastLot()
  {
   int oticket, ticketNumber=0;
   double llot=0;
     if(OrderSelect(OrdersTotal()-1,SELECT_BY_POS,MODE_TRADES))
      {
       if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC && (OrderType()==OP_BUY || OrderType()==OP_SELL))
        {
         oticket=OrderTicket();
         if(oticket>ticketNumber)
          {
           ticketNumber=oticket;
           llot=OrderLots();
          }
        }
      }
    if(DopLot==0 || llot==0) llot=Lot;        
    return(llot);
  }  
//+------------------------------------------------------------------+  
void PutResetOrder()
  {
   int res=0;   
   int ss=0,bs=0;
   double price;
   datetime expiration=TimeCurrent()+3600*Expiration;
   
   for(int i=OrdersTotal()-1;i>=0;i--)
    {
     if(OrderSelect(i, SELECT_BY_POS))
      {  
       if (OrderSymbol()!=Symbol() || OrderMagicNumber()!=MAGIC) continue;
       if (OrderType()==OP_BUYSTOP) bs++;
       if (OrderType()==OP_SELLSTOP) ss++;                     
      }   
    }   
   
   if(OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY))
     {
      if(OrderType()==OP_BUY)
        {
         price=OrderOpenPrice();
         if(OrderProfit()>0 && ss<1)
           {
            res=OrderSend(Symbol(),OP_SELLSTOP,FindLastLot()+DopLot,fND(price),0,fND(price+StopLoss*Point),fND(price-TakeProfit*Point),"",MAGIC,expiration,Red);
            ss++;
           }
        }

      if(OrderType()==OP_SELL && bs<1)
        {
         price=OrderOpenPrice();
         if(OrderProfit()>0)
           {
            res=OrderSend(Symbol(),OP_BUYSTOP,FindLastLot()+DopLot,fND(price),0,fND(price-StopLoss*Point),fND(price+TakeProfit*Point),"",MAGIC,expiration,Blue);
            bs++;
           }
        }
     }
     
   Comment("                       ss = ",ss, " bs = ",bs); 
         
  }
//+------------------------------------------------------------------+

avatar

AM2

  • 24 января 2015, 14:26
0
Посмотрите как вам такая версия:



Файл в базе: www.opentraders.ru/downloads/568/
avatar

AM2

  • 24 января 2015, 12:59
0
Индикатор должен быть под именем «3Bollinger_Bands_Stop_v2». Посмотрите что пишет в журнале, не открывает сделки скорее всего по этой причине.
В файле индикатор переименован.

Добавил трал и расчет лота. Лот расcчитывается по формуле: Баланс*Риск/100000 Т.е. При балансе 10000 рублей и риске 5% лот будет 0.5.

Советник в базе: www.opentraders.ru/downloads/567/
avatar

AM2

  • 24 января 2015, 10:36
0
Посмотрите правильность входов и закрытия ордеров. Остальные функции буду добавлять вечером.




//+------------------------------------------------------------------+
//|                                                     Sluggish.mq4 |
//|                                              Copyright 2014, AM2 |
//|                                      http://www.forexsystems.biz |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, AM2"
#property link      "http://www.forexsystems.biz"
#property description "Simple expert advisor"

#define MAGIC  20141020
//--- Inputs
extern double StopLoss     = 500;
extern double TakeProfit   = 500;
extern int    Slip         = 3;   
extern double Lots         = 0.1;
//----
extern int    BBPer       = 20;
extern double BBDev       = 1;
//----
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   int    res;
   double BBBuy=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,2,0);
   double BBSell=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,3,0);

//--- sell conditions
   if(BBSell>0)
     {
      res=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slip,Bid+StopLoss*Point,Bid-TakeProfit*Point,"",MAGIC,0,Red);
     }
//--- buy conditions
   if(BBBuy>0)
     {
      res=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slip,Ask-StopLoss*Point,Ask+TakeProfit*Point,"",MAGIC,0,Blue);
     }
   
   Comment("\nBuy ",BBBuy, "\nSell ",BBSell);
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double BBBuy=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,2,0);
   double BBSell=iCustom(Symbol(),0,"3Bollinger_Bands_Stop_v2",BBPer,BBDev,3,0);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGIC || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(BBSell>0)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,Slip,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(BBBuy>0)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,Slip,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(OrdersTotal()<1) CheckForOpen();
   else CheckForClose();
//---
  }
//+------------------------------------------------------------------+

avatar

AM2

  • 23 января 2015, 11:02
0
Прошу уточнить входы. Я все правильно понимаю?

avatar

AM2

  • 23 января 2015, 10:02
0
Добавил в советник трал, пересчет с 4 на 5 знак, расчет лота в %от депо.
Лот расcчитывается по формуле: Баланс*Риск/100000 Т.е. При балансе 10000 рублей и риске 5% лот будет 0.5.



Файл в базе: www.opentraders.ru/downloads/566/
avatar

AM2

  • 23 января 2015, 09:22
0
Можно. Разместите ваши пожелания в Стол заказов MQL в выходные сделаю.
avatar

AM2

  • 22 января 2015, 22:40
+1
Да можно. Завтра займусь.
avatar

AM2

  • 22 января 2015, 22:35
0
Каждому ордеру выставляется отдельный тейкпрофит. (Комменты от другого кода просто)

В настройках переменная Lots это лот для каждого ордера сетки, а переменная Lot для замещающего ордера. Скажем Lots может быть 0.1 а Lot 0.8, т.е. то значение которое вы сами укажете.

avatar

AM2

  • 22 января 2015, 10:41
+1
Этот набросок позволяет выставить сетку ордеров с установленными стопами и при достижении тейка, выставляется обратный ордер указанным в настройках лотом, отличающимся от лота сетки.




//+------------------------------------------------------------------+
//|                                                        Reset.mq4 |
//|                                           Copyright © 2014, AM2  |
//|                                      http://www.forexsystems.biz |
//+------------------------------------------------------------------+

#property copyright "Copyright 2014, AM2"
#property link      "http://www.forexsystems.biz"
#property version   "1.00"
#property strict

#define MAGIC  20150121

extern int    StopLoss    = 1900;//Стоплосс всех ордеров
extern int    TakeProfit  = 350; //Тейкпрофит всех ордеров
extern int    StopLimit   = 1;   //Ставим стоповые(0) или лимитные(1) ордера
extern int    Distance    = 250; //Расстояние от цены для установки стопового ордера
extern int    Step        = 250; //Шаг установки стоповых ордеров
extern int    Count       = 10;  //Количество устанавливаемых ордеров стоповых или лимитных 
extern int    Expiration  = 14;  //Время истечения ордера
extern double Lots        = 0.1; //Лот
extern double Lot         = 0.1; //Лот 2

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   int res=0,i;
   datetime expiration=TimeCurrent()+3600*Expiration;
   if(Volume[0]>1) return 0;

//--------------------------------------------------------------------    
   if(OrdersTotal()<=Count)
     {
      for(i=1;i<=Count;i++)
        {
           {
            if(StopLimit==1)
              {
               res=OrderSend(Symbol(),OP_BUYLIMIT,Lots,fND(Ask-(Distance*Point+i*Step*Point)),0,fND(Ask-(Distance*Point+i*Step*Point)-StopLoss*Point),fND(Ask-(Distance*Point+i*Step*Point)+TakeProfit*Point),"",MAGIC,expiration,Blue);
               res=OrderSend(Symbol(),OP_SELLLIMIT,Lots,fND(Bid+(Distance*Point+i*Step*Point)),0,fND(Bid+(Distance*Point+i*Step*Point)+StopLoss*Point),fND(Bid+(Distance*Point+i*Step*Point)-TakeProfit*Point),"",MAGIC,expiration,Red);
              }
            if(StopLimit==0)
              {
               res=OrderSend(Symbol(),OP_BUYSTOP,Lots,fND(Ask+(Distance*Point+i*Step*Point)),0,fND(Ask+(Distance*Point+i*Step*Point)-StopLoss*Point),fND(Ask+(Distance*Point+i*Step*Point)+TakeProfit*Point),"",MAGIC,expiration,Blue);
               res=OrderSend(Symbol(),OP_SELLSTOP,Lots,fND(Bid-(Distance*Point+i*Step*Point)),0,fND(Bid-(Distance*Point+i*Step*Point)+StopLoss*Point),fND(Bid-(Distance*Point+i*Step*Point)-TakeProfit*Point),"",MAGIC,expiration,Red);
              }
           }
        }
      }      
//--------------------------------------------------------------------     
   PutResetOrder();
   
   return(0);
  }
//+------------------------------------------------------------------+
double fND(double d,int n=-1)
  {
   if(n<0) return(NormalizeDouble(d, Digits));
   return(NormalizeDouble(d, n));
  }
//+------------------------------------------------------------------+
void PutResetOrder()
  {
   int res=0;   
   int ss=0,bs=0;
   double price;
   datetime expiration=TimeCurrent()+3600*Expiration;
   
   for(int i=OrdersTotal()-1;i>=0;i--)
    {
     if(OrderSelect(i, SELECT_BY_POS))
      {  
       if (OrderSymbol()!=Symbol() || OrderMagicNumber()!=MAGIC) continue;
       if (OrderType()==OP_BUYSTOP) bs++;
       if (OrderType()==OP_SELLSTOP) ss++;                     
      }   
    }   
   
   if(OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY))
     {
      if(OrderType()==OP_BUY)
        {
         price=OrderOpenPrice();
         if(OrderProfit()>0 && ss<1)
           {
            res=OrderSend(Symbol(),OP_SELLSTOP,Lot,fND(price),0,fND(price+StopLoss*Point),fND(price-TakeProfit*Point),"",MAGIC,expiration,Red);
            ss++;
           }
        }

      if(OrderType()==OP_SELL && bs<1)
        {
         price=OrderOpenPrice();
         if(OrderProfit()>0)
           {
            res=OrderSend(Symbol(),OP_BUYSTOP,Lot,fND(price),0,fND(price-StopLoss*Point),fND(price+TakeProfit*Point),"",MAGIC,expiration,Blue);
            bs++;
           }
        }
     }
     
   Comment("                       ss = ",ss, " bs = ",bs); 
         
  }
//+------------------------------------------------------------------+

avatar

AM2

  • 22 января 2015, 02:25
0
Мне в любом случае будет интересно создать советник который выставляет ордера вместо выбывших. Начал делать.
avatar

AM2

  • 21 января 2015, 22:34
0
Коментом или в журнал принтом выводите:


Comment("\nBuy Price ",ASCBuy,"\nSell Price  ",ASCSell,
           "\nFUP ",FindNearFractal(NULL,0,MODE_UPPER),"\nFDN  ",FindNearFractal(NULL,0,MODE_LOWER));  
avatar

AM2

  • 21 января 2015, 22:13
0
Можете нарисовать на скрине входы и выходы
avatar

AM2

  • 21 января 2015, 17:05