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

MakeGrid193

makegrid193be long.mq4

Похожие материалы по тегам

! macd+.mq5MQL5 / MetaTrader 5 · 1 общих тегов!!!macd_adx.mq4MQL4 / MetaTrader 4 · 1 общих теговxauusd_gold_perfect.mq4MQL4 / MetaTrader 4 · 1 общих теговtm sniper pro.pineTradingView · 1 общих теговsource code of grid with 100 pips stop loss.mq4MQL4 / MetaTrader 4 · 1 общих теговsniper pro.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

MakeGrid193 — это торговый советник для MetaTrader 4, написанный на языке MQL4. Программа реализует сеточную (grid) торговую логику, размещая серию ордеров на заданном расстоянии друг от друга по ценовому графику и управляя открытием и закрытием позиций в рамках заданных параметров.

Советник поддерживает как длинные, так и короткие позиции с возможностью фильтрации по техническим индикаторам EMA, MACD и OsMA. Встроены функции управления рисками: стоп-лосс, трейлинг-стоп, перевод стоп-лосса в безубыток, а также ограничение максимального количества одновременно открытых позиций.

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

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

НастройкаОписание
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) Количество шагов сетки — Общее количество ордеров, размещаемых в сетке.
number of ticks to take profit. normally is = grid size but u can override (TakeProfit) Тейк-профит (пункты) — Значение тейк-профита в пунктах. Если не задано, устанавливается равным размеру сетки.
if u want to add a stop loss. normal grids dont use stop losses (StopLoss) Стоп-лосс (пункты) — Значение стоп-лосса в пунктах. Если равно 0, стоп-лосс не устанавливается.
will trail if > 0 (trailStop) Трейлинг-стоп (пункты) — Активирует трейлинг-стоп. Значение задаётся в пунктах; если 0 — трейлинг не используется.
will move the stoploss to BE after x pips of movement (BEPips) Безубыток (пункты) — Переводит стоп-лосс в безубыток после указанного количества пунктов движения цены.
update orders every x minutes (UpdateInterval) Интервал обновления (минуты) — Интервал обновления ордеров в минутах. Советник пересчитывает сетку с заданной периодичностью.
do we want long positions (wantLongs) Длинные позиции — Разрешает открытие длинных позиций.
do we want short positions (wantShorts) Короткие позиции — Разрешает открытие коротких позиций.
do we want longs above price, shorts below price (wantBreakout) Разрешить breakout — При активации разрешает размещение длинных ордеров выше цены и коротких — ниже цены.
do we want longs below price, shorts above price (wantCounter) Разрешить counter — При активации разрешает размещение длинных ордеров ниже цены и коротких — выше цены.
do we want longs above ema only, shorts below ema only (limitEMA) Фильтр по EMA — При активации разрешает открытие длинных позиций только выше EMA и коротких — только ниже EMA.
the length of the EMA.. was previously fixed at 34 (EMAperiod) Период EMA — Период скользящей средней EMA, используемой для фильтрации направления позиций.
maximum number of open positions : implemented in v1.92 (GridMaxOpen) Макс. открытых позиций — Максимальное количество одновременно открытых позиций. При достижении лимита новые ордера не размещаются.
if true, will use macd >0 for longs only, macd <0 for shorts only (UseMACD) Использовать MACD — При активации использует индикатор MACD для фильтрации направления позиций: лонг при значении выше нуля, шорт — ниже нуля.
if true, will use OSMA > 0 for longs only, OSMA <0 for shorts only. used in same way as MACD. (UseOsMA) Использовать OsMA — При активации использует индикатор OsMA аналогично MACD для фильтрации направления позиций. Если одновременно активны MACD и OsMA, приоритет у OsMA.
if UseMACD, do we also close open positions with a loss? (CloseOpenPositions) Закрытие позиций при сигнале индикатора — При активации фильтра MACD/OsMA определяет, нужно ли также закрывать открытые позиции с убытком.
this will remove long orders below the 34 ema and vv if limitEMA flag is true (doHouseKeeping) Автоочистка ордеров у EMA — Удаляет ордера, расположенные на неправильной стороне от EMA, если фильтр limitEMA активен.
in hours - if > 0, all open orders or positions will be closed after this period. fractions are perm (keepOpenTimeLimit) Время удержания позиций (часы) — Время в часах, по истечении которого все открытые ордера и позиции закрываются. Допускаются дробные значения.
parameters for MACD and OSMA (emaFast) Быстрая EMA (MACD/OsMA) — Быстрая скользящая средняя для индикатора MACD/OsMA.
parameters for MACD and OSMA (emaSlow) Медленная EMA (MACD/OsMA) — Медленная скользящая средняя для индикатора MACD/OsMA.
parameters for MACD and OSMA (signalPeriod) Период сигнальной линии — Период сигнальной линии для индикатора MACD/OsMA.
parameters for MACD and OSMA (timeFrame) Таймфрейм индикатора — Таймфрейм для расчёта индикаторов MACD и OsMA.
minimum distance from price to place trades. (minFromPrice) Мин. расстояние от цены (пункты) — Минимальное расстояние от текущей цены для размещения ордеров.
will trade for this number of minutes after being initialised. (tradeForMinutes) Время торговли (минуты) — Количество минут торговли после инициализации советника. По истечении времени все позиции закрываются.
positions are opened at price modulo GridSize and offset with this parameter. (gridOffset) Смещение сетки — Смещение для размещения ордеров, позволяющее входить по неокруглённым ценам.
defines the center point of a fixed width long grid (longGridCenter) Центр сетки лонг — Центральная точка фиксированной по ширине сетки длинных позиций.
defines the center point of a fixed width short grid (shortGridCenter) Центр сетки шорт — Центральная точка фиксированной по ширине сетки коротких позиций.
defines the bottom of a fixed width long grid (longGridLow) Нижняя граница сетки лонг — Нижняя граница фиксированной по ширине сетки длинных позиций.
defines the top of a fixed width long grid (longGridHigh) Верхняя граница сетки лонг — Верхняя граница фиксированной по ширине сетки длинных позиций.
defines the bottom of a fixed width short grid (shortGridLow) Нижняя граница сетки шорт — Нижняя граница фиксированной по ширине сетки коротких позиций.
defines the top of a fixed width short grid (shortGridHigh) Верхняя граница сетки шорт — Верхняя граница фиксированной по ширине сетки коротких позиций.
if > 0, will close out all positions once the $ target has been met (profitTarget) Целевая прибыль (USD) — Целевая прибыль в долларах. При достижении все позиции и ордера закрываются.
if set to true, will close all unfilled Orders (suspendGrid) Приостановка сетки — При активации закрывает все необработанные ордера.
if set to true, will close all orders and positions. (shutdownGrid) Полная остановка сетки — При активации закрывает все ордера и позиции и останавливает работу советника.
Получить полный код

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

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

