← К каталогу
Исходный код · ID 327

MakeGridLSMA

makegridlsma.mq4
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

MakeGridLSMA — торговый советник для MetaTrader 4, который строит сетку отложенных ордеров в направлении сигнала индикатора LSMA (наименьшее квадратичное отклонение). Советник работает по текущему символу графика и использует заданный магический номер для идентификации своих ордеров и позиций.

Логика входа основана на сравнении двух значений LSMA с разными периодами: при пересечении вверх советник выставляет сетку ордеров Buy Stop, при пересечении вниз — Sell Stop. Ордера Buy Stop размещаются выше текущей цены с шагом GridSize, Sell Stop — ниже. Советник не выставляет встречных ордеров и не является хеджирующей сеткой.

Управление позициями включает сопровождение трейлинг-стопом, а также возможность приостановить или полностью отключить сетку. При включённом suspendGrid удаляются все неисполненные отложенные ордера, при shutdownGrid закрываются все ордера и позиции по данному магическому номеру. Советник также периодически обновляет информацию о прибыли и количестве открытых позиций.

В советнике предусмотрена простая адаптация размера лота в зависимости от баланса счёта. Все параметры задаются через внешние переменные, что позволяет настраивать сетку, уровни стоп-лосса и тейк-профита, интервал обновления и режимы работы.

Настройки программы

НастройкаОписание
Magic number of the trades. must be unique to identify (uniqueGridMagic) Уникальный магический номер — Магический номер ордеров сетки, используемый для идентификации сделок данной сетки.
Lots Размер лота — Базовый размер лота для ордеров сетки; может корректироваться в зависимости от баланса счёта.
pips between orders - grid or mesh size (GridSize) Размер сетки — Расстояние между соседними ордерами сетки в пунктах.
total number of orders to place (GridSteps) Количество шагов сетки — Общее количество ордеров, которое должно быть выставлено в сетке.
Used to limit grid to original when buy and sell stops are filled (ExtendGrid) Расширять сетку — Разрешает добавлять новые ордера в сетку, если количество уже выставленных ордеров меньше заданного числа шагов.
number of ticks to take profit. normally is = grid size but u can override (TakeProfit) Тейк-профит — Размер тейк-профита в пунктах; при значении 0 тейк-профит не устанавливается.
if u want to add a stop loss. normal grids dont use stop losses (StopLoss) Стоп-лосс — Размер стоп-лосса в пунктах; при значении 0 стоп-лосс не устанавливается.
will trail if > 0 (trailStop) Трейлинг-стоп — Величина трейлинг-стопа в пунктах; сопровождение позиций выполняется, если значение больше 0.
Type 1 will trail immediately, type 2 will wait for price to move amount of trailStop (TrailingStopType) Тип трейлинг-стопа — Выбор режима трейлинг-стопа: тип 1 перемещает стоп-лосс сразу, тип 2 ожидает движения цены на величину trailStop.
update orders every x minutes (UpdateInterval) Интервал обновления — Интервал в минутах, с которым советник обновляет ордера и выводимую информацию.
LSMAShortPeriod Короткий период LSMA — Период быстрой линии LSMA, используемой для определения направления сигнала.
LSMALongPeriod Длинный период LSMA — Период медленной линии LSMA, используемой для определения направления сигнала.
PipsDifference Разница в пунктах — Параметр разницы в пунктах, связанный с сигналом LSMA.
positions are opened at price modulo GridSize and offset with this parameter. (gridOffset) Смещение сетки — Смещение уровней сетки в пунктах, позволяющее выставлять ордера не на круглых значениях цены.
if set to true, will close all unfilled Orders (suspendGrid) Приостановить сетку — При значении true закрывает все неисполненные отложенные ордера сетки.
if set to true, will close all orders and positions. (shutdownGrid) Отключить сетку — При значении true закрывает все ордера и позиции по данному магическому номеру.
Получить полный код

Поиск по коду файла

extern int    uniqueGridMagic = 11111; // Magic number of the trades. must be unique to identify

extern double Lots = 0.1;              // 
extern double GridSize = 10;            // pips between orders - grid or mesh size
extern double GridSteps = 10;          // total number of orders to place
extern bool ExtendGrid = true;        // Used to limit grid to original when buy and sell stops are filled
extern double TakeProfit = 0 ;        // number of ticks to take profit. normally is = grid size but u can override
extern double StopLoss = 0;            // if u want to add a stop loss. normal grids dont use stop losses
extern int    trailStop = 0;           // will trail if > 0
extern int TrailingStopType = 1;       // Type 1 will trail immediately, type 2 will wait for price to move amount of trailStop
extern double UpdateInterval = 15;      // update orders every x minutes

extern int LSMAShortPeriod=7;          // 
extern int LSMALongPeriod=16;
extern int PipsDifference = 16;
extern int    gridOffset = 0;          // positions are opened at price modulo GridSize and offset with this parameter.

extern bool   suspendGrid = false;       // if set to true, will close all unfilled Orders 
extern bool   shutdownGrid = false;      // if set to true, will close all orders and positions.

string   GridName = "Grid";              // identifies the grid. allows for several co-existing grids - old variable.. shold not use any more
double   LastUpdate = 0;                 // counter used to note time of last update
double   startTime = 0;                  // counter to note trade start time.
double   closedProfit = 0;               // counts closed p&l
double   openProfit = 0;                 // counts open p&l
double   accumulatedProfit = 0;          // for back testing only
int      openLongs = 0;                  //  how many longs are open 
int      openShorts = 0;                 // how many shorts are open 
bool     gridActive = true;              // is the grid active

double LongTradeRate;                    // Keeps track of where to extend a long grid
double ShortTradeRate;                   // Keeps track of where to extend a short grid
int GridCount;                           // How many Buy Stop or Sell Stop are in the grid

