Как начать работу с MQL5 - страница 39

 
Vladimir Karputov iStochastic get value.mq5

Не забывайте о правилах: создавайте хэндл индикатора ОДИН раз в OnInit, используйте CopyBuffer для получения данных.


Результат:


Закрывают ли эти коды индикатор stochastik, когда разница между двумя линиями слишком велика?

 
Kutluhan Yesilkaya # :

Закрывают ли эти коды индикатор stochastik, когда разница между двумя линиями слишком велика?

Приведенный код - это пример кода, как правильно создать индикатор и как получить его значение. То есть это учебный код для эксперта, который делает ТОЛЬКО две вещи: показывает, как правильно создать индикатор и как получить его значение.

 

Очень простое пересечение iMA Open Position

(код 'Very Simple Intersection iMA Open Position.mq5')

Пример показывает, как:

  • создать хэндл индикатора iMA
  • получать значения индикатора
  • закрывать и открывать позиции при пересечении двух iMA ("Fast" и "Slow")

//+------------------------------------------------------------------+
//|                   Very Simple Intersection iMA Open Position.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input group             "Position size management (lot calculation)"
input double               InpLots                    = 0.01;           // Lots
input group             "MA Fast"
input int                  Inp_MA_Fast_ma_period      = 5;              // MA Fast: averaging period
input int                  Inp_MA_Fast_ma_shift       = 0;              // MA Fast: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Fast_ma_method      = MODE_SMA;       // MA Fast: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price  = PRICE_CLOSE;    // MA Fast: type of price
input group             "MA Slow"
input int                  Inp_MA_Slow_ma_period      = 15;             // MA Slow: averaging period
input int                  Inp_MA_Slow_ma_shift       = 0;              // MA Slow: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Slow_ma_method      = MODE_SMA;       // MA Slow: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price  = PRICE_CLOSE;    // MA Slow: type of price
input group             "Additional features"
input ulong                InpMagic                   = 200;            // Magic number
//---
int      handle_iMA_Fast;  // variable for storing the handle of the iMA indicator
int      handle_iMA_Slow;  // variable for storing the handle of the iMA indicator

datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
bool     m_init_error               = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
   m_init_error               = false;    // error on InInit
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(10);
//---
//--- create handle of the indicator iMA
   handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,
                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);
//--- if the handle is not created
   if(handle_iMA_Fast==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator ('Fast') for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,
                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);
