EA по системе НМА ЕМА/WMA - страница 2

 
Eugen8519:

вроде сделал как Вы хотели  (жёлтым мечено - это где были изменения

2 EMA_WMA v2

//+------------------------------------------------------------------+
//|                          EMA_WMA v2(barabashkakvn's edition).mq5 |
//|                               Copyright © 2009, Vladimir Hlystov |
//|                                                cmillion@narod.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Vladimir Hlystov"
#property link      "cmillion@narod.ru"
#property version   "2.000"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
CAccountInfo   m_account;                    // account info wrapper
//+------------------------------------------------------------------+
//| Enum Prices                                                      |
//+------------------------------------------------------------------+
enum enPrices
  {
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average     // Average (high+low+oprn+close)/4
  };
//+------------------------------------------------------------------+
//--- Super Trend Hull Indicator
input int      Inp_hullPeriod       = 12;          // Hull period
input enPrices Inp_Price            = pr_median;   // Price
input int      Inp_atrPeriod        = 12;          // ATR period
input double   Inp_atrMultiplier    = 0.66;        // ATR multiplier
//---
input int      period_EMA     = 28;          // EMA: averaging period
input int      period_WMA     = 8;           // WMA: averaging period
input ushort   InpStopLoss    = 50;          // StopLoss
input ushort   InpTakeProfit  = 50;          // TakeProfit
input ushort   InpTrailingStop= 50;          // Trailing Stop
input ushort   InpTrailingStep= 10;          // Trailing Step
input int      risk           = 10;          // Risk
double         my_lot;
ulong          m_magic=72406264;             // magic number
//---
double my_SL,my_TP;
datetime TimeBar;

double         ExtStopLoss=0.0;
double         ExtTakeProfit=0.0;
double         ExtTrailingStop=0.0;
double         ExtTrailingStep=0.0;
int            m_bar_current=0;
int            handle_iCustom;               // variable for storing the handle of the iCustom indicator
int            handle_iMA_EMA;               // variable for storing the handle of the iMA indicator
int            handle_iMA_WMA;               // variable for storing the handle of the iMA indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpTrailingStop!=0 && InpTrailingStep==0)
     {
      Alert(__FUNCTION__," ERROR: Trailing is not possible: the parameter \"Trailing Step\" is zero!");
      return(INIT_PARAMETERS_INCORRECT);
     }
//---
   m_symbol.Name(Symbol());                  // sets symbol name
//---
   m_trade.SetExpertMagicNumber(m_magic);    // sets magic number
   if(!RefreshRates())
     {
      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),
            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));
      return(INIT_FAILED);
     }
   m_symbol.Refresh();
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   ExtStopLoss    = InpStopLoss     * digits_adjust;
   ExtTakeProfit  = InpTakeProfit   * digits_adjust;
   ExtTrailingStop= InpTrailingStop * digits_adjust;
   ExtTrailingStep= InpTrailingStep * digits_adjust;
//--- create handle of the indicator iMA
   handle_iMA_EMA=iMA(Symbol(),Period(),period_EMA,0,MODE_EMA,PRICE_OPEN);