extern double Lots = 0.1;              // 
extern double GridSize = 6;            // pips between orders - grid or mesh size
extern double GridSteps = 10;          // total number of orders to place
extern double TakeProfit = 10 ;        // 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    BEPips = 0;              // will move the stoploss to BE after x pips of movement
extern double UpdateInterval = 1;      // update orders every x minutes
extern bool   wantLongs = true;        // do we want long positions
extern bool   wantShorts = false;       // do we want short positions
extern bool   wantBreakout = true;     // do we want longs above price, shorts below price
extern bool   wantCounter = true;      // do we want longs below price, shorts above price
extern bool   limitEMA = true;         // do we want longs above ema only, shorts below ema only
extern int    EMAperiod = 34;          // the length of the EMA.. was previously fixed at 34
extern double GridMaxOpen = 0;         // maximum number of open positions : implemented in v1.92
extern bool   UseMACD = true;          // if true, will use macd >0 for longs only, macd <0 for shorts only

extern bool   UseOsMA = false;         // if true, will use OSMA > 0 for longs only, OSMA <0 for shorts only. used in same way as MACD. 

extern bool CloseOpenPositions = false;// if UseMACD, do we also close open positions with a loss?
extern bool   doHouseKeeping = true;   // this will remove long orders below the 34 ema and vv if limitEMA flag is true
extern double keepOpenTimeLimit = 0;   // in hours - if > 0, all open orders or positions will be closed after this period. fractions are permitted
extern int    emaFast = 12;            // parameters for MACD and OSMA
extern int    emaSlow = 26;            // parameters for MACD and OSMA
extern int    signalPeriod = 9;        // parameters for MACD and OSMA
extern int    timeFrame = 0;           // parameters for MACD and OSMA
extern int    minFromPrice = 0;        // minimum distance from price to place trades.
extern int    tradeForMinutes=0;       // will trade for this number of minutes after being initialised. 

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