//--- if the handle is not created
   if(handle_iMA_Slow==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator ('Slow') for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(Symbol(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//---
   double ma_fast[],ma_slow[];
   ArraySetAsSeries(ma_fast,true);
   ArraySetAsSeries(ma_slow,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iMA_Fast,0,start_pos,count,ma_fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,ma_slow))
     {
      m_prev_bars=0;
      return;
     }
//---
   if(ma_fast[2]<ma_slow[2] && ma_fast[1]>ma_slow[1])
     {
      //--- Close all 'SELL' ...
      for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
         if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
            if(m_position.Symbol()==Symbol() && m_position.Magic()==InpMagic)
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
      //--- ... and open one 'BUY'
      m_trade.Buy(InpLots);
      //---
      return;
     }
   if(ma_fast[2]>ma_slow[2] && ma_fast[1]<ma_slow[1])
     {
      //--- Close all 'BUY' ...
      for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
         if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
            if(m_position.Symbol()==Symbol() && m_position.Magic()==InpMagic)
               if(m_position.PositionType()==POSITION_TYPE_BUY)
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
      //--- ...and open one 'SELL'
      m_trade.Sell(InpLots);
      //---
      return;
     }
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      //--- if the copying fails, tell the error code
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                  __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+
 

Обновленный скрипт - вывод 'ENUM_TIMEFRAMES'

Таймфрейм в MT5 является битовым полем. Вывод значений'HEX' дает представление о том, как кодируются таймфреймы (см. кодировку таймфреймов от H1 и выше).


Результат:

  0: "PERIOD_CURRENT", int:     0, HEX:    0, "Current timeframe"
  1: "     PERIOD_M1", int:     1, HEX:    1, "1 minute"
  2: "     PERIOD_M2", int:     2, HEX:    2, "2 minutes"
  3: "     PERIOD_M3", int:     3, HEX:    3, "3 minutes"
  4: "     PERIOD_M4", int:     4, HEX:    4, "4 minutes"
  5: "     PERIOD_M5", int:     5, HEX:    5, "5 minutes"
  6: "     PERIOD_M6", int:     6, HEX:    6, "6 minutes"
  7: "    PERIOD_M10", int:    10, HEX:    A, "10 minutes"
  8: "    PERIOD_M12", int:    12, HEX:    C, "12 minutes"
  9: "    PERIOD_M15", int:    15, HEX:    F, "15 minutes"
 10: "    PERIOD_M20", int:    20, HEX:   14, "20 minutes"
 11: "    PERIOD_M30", int:    30, HEX:   1 E, "30 minutes"
 12: "     PERIOD_H1", int: 16385, HEX: 4 001, "1 hour"
 13: "     PERIOD_H2", int: 16386, HEX: 4 002, "2 hours"
 14: "     PERIOD_H3", int: 16387, HEX: 4 003, "3 hours"
 15: "     PERIOD_H4", int: 16388, HEX: 4 004, "4 hours"
 16: "     PERIOD_H6", int: 16390, HEX: 4 006, "6 hours"
 17: "     PERIOD_H8", int: 16392, HEX: 4 008, "8 hours"
 18: "    PERIOD_H12", int: 16396, HEX: 4 00 C, "12 hours"
 19: "     PERIOD_D1", int: 16408, HEX: 4 018, "1 day"
 20: "     PERIOD_W1", int: 32769, HEX: 8 001, "1 week"
 21: "    PERIOD_MN1", int: 49153, HEX: C 001, "1 month"


24 -> HEX -> '18'

Файлы:
 

Простой трейлинг

Код: 'Simple Trailing.mq5'

Простой трейлинг - работает на каждом тике, работает как для убыточной, так и для прибыльной позиции. Работает с текущим символом и только для позиций с'Magic number'

//+------------------------------------------------------------------+
//|                                              Simple Trailing.mq5 |
//|                                  Copyright 2022, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property description "'Trailing' - in Points (1.00055-1.00045=10 points)"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Trailing"
input uint                 InpTrailingStop      = 250;         // Trailing Stop, min distance from price to SL
input uint                 InpTrailingStep      = 50;          // Trailing Step
input group             "Additional features"
input bool                 InpPrintLog          = true;        // Print log
input ulong                InpDeviation         = 10;          // Deviation
input ulong                InpMagic             = 75941265;    // Magic number
//---
double   m_trailing_stop            = 0.0;      // Trailing Stop              -> double
double   m_trailing_step            = 0.0;      // Trailing Step              -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_trailing_stop            = InpTrailingStop             * m_symbol.Point();
   m_trailing_step            = InpTrailingStep             * m_symbol.Point();
//---
   /*bool res=false;
   while(!res)
     {
      res=m_trade.Sell(0.03);
      if(!res)
         Sleep(1000*60*5);
     }*/
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            double price_current = m_position.PriceCurrent();
            double price_open    = m_position.PriceOpen();
            double stop_loss     = m_position.StopLoss();
            double take_profit   = m_position.TakeProfit();
            //---
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(price_current-stop_loss>=m_trailing_stop+m_trailing_step)
                 {
                  if(!m_trade.PositionModify(m_position.Ticket(),m_symbol.NormalizePrice(price_current-m_trailing_stop),take_profit))
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify BUY ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                  continue;
                 }
              }
            else
              {
               if(stop_loss-price_current>=m_trailing_stop+m_trailing_step || stop_loss==0.0)
                 {
                  if(!m_trade.PositionModify(m_position.Ticket(),m_symbol.NormalizePrice(price_current+m_trailing_stop),take_profit))
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify SELL ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                 }
              }
           }
