Вопросы от начинающих MQL5 MT5 MetaTrader 5 - страница 1522

 
MrBrooklin #:

Привет, Алексей! Не знаю, но вроде бы всё чётко и понятно расписал в своем сообщении:

С уважением, Владимир.

Привет. НО штатному индикатору это никак не впишешь… Именно поэтому я уточнил проблему.

 
Alexey Viktorov #:

Привет. НО штатному индикатору это никак не впишешь… Именно поэтому я уточнил проблему.

Доброе утро, Алексей! Можешь пояснить почему нельзя вписать?

С уважением, Владимир.

 
MrBrooklin #:

Доброе утро, Алексей! Можешь пояснить почему нельзя вписать?

С уважением, Владимир.

Потому, что у штатного, точней сказать технического индикатора код недоступен. 

Документация по MQL5: Технические индикаторы
Документация по MQL5: Технические индикаторы
  • www.mql5.com
Все функции типа iMA, iAC, iMACD, iIchimoku и т.п., создают в глобальном кеше клиентского терминала копию соответствующего технического индикатора...
 
Alexey Viktorov #:

Потому, что у штатного, точней сказать технического индикатора код недоступен. 

Алексей, извини меня за тупизну и бестолковость, но тогда вот этот код, взятый мною из MetaEditor, что за код?

С уважением, Владимир.

//+------------------------------------------------------------------+
//|                                                    Alligator.mq5 |
//|                             Copyright 2000-2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"

//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_type2   DRAW_LINE
#property indicator_type3   DRAW_LINE
#property indicator_color1  Blue
#property indicator_color2  Red
#property indicator_color3  Lime
#property indicator_width1  1
#property indicator_width2  1
#property indicator_width3  1
#property indicator_label1  "Jaws"
#property indicator_label2  "Teeth"
#property indicator_label3  "Lips"
//--- input parameters
input int                InpJawsPeriod=13;               // Jaws period
input int                InpJawsShift=8;                 // Jaws shift
input int                InpTeethPeriod=8;               // Teeth period
input int                InpTeethShift=5;                // Teeth shift
input int                InpLipsPeriod=5;                // Lips period
input int                InpLipsShift=3;                 // Lips shift
input ENUM_MA_METHOD     InpMAMethod=MODE_SMMA;          // Moving average method
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_MEDIAN;   // Applied price
//--- indicator buffers
double ExtJaws[];
double ExtTeeth[];
double ExtLips[];
//--- handles for moving averages
int    ExtJawsHandle;
int    ExtTeethHandle;
int    ExtLipsHandle;
//--- bars minimum for calculation
int    ExtBarsMinimum;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtJaws,INDICATOR_DATA);
   SetIndexBuffer(1,ExtTeeth,INDICATOR_DATA);
   SetIndexBuffer(2,ExtLips,INDICATOR_DATA);
//--- set accuracy
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpJawsPeriod-1);
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpTeethPeriod-1);
   PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,InpLipsPeriod-1);
//--- line shifts when drawing
   PlotIndexSetInteger(0,PLOT_SHIFT,InpJawsShift);
   PlotIndexSetInteger(1,PLOT_SHIFT,InpTeethShift);
   PlotIndexSetInteger(2,PLOT_SHIFT,InpLipsShift);
//--- name for DataWindow
   PlotIndexSetString(0,PLOT_LABEL,"Jaws("+string(InpJawsPeriod)+")");
   PlotIndexSetString(1,PLOT_LABEL,"Teeth("+string(InpTeethPeriod)+")");
   PlotIndexSetString(2,PLOT_LABEL,"Lips("+string(InpLipsPeriod)+")");
//--- get MA's handles
   ExtJawsHandle=iMA(NULL,0,InpJawsPeriod,0,InpMAMethod,InpAppliedPrice);
   ExtTeethHandle=iMA(NULL,0,InpTeethPeriod,0,InpMAMethod,InpAppliedPrice);
   ExtLipsHandle=iMA(NULL,0,InpLipsPeriod,0,InpMAMethod,InpAppliedPrice);
//--- bars minimum for calculation
   ExtBarsMinimum=InpJawsPeriod+InpJawsShift;
   if(ExtBarsMinimum<(InpTeethPeriod+InpTeethShift))
      ExtBarsMinimum=InpTeethPeriod+InpTeethShift;
   if(ExtBarsMinimum<(InpLipsPeriod+InpLipsPeriod))
      ExtBarsMinimum=InpLipsPeriod+InpLipsPeriod;
  }