extern double longGridCenter = 0;      // defines the center point of a fixed width long grid                                       
extern double shortGridCenter = 0;     // defines the center point of a fixed width short grid                                       

extern double longGridLow = 0;         // defines the bottom of a fixed width long grid
extern double longGridHigh = 0;        // defines the top of a fixed width long grid

extern double shortGridLow = 0;         // defines the bottom of a fixed width short grid
extern double shortGridHigh = 0;        // defines the top of a fixed width short grid

extern double profitTarget = 15000;     // if > 0, will close out all positions once the $ target has been met

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
bool     haveHitTarget = false;          //  if there is a target, this flag says we have hit it
int      openLongs = 0;                  //  how many longs are open 
int      openShorts = 0;                 // how many shorts are open 
bool     gridActive = true;              // is the grid active
bool     gridOneShot = false;       // is this a one shot? if so, it stops after the profitTarget has been reached

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

bool IsPosition(double atRate, double inRange, bool checkLongs )
  {
     int totalorders = OrdersTotal();
     for(int i=0;i<totalorders;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 (MathAbs( OrderOpenPrice() - atRate ) < (inRange*0.9)) // dont look for exact price but price proximity (less than gridsize) - added 0.9 because of floating point errors
              { if ( ( checkLongs && ( type == OP_BUY || type == OP_BUYLIMIT  || type == OP_BUYSTOP ) )  || (!checkLongs && ( type == OP_SELL || type == OP_SELLLIMIT  || type == OP_SELLSTOP ) ) )
                 { 
                    return(true); 
                 }
              }
         }
      } 
   return(false);
  }

void DeleteAfter( double xHours )    // delete pending orders or open positions after x hours
  {
  int totalorders = OrdersTotal();
  for(int i=totalorders-1;i>=0;i--)
     OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

     if ( OrderSymbol()==Symbol() && ( (OrderMagicNumber() == uniqueGridMagic) || (OrderComment() == GridName)) )  // only look if mygrid and symbol...
        {
            if (( MathAbs(iTime(Symbol(),5,0)-OrderOpenTime()) >= xHours*60*60 ) && (iTime(Symbol(),5,0)>0))
            {  bool result = false;

               if ( OrderType() == OP_BUY )  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );

               if ( OrderType() == OP_SELL )  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );

               if ( OrderType() > 1 ) result = OrderDelete( OrderTicket() );
           }
        }

  } // proc DeleteAfter()

void CloseAllPendingOrders( )
  {
     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...
         {  
          if ( OrderType() > 1 ) bool result = OrderDelete( OrderTicket() );
         }
      } 
   return;
  }

void ClosePendingOrdersAndPositions()
{
  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 ( OrderType() == OP_BUY )  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );

           if ( OrderType() == OP_SELL )  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );

           if ( OrderType() > 1 ) result = OrderDelete( OrderTicket() );
      }
  }
  return;
}

void CloseOrdersfromEMA( double theEMAValue )
  {
     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();
          bool result = false;

          if ( type == OP_BUYLIMIT && OrderOpenPrice() <= theEMAValue ) result = OrderDelete( OrderTicket() ); 
          if ( type == OP_BUYSTOP && OrderOpenPrice() <= theEMAValue ) result = OrderDelete( OrderTicket() ); 
          if ( type == OP_SELLLIMIT && OrderOpenPrice() >= theEMAValue ) result = OrderDelete( OrderTicket() ); 
          if ( type == OP_SELLSTOP && OrderOpenPrice() >= theEMAValue ) 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);
  }

void TestForProfit( int forMagic, double profittarget, bool testOpen, bool testHistory )                   // based on trailing stop code from MT site... but modified as per Hiro
  {
    if (profittarget > 0 )
     {
         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 )  

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

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

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

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

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

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

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