//--- if the handle is not created
   if(handle_iMA_EMA==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_WMA=iMA(Symbol(),Period(),period_WMA,0,MODE_LWMA,PRICE_OPEN);
//--- if the handle is not created
   if(handle_iMA_WMA==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iCustom
   handle_iCustom=iCustom(m_symbol.Name(),Period(),"super_trend_hull",Inp_hullPeriod,Inp_Price,Inp_atrPeriod,Inp_atrMultiplier);
//--- if the handle is not created
   if(handle_iCustom==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iCustom indicator for the symbol %s/%s, error code %d",
                  m_symbol.Name(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   datetime time_0=iTime(0);
   if(TimeBar==time_0)
      return;
   if(TimeBar==0)
     {
      TimeBar=time_0;
      return;
     }//first program run
   double color_buffer[],EMA0[],WMA0[];
   ArraySetAsSeries(color_buffer,true);
   ArraySetAsSeries(EMA0,true);
   ArraySetAsSeries(WMA0,true);
   int start_pos=1,count=3;
   if(!iGetArray(handle_iCustom,1,start_pos,count,color_buffer))
      return;
   if(!iGetArray(handle_iMA_EMA,0,start_pos,count,EMA0))
      return;
   if(!iGetArray(handle_iMA_WMA,0,start_pos,count,WMA0))
      return;
//---
//if(color_buffer[m_bar_current+1]>color_buffer[m_bar_current]) //Buy
   if(EMA0[m_bar_current]<WMA0[m_bar_current] && EMA0[m_bar_current+1]>WMA0[m_bar_current+1]) //Buy
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Sell");
     }
//if(color_buffer[m_bar_current+1]<color_buffer[m_bar_current]) //Sell
   if(EMA0[m_bar_current]>WMA0[m_bar_current] && EMA0[m_bar_current+1]<WMA0[m_bar_current+1]) //Sell
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Buy");
     }
//---
//if(EMA0[m_bar_current]<WMA0[m_bar_current] && EMA0[m_bar_current+1]>WMA0[m_bar_current+1]) //Buy
   if(color_buffer[m_bar_current+1]>color_buffer[m_bar_current]) //Buy
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP  = m_symbol.Ask() + ExtTakeProfit*Point();
      my_SL  = m_symbol.Ask() - ExtStopLoss*Point();
      my_lot = LOT(risk);
      OPENORDER("Buy");
     }
//if(EMA0[m_bar_current]>WMA0[m_bar_current] && EMA0[m_bar_current+1]<WMA0[m_bar_current+1]) //Sell
   if(color_buffer[m_bar_current+1]<color_buffer[m_bar_current]) //Sell
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP=m_symbol.Bid()-ExtTakeProfit*Point();
      my_SL = m_symbol.Bid() + ExtStopLoss*Point();
      my_lot= LOT(risk);
      OPENORDER("Sell");
     }
//---
   Trailing();
//---
   return;
  }
//--------------------------------------------------------------------
void CLOSEORDER(string ord)
  {
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY && ord=="Buy")
               m_trade.PositionClose(m_position.Ticket());  // Close Buy
            if(m_position.PositionType()==POSITION_TYPE_SELL && ord=="Sell")
               m_trade.PositionClose(m_position.Ticket()); // Close Sell
           }
  }