//+------------------------------------------------------------------+
//|  Alligator OnCalculate 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[])
  {
   if(rates_total<ExtBarsMinimum)
      return(0);
//--- not all data may be calculated
   int calculated=BarsCalculated(ExtJawsHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtJawsHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
   calculated=BarsCalculated(ExtTeethHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtTeethHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
   calculated=BarsCalculated(ExtLipsHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtLipsHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
//--- we can copy not all data
   int to_copy;
   if(prev_calculated>rates_total || prev_calculated<0)
      to_copy=rates_total;
   else
     {
      to_copy=rates_total-prev_calculated;
      if(prev_calculated>0)
         to_copy++;
     }
//--- get ma buffers
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtJawsHandle,0,0,to_copy,ExtJaws)<=0)
     {
      Print("getting ExtJawsHandle is failed! Error ",GetLastError());
      return(0);
     }
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtTeethHandle,0,0,to_copy,ExtTeeth)<=0)
     {
      Print("getting ExtTeethHandle is failed! Error ",GetLastError());
      return(0);
     }
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtLipsHandle,0,0,to_copy,ExtLips)<=0)
     {
      Print("getting ExtLipsHandle is failed! Error ",GetLastError());
      return(0);
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
MrBrooklin #:

Алексей, извини меня за тупизну и бестолковость, но тогда вот этот код, взятый мною из MetaEditor, что за код?

С уважением, Владимир.

1 — технический (штатный)

Получение хендла

int  iAlligator(
   string              symbol,            // имя символа
   ENUM_TIMEFRAMES     period,            // период
   int                 jaw_period,        // период для расчета челюстей
   int                 jaw_shift,         // смещение челюстей по горизонтали
   int                 teeth_period,      // период для расчета зубов
   int                 teeth_shift,       // смещение зубов по горизонтали
   int                 lips_period,       // период для расчета губ
   int                 lips_shift,        // смещение губ по горизонтали
   ENUM_MA_METHOD      ma_method,         // тип сглаживания
   ENUM_APPLIED_PRICE  applied_price      // тип цены или handle
   );

2 — пользовательский. Не смотря на то, что поставляется с терминалом…

А этот так

int  iCustom(
   string           symbol,     // имя символа
   ENUM_TIMEFRAMES  period,     // период
   string           name        // папка/имя_пользовательского индикатора
   ...                          // список входных параметров индикатора
   );
 
Alexey Viktorov #:

1 — технический (штатный)

2 — пользовательский. Не смотря на то, что поставляется с терминалом…

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

С уважением, Владимир.

 
MrBrooklin #:
Наверное и работают по разному?

Отвечу на свой же вопрос. Оказалось, что при одних и тех же входных параметрах, оба индикатора показывают одну и туже картинку.

С уважением, Владимир.


 
ESTARIX #:
Я новичок в бэктестинге. Пытаюсь протестировать советник на основе Мартингейла на MT4. По какой-то причине мой график не работает. Когда советник мартингейлит, чтобы компенсировать убыточную позицию, вы должны видеть большие провалы на графике, но я этого не вижу. Я вижу большие горбы, когда должен видеть большие провалы. Есть какие-нибудь мысли?
Ваш советник при закрытии серии позиций начинает закрывать с самой прибыльной позиции. Поэтому баланс сначала растет, а потом падает, когда начинают закрываться убыточные позиции. Если хотите увидеть провалы, то измените порядок закрытия.
 

в чем может быть ошибка если я имею такой код: 

void SendBuy(double lot)
{
    MqlTradeRequest request = {};
    MqlTradeResult result = {};
    double priceAsk = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
    request.action = TRADE_ACTION_DEAL;
    request.symbol = _Symbol;
    request.volume = lot;
    request.type = ORDER_TYPE_BUY;
    request.price = priceAsk;
    double tp = priceAsk + TakeProfit* _Point;
    if(EnableTakeProfit)
        request.tp = tp;
    else 
        request.tp = 0;
    double sl = priceAsk - StopLoss* _Point;
    if(EnableStopLoss)
        request.sl = sl;
    else 
        request.sl = 0;
    request.deviation = OrderDeviation;
    request.magic = MagicNumber;
    request.comment = "BidAskProfitEA";

    if(OrderSend(request, result)) {
    } else {
        PrintFormat("Ошибка открытия ордера Buy: GetLastError=%d, priceAsk=%g, lot=%g, tp=%g, sl=%g", GetLastError(), priceAsk, lot, tp, sl);
    }
}

2024.04.22 04:02:36.906	BidAskProfitBollEAv5.5(CounterTrend and Scalping) (XAUUSD,M1)	Buy Error: GetLastError=4752, priceAsk=2381.01, lot=0.1, tp=2391.01, sl=2371.01

если других ордеров у меня нет, MagicNumber=222222222 , OrderDeviation=500 , lot=1 на счету 96 тысяч USD, StopLoss==500 , TakeProfit=500 , EnableStopLoss=true , EnableTakeProfit=true


 
AkaEdie #:

в чем может быть ошибка если я имею такой код: 

https://www.mql5.com/ru/docs/constants/errorswarnings/errorcodes

ERR_TRADE_DISABLED

4752

Торговля для эксперта запрещена

Документация по MQL5: Константы, перечисления и структуры / Коды ошибок и предупреждений / Ошибки времени выполнения
Документация по MQL5: Константы, перечисления и структуры / Коды ошибок и предупреждений / Ошибки времени выполнения
  • www.mql5.com
GetLastError() – функция, возвращающая код последней ошибки, которая хранится в предопределенной переменной _LastError . Значение этой переменной...