//---
   /*if(PositionsTotal()==0)
     {
      bool res=false;
      while(!res)
        {
         res=m_trade.Sell(0.03);
         if(!res)
            Sleep(1000*60*5);
        }
     }*/
  }
//+------------------------------------------------------------------+
Файлы:
 
Эта тема заслуживает гораздо большего внимания. Спасибо за хорошую работу.
 

Простой советник. Всегда одна позиция. Позиция открывается со стоп-лоссом и тейк-профитом. Защиты нет

Код: 'Stop Loss Take Profit EA.mq5'

//+------------------------------------------------------------------+
//|                                     Stop Loss Take Profit EA.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Trading settings"
input uint                 InpStopLoss             = 150;            // Stop Loss (SL) ('0' -> OFF)
input uint                 InpTakeProfit           = 460;            // Take Profit (TP) ('0' -> OFF)
input group             "Additional features"
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 200;            // Magic number
//---
double   m_stop_loss                = 0.0;      // Stop Loss                  -> double
double   m_take_profit              = 0.0;      // Take Profit                -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_stop_loss                = 0.0;      // Stop Loss                  -> double
   m_take_profit              = 0.0;      // Take Profit                -> double
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_stop_loss                = InpStopLoss                 * m_symbol.Point();
   m_take_profit              = InpTakeProfit               * m_symbol.Point();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(!IsPositionExists())
     {
      if(!RefreshRates())
         return;
      if(MathRand()<32767/2)
        {
         //--- open BUY
         double sl=(m_stop_loss==0.0)?0.0:m_symbol.Ask()-m_stop_loss;
         double tp=(m_take_profit==0.0)?0.0:m_symbol.Ask()+m_take_profit;
         m_trade.Buy(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Ask(),sl,tp);
         //---
         return;
        }
      else
        {
         //--- open SELL
         double sl=(m_stop_loss==0.0)?0.0:m_symbol.Bid()+m_stop_loss;
         double tp=(m_take_profit==0.0)?0.0:m_symbol.Bid()-m_take_profit;
         m_trade.Sell(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Bid(),sl,tp);
        }
     }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Is position exists                                               |
//+------------------------------------------------------------------+
bool IsPositionExists(void)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+
Файлы:
 

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

//+------------------------------------------------------------------+
//|                                                          S&R.mq5 |
//|                                  Copyright 2022, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

int   Candles = 250;
MqlRates    rates[];
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   ArraySetAsSeries(rates,true);
   CopyRates(_Symbol,_Period,0,Candles,rates);
   Alert("");

   for(int i=5; i<Candles; i++)
     {
      if(support(i))
         Alert("Support: ",i);
     }
  }
//+------------------------------------------------------------------+
//|                                                                                |
//+------------------------------------------------------------------+
bool support(int i)
  {
   int candles = 2;

   for(int l=i; l<i+candles; l++)
     {
      if(rates[l+1].close>rates[l+1].open && rates[l+1].low>rates[l+2].low)
         return (false);
     }
   for(int l=i; l>l-candles; l--)
     {
      if(rates[l].close<rates[l].open && rates[l].low>rates[l-1].low)
         return (false);
     }
   return true;


  }
//+------------------------------------------------------------------+

Я не могу понять, что я делаю не так, но он не возвращает true.

 
Доброе утро, Владимир,

Я изучаю mql5. Я разработал модуль, который проверяет вводимые данные и многочисленные флаги, которые подтверждают это, или нет.
Ситуация, в которой я нахожусь, очень кратко изложена в приложенном коде: Сигнал на вход, определенный индикатором MA, и вход, подтвержденный осциллятором.
В представленном случае у меня есть 2 осциллятора, и в тестере стратегий я могу тестировать их по отдельности или оба вместе.