//--------------------------------------------------------------------
void OPENORDER(string ord)
  {
   if(ord=="Buy")
      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription(),
               ", ticket of deal: ",m_trade.ResultDeal());
   if(ord=="Sell")
      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
         Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of Retcode: ",m_trade.ResultRetcodeDescription(),
               ", ticket of order: ",m_trade.ResultOrder());
   return;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double LOT(int input_risk)
  {
   if(!RefreshRates())
      return(m_symbol.LotsMin());
   double MINLOT=m_symbol.LotsMin();
   double margin_required=0.0;
   if(!OrderCalcMargin(ORDER_TYPE_BUY,Symbol(),1.0,m_symbol.Ask(),margin_required))
      return(m_symbol.LotsMin());
   my_lot=m_account.FreeMargin()*input_risk/100.0/margin_required;
   if(my_lot>m_symbol.LotsMax())
      my_lot=m_symbol.LotsMax();
   if(my_lot<MINLOT)
      my_lot=MINLOT;
   if(MINLOT<0.1)
      my_lot=NormalizeDouble(my_lot,2);
   else
      my_lot=NormalizeDouble(my_lot,1);
   return(my_lot);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Get Time for specified bar index                                 |
//+------------------------------------------------------------------+
datetime iTime(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)
  {
   if(symbol==NULL)
      symbol=Symbol();
   if(timeframe==0)
      timeframe=Period();
   datetime Time[];
   datetime time=0;
   ArraySetAsSeries(Time,true);
   int copied=CopyTime(symbol,timeframe,index,1,Time);
   if(copied>0)
      time=Time[0];
   return(time);
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
//| Trailing                                                         |
//+------------------------------------------------------------------+
void Trailing()
  {
   if(InpTrailingStop==0)
      return;
   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()==m_magic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(m_position.PriceCurrent()-m_position.PriceOpen()>ExtTrailingStop+ExtTrailingStep)
                  if(m_position.StopLoss()<m_position.PriceCurrent()-(ExtTrailingStop+ExtTrailingStep))
                    {
                     if(!m_trade.PositionModify(m_position.Ticket(),
                                                m_symbol.NormalizePrice(m_position.PriceCurrent()-ExtTrailingStop),
                                                m_position.TakeProfit()))
                        Print("Modify ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                    }
              }
            else
              {
               if(m_position.PriceOpen()-m_position.PriceCurrent()>ExtTrailingStop+ExtTrailingStep)
                  if((m_position.StopLoss()>(m_position.PriceCurrent()+(ExtTrailingStop+ExtTrailingStep))) ||
                     (m_position.StopLoss()==0))
                    {
                     if(!m_trade.PositionModify(m_position.Ticket(),
                                                m_symbol.NormalizePrice(m_position.PriceCurrent()+ExtTrailingStop),
                                                m_position.TakeProfit()))
                        Print("Modify ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                    }
              }
           }
  }
//+------------------------------------------------------------------+
 
SanAlex:

вроде сделал как Вы хотели  (жёлтым мечено - это где были изменения


Спасибо тебе большое. 
Ну его мне ещё ковырять придется
Не разберусь как там решается StopLoss и Take Profit 
Как  и  чем связан ExtStopLoss с InpStopLoss 



Зачем здесь? 
double my_SL,my_TP;



И что если я хочу испытать другой HMA индикатор,  мне нужно будет только поменять 

super_trend_hull
На другой, например "HMA5"  ? 



 
Eugen8519:

Спасибо тебе большое. 
Ну его мне ещё ковырять придется
Не разберусь как там решается StopLoss и Take Profit 
Как  и  чем связан ExtStopLoss с InpStopLoss 



Зачем здесь? 



И что если я хочу испытать другой HMA индикатор,  мне нужно будет только поменять 

На другой, например "HMA5"  ? 



Индикатор может подойти если он такой же ? если он другого типа, тогда нужно немного подправить. А насчёт профитов и стопов - там автор эксперта химичил, что Вам в функции профит стоп не нравиться???

вот сюда передаётся 

   if(ord=="Buy")
      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))

стоп лос и тек профит - тут связан 

//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   ExtStopLoss    = InpStopLoss     * digits_adjust;
   ExtTakeProfit  = InpTakeProfit   * digits_adjust;
 
SanAlex:

Индикатор может подойти если он такой же ? если он другого типа, тогда нужно немного подправить. А насчёт профитов и стопов - там автор эксперта химичил, что Вам в функции профит стоп не нравиться???

вот сюда передаётся 



Нет, меня SL  и ТP устраивает, просто охота понять как это здесь работает



 
Eugen8519:


Нет, меня SL  и ТP устраивает, просто охота понять как это здесь работает



здесь Вы задаёте расстояние 

input ushort   InpTakeProfit  = 50;          // TakeProfit

а здесь умножается на 10

   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   ExtStopLoss    = InpStopLoss     * digits_adjust;
   ExtTakeProfit  = InpTakeProfit   * digits_adjust;

а здесь передаётся  на   my_TP

      my_TP=m_symbol.Bid()-ExtTakeProfit*Point();
      my_SL = m_symbol.Bid() + ExtStopLoss*Point();

а сюда уже попадает с нормализацией

   if(ord=="Sell")
      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

получается из 50 в терминале закроется когда будет показывать 500 пунктов  

 

 
SanAlex:

здесь Вы задаёте расстояние 

а здесь умножается на 10

а здесь передаётся  на   my_TP

а сюда уже попадает с нормализацией

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

получается из 50 в терминале когда будет показывать 500 пунктов  

 

Ну вот с лотами, Стопом и таке профитом я разобрался. 
Но вот один феномен есть который мне нужно поправить
Идея в том что если открылась  SELL позиция и через некоторое время появился новый сигнал на покупку то робот путается и ставит п осли сигнала Buy позицию на продажу

Вот так я сделал


void OPENORDER(string ord)
  {
   if(all_positions==1)
     {
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               return;                          // Если buy, то не открываемся
     }
      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription(),
               ", ticket of deal: ",m_trade.ResultDeal());
   if(ord=="Sell")

   if(all_positions==1)
     {
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               return;                             // Если sell, то не открываемся
     }
      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
         Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of Retcode: ",m_trade.ResultRetcodeDescription(),
               ", ticket of order: ",m_trade.ResultOrder());
   return;
  }


Вот результат





Файлы:
Unbenannt2.PNG  14 kb
 

вроде разобрался

вот если он зашол в позицию  при закрытием под линией HMA  и  потом позже свеча закрывается уже над линией HMA , позиция просто закрывается.

но нужно чтобы в этот момент позиция меняла направления (разворачивалась)


вот здесь неправильно


https://ibb.co/sHyfbZL




может кто знает как это сделать здесь?


//if(color_buffer[m_bar_current+1]>color_buffer[m_bar_current]) //Buy
   if(EMA0[m_bar_current]<WMA0[m_bar_current] && EMA0[m_bar_current+1]>WMA0[m_bar_current+1]) //Buy
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Sell");
     }
//if(color_buffer[m_bar_current+1]<color_buffer[m_bar_current]) //Sell
   if(EMA0[m_bar_current]>WMA0[m_bar_current] && EMA0[m_bar_current+1]<WMA0[m_bar_current+1]) //Sell
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Buy");
     }
//---
//if(EMA0[m_bar_current]<WMA0[m_bar_current] && EMA0[m_bar_current+1]>WMA0[m_bar_current+1]) //Buy
   if(color_buffer[m_bar_current+1]>color_buffer[m_bar_current]) //Buy
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP  = m_symbol.Ask() + ExtTakeProfit*Point();
      my_SL  = m_symbol.Ask() - ExtStopLoss*Point();
      my_lot = Lots;
      OPENORDER("Buy");
     }
//if(EMA0[m_bar_current]>WMA0[m_bar_current] && EMA0[m_bar_current+1]<WMA0[m_bar_current+1]) //Sell
   if(color_buffer[m_bar_current+1]<color_buffer[m_bar_current]) //Sell
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP = m_symbol.Bid() - ExtTakeProfit*Point();
      my_SL = m_symbol.Bid() + ExtStopLoss*Point();
      my_lot= Lots;
      OPENORDER("Sell");
     }
 
   return;
  }
//--------------------------------------------------------------------
void CLOSEORDER(string ord)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)  // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY && ord=="Buy")
               m_trade.PositionClose(m_position.Ticket());  // Close Buy
            if(m_position.PositionType()==POSITION_TYPE_SELL && ord=="Sell")
               m_trade.PositionClose(m_position.Ticket()); // Close Sell
           }
  }
//--------------------------------------------------------------------
void OPENORDER(string ord)
  {
  if(ord=="Sell")
   if(all_positions==1)
  
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
           if(m_position.PositionType()==POSITION_TYPE_BUY)
            //if(m_position.PositionType()==POSITION_TYPE_SELL)
               return;                          // Если buy, то не открываемся
 
      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription(),
               ", ticket of deal: ",m_trade.ResultDeal());
   if(ord=="Sell")
   if(all_positions==1)
 
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
            //if(m_position.PositionType()==POSITION_TYPE_BUY)
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               return;                          // Если buy, то не открываемся
 

      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
         Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of Retcode: ",m_trade.ResultRetcodeDescription(),
               ", ticket of order: ",m_trade.ResultOrder());
   return;
  }
Unbenannt3
Unbenannt3
  • ibb.co
Bild Unbenannt3 gespeichert in ImgBB