int init()
  {
      // код доступен только после оплаты
   }

double LSMADaily(int Rperiod, int shift)
{
   int i;
   double sum;
   int length;
   double lengthvar;
   double tmp;
   double wt;

   length = Rperiod;

   sum = 0;
   for(i = length; i >= 1  ; i--)
   {
     lengthvar = length + 1;
     lengthvar /= 3;
     tmp = 0;
     tmp = ( i - lengthvar)*iClose(NULL,PERIOD_D1,length-i+shift);
     sum+=tmp;
    }
    wt = sum*6/(length*(length+1));

    return(wt);
}

double LSMA(int Rperiod, int shift)
{
   int i;
   double sum;
   int length;
   double lengthvar;
   double tmp;
   double wt;

   length = Rperiod;

   sum = 0;
   for(i = length; i >= 1  ; i--)
   {
     lengthvar = length + 1;
     lengthvar /= 3;
     tmp = 0;
     tmp = ( i - lengthvar)*Close[length-i+shift];
     sum+=tmp;
    }
    wt = sum*6/(length*(length+1));

    return(wt);
}

int CheckDailyDirection()
{
   double SlowEMA, FastEMA;
   double Dif;

   Dif = LSMADaily(LSMAShortPeriod,1) - LSMADaily(LSMALongPeriod,1);

   if(Dif > 0 ) return(1);
   if(Dif < 0 ) return(-1);
   return(0);

}

bool CheckExitCondition(string TradeType)
{
   bool YesClose;
   double Dif;

   YesClose = false;
   Dif=LSMA(LSMAShortPeriod,1)-LSMA(LSMALongPeriod,1);

   if (TradeType == "BUY" && Dif < 0) YesClose = true;
   if (TradeType == "SELL" && Dif > 0) YesClose = true;

   return (YesClose);
}

bool CheckEntryCondition(string TradeType)
{
   bool YesTrade;
   double Dif;

   YesTrade = false;

   Dif = LSMA(LSMAShortPeriod,1) - LSMA(LSMALongPeriod,1);

   if (TradeType == "BUY" && Dif > 0 ) YesTrade = true;
   if (TradeType == "SELL" && Dif < 0 ) YesTrade = true;

   return (YesTrade);
}

void ClosePendingOrdersAndPositions(bool CloseOpenPos,string type)
{
  int totalorders = OrdersTotal();
  for(int i=totalorders-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
    bool result = false;

    if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == uniqueGridMagic) || (OrderComment() == GridName)) )  // only look if mygrid and symbol...
     {
        if (CloseOpenPos) {
        if (type == "BUY") {

           if ( OrderType() == OP_BUY )  result = OrderClose( OrderTicket(), OrderLots(),  Bid, 5, Red );
          } 
         if (type == "SELL") {

           if ( OrderType() == OP_SELL )  result = OrderClose( OrderTicket(), OrderLots(),  Ask, 5, Red );
           }
        }

        if (type == "BUY" && OrderType() == OP_BUYSTOP ) result = OrderDelete( OrderTicket() );
        if (type == "SELL" && OrderType() == OP_SELLSTOP ) result = OrderDelete( OrderTicket() );
      }
  }
  return;
}

int openPositions(  )
  {  int op =0;
     int totalorders = OrdersTotal();
     for(int i=totalorders-1;i>=0;i--)                                // scan all orders and positions...
      {
        OrderSelect(i, SELECT_BY_POS);
        if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == uniqueGridMagic) || (OrderComment() == GridName)) )  // only look if mygrid and symbol...
         {  
          int type = OrderType();
          if ( type == OP_BUY ) {op=op+1;} 
          if ( type == OP_SELL ) {op=op+1;} 
         }
      } 
   return(op);
  }

int openGrids(  )
  {  int op =0;
     int totalorders = OrdersTotal();
     for(int i=totalorders-1;i>=0;i--)                                // scan all orders and positions...
      {
        OrderSelect(i, SELECT_BY_POS);
        if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == uniqueGridMagic) || (OrderComment() == GridName)) )  // only look if mygrid and symbol...
         {  
          int type = OrderType();
          if ( type == OP_BUYSTOP ) {op=op+1;} 
          if ( type == OP_SELLSTOP ) {op=op+1;} 
         }
      } 
   return(op);
  }

void TestForProfit( int forMagic, bool testOpen, bool testHistory )                   // based on trailing stop code from MT site... but modified as per Hiro
  {
         closedProfit = 0;                // counts closed p&l

         if (testHistory == true) {
            int total = HistoryTotal();
            for(int i=0;i<total;i++)                                // scan all closed / cancelled transactions
              {
              OrderSelect(i, SELECT_BY_POS, MODE_HISTORY );
              if ( OrderSymbol() == Symbol() && OrderMagicNumber() == forMagic )  // only look if mygrid and symbol...
                {
                 closedProfit = closedProfit + OrderProfit();
               }
              }
          } else {
             accumulatedProfit =0;
          }

         openProfit = 0;                  // counts open p&l

         if (testOpen == true) {
            total = OrdersTotal();
            openLongs = 0;
            openShorts = 0;
            for(i=0;i<total;i++)                                // scan all open orders and positions
              {
              OrderSelect(i, SELECT_BY_POS );
              if ( OrderSymbol() == Symbol() && OrderMagicNumber() == forMagic )  // only look if mygrid and symbol...
                {
                  openProfit = openProfit + OrderProfit();
                  int type = OrderType();
                  if ( type == OP_BUY ) {openLongs=openLongs+1;} 
                  if ( type == OP_SELL ) {openShorts=openShorts+1;} 
                }
              }
           }
           accumulatedProfi

Показано первые 50% кода (символов: 10249)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
1 024,90₽ ≈ $12.53