Что я хочу, так это иметь возможность выполнять оба по отдельности из симулятора стратегии, таким образом, чтобы при одном выполнении симулятора я мог получить индивидуальные результаты, результаты которых я мог бы извлечь, например, с помощью Print.

Заранее спасибо,
Хуан Луис.
//+------------------------------------------------------------------+
//|                                      juanluistrading@gmail.com   |
//+------------------------------------------------------------------+

#include<Trade\Trade.mqh>
 CTrade  trade;

input double Lotes=0.01;
input double TP=0.0001; //TakeProfit
input double SL=0.0001; //StopLoss

input bool BUL=false;
input bool CCI=false;

string senal, entrada;
double Ask, Bid;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnInit()
  {

  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   Ask=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   Bid=NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   senal=SenalIMA();

   if(BUL==true)
     {
      entrada=EntradaBUL();
      if(senal=="buy" && entrada=="buy")
         OpenBuy();
      if(senal=="sell" && entrada=="sell")
         OpenSell();
     }

   if(CCI==true)
     {
      entrada=EntradaCCI();
      if(senal=="buy" && entrada=="buy")
         OpenBuy();
      if(senal=="sell" && entrada=="sell")
         OpenSell();
     }
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string SenalIMA()
  {
   MqlRates PriceInfo[];
   ArraySetAsSeries(PriceInfo,true);
   int PriceData =CopyRates(Symbol(),Period(),0,3,PriceInfo);
   senal="";
   double myPriceArray[];
   int AdaptiveMovingAverageDefinition = iAMA(_Symbol,_Period,9,2,30,0,PRICE_CLOSE);
   ArraySetAsSeries(myPriceArray,true);
   CopyBuffer(AdaptiveMovingAverageDefinition,0,0,3,myPriceArray);
   double AdaptiveMovingAverageValue=NormalizeDouble(myPriceArray[0],6);

   if(AdaptiveMovingAverageValue> PriceInfo[0].close)
      senal ="buy";
   if(AdaptiveMovingAverageValue< PriceInfo[0].close)
      senal ="sell";

   return senal;
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string EntradaBUL()
  {
   entrada="";
   static double BullsPowerValueOld;
   double myPriceArray[];
   int BullsPowerDefinition =iBullsPower(_Symbol,_Period,13);
   ArraySetAsSeries(myPriceArray,true);
   CopyBuffer(BullsPowerDefinition,0,0,3,myPriceArray);

   double BullsPowerValue=(myPriceArray[0]);

   if((BullsPowerValue>0)&&(BullsPowerValueOld<0))
     {
      entrada="buy";
     }
   BullsPowerValueOld=BullsPowerValue;

   return entrada;
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string EntradaCCI()
  {
   entrada="";
   double myPriceArray[];
   int ICCIDefinition = iCCI(_Symbol,_Period,14,PRICE_TYPICAL);
   ArraySetAsSeries(myPriceArray,true);
   CopyBuffer(ICCIDefinition,0,0,3,myPriceArray);

   double ICCIVal=(myPriceArray[0]);

   if(ICCIVal>100)
      entrada="sell";
   if(ICCIVal<-100)
      entrada="buy";

   return entrada;
  }


void OpenBuy() {trade.Buy(Lotes,NULL,Ask,Ask-SL,Ask+TP,NULL);}

void OpenSell() {trade.Sell(Lotes,NULL,Bid,Bid+SL,Bid-TP,NULL);}

//+------------------------------------------------------------------+

 
Vladimir Karputov #:

Да, фракталы могут содержать '0.0' или 'EMPTY_VALUE'. Пример:

Код: 'iFractals.mq5'


Результат:


Привет, спасибо, это было очень полезно, Если я хочу, чтобы фрактальная дата также была добавлена к нему? Я пробовал CopyTime(), но он дает неправильное значение времени, которое не соответствует фрактальному значению.
Причина обращения: