Разбор кода на MQL.

Программирование прибыли: от азов к секретам мастерства. Читайте, спрашивайте, делитесь опытом.
Бонус за сообщение 0.5$
Ответственный Модератор - Haos

Re: Разбор кода на MQL.

Сообщение mfcoder » 30 авг 2013, 04:22

Код: выделить все
 if (k<0) continue;

Дело в том что цикл определен так что может быть выход за границы буфера, и индикатор завершиться по ошибке. Этот код проверяет выходит ли индекс за границы, и если выходит, то начинается новая итерация цикла.[/quote]


по смыслу сместо continue больше подходит break, разве нет :) ?
Аватар пользователя
mfcoder
 
Сообщений: 1531
Зарегистрирован: 29 июл 2013, 11:55
Средств на руках: 26.85 Доллар
Группа: Базовая
Благодарил (а): 78 раз.
Поблагодарили: 423 раз.

Re: Разбор кода на MQL.

Сообщение Рэндом » 30 авг 2013, 04:25

Нет. При break произойдет выход из цикла, а нам нужно начать считать при k==0.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение mfcoder » 30 авг 2013, 17:58

Рэндом писал(а):Нет. При break произойдет выход из цикла, а нам нужно начать считать при k==0.


а, ну да, тут справа налево перебор идет :(
Аватар пользователя
mfcoder
 
Сообщений: 1531
Зарегистрирован: 29 июл 2013, 11:55
Средств на руках: 26.85 Доллар
Группа: Базовая
Благодарил (а): 78 раз.
Поблагодарили: 423 раз.

Re: Разбор кода на MQL.

Сообщение Рэндом » 02 сен 2013, 04:02

Индикатор Lot MT5. Тема индикатора viewtopic.php?f=9&t=48
Код: выделить все
//+------------------------------------------------------------------+
//|                                                          Lot.mq5 |
//|                                                           Рэндом |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      ""
#property version   "1.00"
#property indicator_chart_window
//--- input parameters
input double   Frac=1000.0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   Comment("Lot=",FLot(Frac));
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   Comment("Lot=",FLot(Frac));
  }
//+------------------------------------------------------------------+

double FLot(double Fract)
{
   double minl=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   double maxl=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   double lot=MathFloor(AccountInfoDouble(ACCOUNT_BALANCE)/Fract)*minl;
   if(lot>maxl) lot=maxl;
   if(lot<minl) lot=minl;
   return lot;
}

Здесь есть один интересный момент.
Код: выделить все
double lot=MathFloor(AccountInfoDouble(ACCOUNT_BALANCE)/Fract)*minl;

Использование функции MathFloor. Эта функция отбрасывает дробную часть числа. Без этой функции мы бы могли получить не коректный размер лота. Например лот 0.011, когда шаг лота 0.01.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение Рэндом » 03 сен 2013, 06:04

Индикатор FoxPivot. Тема с индикатором viewtopic.php?f=9&t=42
Код: выделить все
 //+------------------------------------------------------------------+
//|                                                     FoxPivot.mq5 |
//|                                                           Рэндом |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 9
#property indicator_plots   7
//--- plot Map1
#property indicator_label1  "Map1"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrYellow
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- plot Map2
#property indicator_label2  "Map2"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrMidnightBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1
//--- plot Map3
#property indicator_label3  "Map3"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrMidnightBlue
#property indicator_style3  STYLE_SOLID
#property indicator_width3  1
//--- plot Map4
#property indicator_label4  "Map4"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrMidnightBlue
#property indicator_style4  STYLE_SOLID
#property indicator_width4  1
//--- plot Map5
#property indicator_label5  "Map5"
#property indicator_type5   DRAW_LINE
#property indicator_color5  clrRed
#property indicator_style5  STYLE_SOLID
#property indicator_width5  1
//--- plot Map6
#property indicator_label6  "Map6"
#property indicator_type6   DRAW_LINE
#property indicator_color6  clrRed
#property indicator_style6  STYLE_SOLID
#property indicator_width6  1
//--- plot Map7
#property indicator_label7  "Map7"
#property indicator_type7   DRAW_LINE
#property indicator_color7  clrRed
#property indicator_style7  STYLE_SOLID
#property indicator_width7  1
//--- input parameters
input int      Leght=13;
input int      Shift=13;
//--- indicator buffers
double         Map1Buffer[];
double         Map2Buffer[];
double         Map3Buffer[];
double         Map4Buffer[];
double         Map5Buffer[];
double         Map6Buffer[];
double         Map7Buffer[];
double         HBuf[];
double         LBuf[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,Map1Buffer,INDICATOR_DATA);
   SetIndexBuffer(1,Map2Buffer,INDICATOR_DATA);
   SetIndexBuffer(2,Map3Buffer,INDICATOR_DATA);
   SetIndexBuffer(3,Map4Buffer,INDICATOR_DATA);
   SetIndexBuffer(4,Map5Buffer,INDICATOR_DATA);
   SetIndexBuffer(5,Map6Buffer,INDICATOR_DATA);
   SetIndexBuffer(6,Map7Buffer,INDICATOR_DATA);
   SetIndexBuffer(7,HBuf,INDICATOR_CALCULATIONS);
   SetIndexBuffer(8,LBuf,INDICATOR_CALCULATIONS);

   PlotIndexSetInteger(0,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(1,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(2,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(3,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(4,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(5,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(6,PLOT_SHIFT,Shift);
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
   int limit;
   if(prev_calculated==0)
      limit=0;
   else limit=prev_calculated-1;
   for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      HBuf[i]=high[i];
      LBuf[i]=low[i];
   }
   for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      if(i<Leght-1) continue;
      double Max=Highest(i,HBuf);
      double Min=Lowest(i,LBuf);
     
      Map1Buffer[i]=(Max+Min)/2;
      Map2Buffer[i]=2*Map1Buffer[i]-Min;
      Map3Buffer[i]=Map1Buffer[i]+(Max-Min);
      Map4Buffer[i]=2*Map1Buffer[i]+(Max-Min*2);
      Map5Buffer[i]=2*Map1Buffer[i]-Max;
      Map6Buffer[i]=Map1Buffer[i]-(Max-Min);
      Map7Buffer[i]=2*Map1Buffer[i]-(Max*2-Min);
   }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   
  }
//+------------------------------------------------------------------+
double Highest(int index, const double &high[])
{
   double max=0;
   for(int i=index;i>index-Leght;i--)
   {
     
      if(high[i]>max) max=high[i];
   }
   return max;
}

double Lowest(int index, const double &low[])
{
   double min=1.7976931348623158e+308;
   for(int i=index;i>index-Leght;i--)
      if(low[i]<min) min=low[i];
   return min;
}

Вот вам пример не эффективного кода. Я не представляю почему я сделал так.
Код: выделить все
 for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      HBuf[i]=high[i];
      LBuf[i]=low[i];
   }
   for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      if(i<Leght-1) continue;
      double Max=Highest(i,HBuf);
      double Min=Lowest(i,LBuf);
     
      Map1Buffer[i]=(Max+Min)/2;
      Map2Buffer[i]=2*Map1Buffer[i]-Min;
      Map3Buffer[i]=Map1Buffer[i]+(Max-Min);
      Map4Buffer[i]=2*Map1Buffer[i]+(Max-Min*2);
      Map5Buffer[i]=2*Map1Buffer[i]-Max;
      Map6Buffer[i]=Map1Buffer[i]-(Max-Min);
      Map7Buffer[i]=2*Map1Buffer[i]-(Max*2-Min);
   }

Первый цикл здесь абсолютно не нужен.
Код: выделить все
 double Max=Highest(i,HBuf);
      double Min=Lowest(i,LBuf);

Здесь можно напрямую передать буферы high и low.
Исправленный вариант. Он будет работать несколько быстрее. Хотя и первый вариант работает весьма сносно.
Код: выделить все
//+------------------------------------------------------------------+
//|                                                     FoxPivot.mq5 |
//|                                                           Рэндом |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 7
#property indicator_plots   7
//--- plot Map1
#property indicator_label1  "Map1"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrYellow
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- plot Map2
#property indicator_label2  "Map2"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrMidnightBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1
//--- plot Map3
#property indicator_label3  "Map3"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrMidnightBlue
#property indicator_style3  STYLE_SOLID
#property indicator_width3  1
//--- plot Map4
#property indicator_label4  "Map4"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrMidnightBlue
#property indicator_style4  STYLE_SOLID
#property indicator_width4  1
//--- plot Map5
#property indicator_label5  "Map5"
#property indicator_type5   DRAW_LINE
#property indicator_color5  clrRed
#property indicator_style5  STYLE_SOLID
#property indicator_width5  1
//--- plot Map6
#property indicator_label6  "Map6"
#property indicator_type6   DRAW_LINE
#property indicator_color6  clrRed
#property indicator_style6  STYLE_SOLID
#property indicator_width6  1
//--- plot Map7
#property indicator_label7  "Map7"
#property indicator_type7   DRAW_LINE
#property indicator_color7  clrRed
#property indicator_style7  STYLE_SOLID
#property indicator_width7  1
//--- input parameters
input int      Leght=13;
input int      Shift=13;
//--- indicator buffers
double         Map1Buffer[];
double         Map2Buffer[];
double         Map3Buffer[];
double         Map4Buffer[];
double         Map5Buffer[];
double         Map6Buffer[];
double         Map7Buffer[];


//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,Map1Buffer,INDICATOR_DATA);
   SetIndexBuffer(1,Map2Buffer,INDICATOR_DATA);
   SetIndexBuffer(2,Map3Buffer,INDICATOR_DATA);
   SetIndexBuffer(3,Map4Buffer,INDICATOR_DATA);
   SetIndexBuffer(4,Map5Buffer,INDICATOR_DATA);
   SetIndexBuffer(5,Map6Buffer,INDICATOR_DATA);
   SetIndexBuffer(6,Map7Buffer,INDICATOR_DATA);
   

   PlotIndexSetInteger(0,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(1,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(2,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(3,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(4,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(5,PLOT_SHIFT,Shift);
   PlotIndexSetInteger(6,PLOT_SHIFT,Shift);
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
   int limit;
   if(prev_calculated==0)
      limit=0;
   else limit=prev_calculated-1;
   
   for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      if(i<Leght-1) continue;
      double Max=Highest(i,high);
      double Min=Lowest(i,low);
     
      Map1Buffer[i]=(Max+Min)/2;
      Map2Buffer[i]=2*Map1Buffer[i]-Min;
      Map3Buffer[i]=Map1Buffer[i]+(Max-Min);
      Map4Buffer[i]=2*Map1Buffer[i]+(Max-Min*2);
      Map5Buffer[i]=2*Map1Buffer[i]-Max;
      Map6Buffer[i]=Map1Buffer[i]-(Max-Min);
      Map7Buffer[i]=2*Map1Buffer[i]-(Max*2-Min);
   }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   
  }
//+------------------------------------------------------------------+
double Highest(int index, const double &high[])
{
   double max=0;
   for(int i=index;i>index-Leght;i--)
   {
     
      if(high[i]>max) max=high[i];
   }
   return max;
}

double Lowest(int index, const double &low[])
{
   double min=1.7976931348623158e+308;
   for(int i=index;i>index-Leght;i--)
      if(low[i]<min) min=low[i];
   return min;
}
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение mfcoder » 03 сен 2013, 17:41

сурово так
Код: выделить все
double min=1.7976931348623158e+308;

в рамках цен достаточно было разделить любую цену на поинт :)
Аватар пользователя
mfcoder
 
Сообщений: 1531
Зарегистрирован: 29 июл 2013, 11:55
Средств на руках: 26.85 Доллар
Группа: Базовая
Благодарил (а): 78 раз.
Поблагодарили: 423 раз.

Re: Разбор кода на MQL.

Сообщение Рэндом » 04 сен 2013, 03:10

Можно было использовать DBL_MAX константу.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение Рэндом » 09 сен 2013, 04:18

Советник Shadow. Тема с советником viewtopic.php?f=10&t=175
Код: выделить все
//+------------------------------------------------------------------+
//|                                                       Shadow.mq4 |
//|                                                           Рэндом |
//|                                         http://mt4.maxiforex.ru/ |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      "http://mt4.maxiforex.ru/"

//--- input parameters
extern double    ShadowP=20.0;
extern int       StopLoss=10;
extern int       MinStop=10;
extern int       TakeProfit=80;
extern double    Lot=0.1;
extern int       Slipage=3;
extern int       Magic=777;
datetime dd;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   dd=Time[0];
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   if(dd==Time[0]) return(0);
   dd=Time[0];
   int pos=0;
   for(int i=0;i<OrdersTotal();i++)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderMagicNumber()==Magic) pos++;
   }
   if(pos==0)
   {
      if(Long() && !Short())
      {
         double tp=0;
         if(TakeProfit==0)
            tp=0;
         else
            tp=Ask+TakeProfit*Point;
        double sl=Low[1]-StopLoss*Point;
        if((Bid-sl)/Point<MinStop)
         sl=Bid-MinStop*Point;
        OrderSend(Symbol(),OP_BUY,Lot,Ask,Slipage,sl,tp,NULL,Magic);       
      }
      if(Short() && !Long())
      {
         tp=0;
         if(TakeProfit==0)
            tp=0;
         else
            tp=Bid-TakeProfit*Point;
         sl=High[1]+StopLoss*Point;
         if((sl-Ask)/Point<MinStop)
            sl=Ask-MinStop*Point;
         OrderSend(Symbol(),OP_SELL,Lot,Bid,Slipage,sl,tp,NULL,Magic);
      }
   }
   if(pos==1)
   {
      for(i=0;i<OrdersTotal();i++)
      {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderMagicNumber()==Magic) break;
      }
      if(OrderType()==OP_BUY && Short())
      {
         OrderClose(OrderTicket(),OrderLots(),Bid,Slipage);
         if(!Long())
         {
            tp=0;
            if(TakeProfit==0)
               tp=0;
            else
               tp=Bid-TakeProfit*Point;
            sl=High[1]+StopLoss*Point;
            if((sl-Ask)/Point<MinStop)
               sl=Ask+MinStop*Point;
            OrderSend(Symbol(),OP_SELL,Lot,Bid,Slipage,sl,tp,NULL,Magic);
         }
      }
      if(OrderType()==OP_SELL && Long())
      {
         OrderClose(OrderTicket(),OrderLots(),Ask,Slipage);
         if(!Short())
         {
            tp=0;
            if(TakeProfit==0)
               tp=0;
            else
               tp=Ask+TakeProfit*Point;
            sl=Low[1]-StopLoss*Point;
            if((Bid-sl)/Point<MinStop)
               sl=Bid-MinStop*Point;
            OrderSend(Symbol(),OP_BUY,Lot,Ask,Slipage,sl,tp,NULL,Magic);
         }
      }
     
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+
bool Long()
{
   double pr=0.0;
   double t=0.0;
   double s=0.0;
   if(Open[1]<Close[1])
   {
      pr=Open[1];
     
     
   }
   else
   {
      pr=Close[1];
     
     
   }
   t=(High[1]-Low[1])/Point;
   s=(pr-Low[1])/Point;
   if(s/(t/100)>ShadowP) return(true);
   return(false);
}

bool Short()
{
   double pr=0.0;
   double t=0.0;
   double s=0.0;
   if(Open[1]<Close[1])
   {
      pr=Close[1];
     
     
   }
   else
   {
      pr=Open[1];
     
   }
   t=(High[1]-Low[1])/Point;
   s=(High[1]-pr)/Point;
   if(s/(t/100)>ShadowP) return(true);
   return(false);
}

Здесь интересный момент вот это
Код: выделить все
        double sl=Low[1]-StopLoss*Point;
        if((Bid-sl)/Point<MinStop)
         sl=Bid-MinStop*Point;
        OrderSend(Symbol(),OP_BUY,Lot,Ask,Slipage,sl,tp,NULL,Magic);

Суть в том, что если стоп считается отличным методом от расстояния от текущей цены, необходимо вводить проверку на минимально допустимый стоп.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение Рэндом » 13 сен 2013, 03:56

Индикатор PriceLine (МТ5). Тема viewtopic.php?f=9&t=183
Код:
Код: выделить все
//+------------------------------------------------------------------+
//|                                                    PriseLine.mq5 |
//|                                                           Рэндом |
//|                                         http://mt4.maxiforex.ru/ |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      "http://mt4.maxiforex.ru/"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
//--- plot Main
#property indicator_label1  "Main"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- indicator buffers
enum PRICE_LINE
{
   Close,
   Median,
   Weighted
};

input PRICE_LINE  Type=Close;

double         MainBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,MainBuffer,INDICATOR_DATA);
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   int limit;
   if(prev_calculated==0)
      limit=0;
   else limit=prev_calculated-1;
//--- calculate MACD
   for(int i=limit;i<rates_total && !IsStopped();i++)
   {
      switch(Type)
      {
         case Close: MainBuffer[i]=close[i];
                     break;
         case Median: MainBuffer[i]=(high[i]+low[i])/2;
                      break;
         case Weighted: MainBuffer[i]=(high[i]+low[i]+close[i])/3;
      }
   }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

Здесь интересно использование enum. Обратите внимания что переменная input (доступная при установки индикатора на график) объявлена как созданный нами enum. Это дает нам то, что при установке типа графика в терминале пользователь может выбрать его тип по именам переменных enum из выпадающего списка.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.

Re: Разбор кода на MQL.

Сообщение Рэндом » 26 сен 2013, 04:54

Советник PirMA МТ4. Тема viewtopic.php?f=10&p=1335#p1335
Код:
Код: выделить все
//+------------------------------------------------------------------+
//|                                                        PirMA.mq4 |
//|                                                           Рэндом |
//|                                         http://mt4.maxiforex.ru/ |
//+------------------------------------------------------------------+
#property copyright "Рэндом"
#property link      "http://mt4.maxiforex.ru/"

//--- input parameters
extern int       MAPeriod=34;
extern int       Npips=20;
extern int       TP=20;
extern int       Slipage=3;
extern double    Lot=0.1;
extern int       KPos=5;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int p;
int init()
  {
//----
  p=0;
  if(GlobalVariableCheck("PirMA_P"))
   p=GlobalVariableGet("PirMA_P");
  else
   GlobalVariableSet("PirMA_P",p);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   GlobalVariableSet("PirMA_P",p);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   if(Long())
   {
      p=1;
      CloseAll();
      OrderSend(Symbol(),OP_BUY,Lot*2,Ask,Slipage,0,0);
   }
   if(Short())
   {
      p=2;
      CloseAll();
      OrderSend(Symbol(),OP_SELL,Lot*2,Bid,Slipage,0,0);
   }
   if(OrdersTotal()>0 && OrdersTotal()<KPos)
   {
      OrderSelect(OrdersTotal()-1,MODE_TRADES);
     
      if(p==1)
      {
         if(Ask>OrderOpenPrice() && Ask-OrderOpenPrice()>=Npips*Point) OrderSend(Symbol(),OP_BUY,Lot*2,Ask,Slipage,0,0);
         if(Ask<OrderOpenPrice() && OrderOpenPrice()-Ask>=Npips*Point) OrderSend(Symbol(),OP_SELL,Lot,Bid,Slipage,0,Ask-TP*Point);
      }
      if(p==2)
      {
         if(Bid<OrderOpenPrice() && OrderOpenPrice()-Bid>=Npips*Point) OrderSend(Symbol(),OP_SELL,Lot*2,Bid,Slipage,0,0);
         if(Bid>OrderOpenPrice() && Bid-OrderOpenPrice()>=Npips*Point) OrderSend(Symbol(),OP_BUY,Lot,Ask,Slipage,0,Bid+TP*Point);
      }
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+
bool Long()
{
   double ma1=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   double ma2=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,2);
   double ma3=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,3);
   if(ma1<ma2 && ma1<ma3) return(true);
   return (false);
}

bool Short()
{
   double ma1=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   double ma2=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,2);
   double ma3=iMA(Symbol(),Period(),MAPeriod,0,MODE_EMA,PRICE_CLOSE,3);
   if(ma1>ma1 && ma1>ma3) return (true);
   return (false);
}

void CloseAll()
{
  if(OrdersTotal()==0) return;
  int limit =OrdersTotal()-1;
  for(int i=limit;i>=0;i--)
  {
      OrderSelect(i,MODE_TRADES);
      if(OrderType()==OP_BUY) OrderClose(OrderTicket(),OrderLots(),Bid,Slipage);
      if(OrderType()==OP_SELL) OrderClose(OrderTicket(),OrderLots(),Ask,Slipage);
  }
}

Здесь интересно использование переменной p. Она используется для запоминания текущего тренда, а затем в зависимости от текущего тренда открываются дополнительные позиции. Простой, но мощный прием. Обратите внимание на то что используются глобальные переменные терминала, т.к. если терминал будет закрыт мы можем потерять значение переменной p, а это не желательно.
Аватар пользователя
Рэндом
Специалист MQL
 
Сообщений: 13700
Зарегистрирован: 18 июл 2013, 08:05
Средств на руках: 31.45 Доллар
Группа: Администраторы
Благодарил (а): 1131 раз.
Поблагодарили: 3174 раз.
Каждый заблуждается в меру своих возможностей.


Вернуться в MQL – теория и практика

Кто сейчас на форуме?

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 83

Права доступа к форуму

Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

cron