Domande dai principianti MQL5 MT5 MetaTrader 5 - pagina 1318

 
Kira27:

Per favore, ditemi da quale classe ereditare la vostra classe per utilizzare tutti i metodi di questi

per utilizzare tutti i metodi di queste classi all'interno della vostra classe, senza creare oggetti all'interno della vostra classe?

Ereditare significa creare una classe.

 

Ciao a tutti!
Ho un indicatore - scritto in mql5 che vorrei usare per creare un EA.
Quando creo un EA, non riesco a trovare i buffer di cui ho bisogno, è come se non li avessi affatto.
Ecco come faccio io:

  {
//--- indicator buffers mapping 
   SetIndexBuffer(2,BuyBuffer,INDICATOR_DATA);
   ResetLastError(); 

double   handle3 = 0; 
double   handle4 = 0;
double   UP = 0;
double   DW = 0;

for (int i=1; i<11; i++)
   {
      UP = iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift,2,i); 
      DW = iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift,3,i); 
 
      if (handle3==0)   
      if (UP != EMPTY_VALUE)
      handle3=1;

      if (handle4==0)   
      if (UP != EMPTY_VALUE)
      handle4=1;
      
      if (handle3>0 && handle4)
      break;      
   }  
   
Comment(DoubleToString(handle3,Digits())+"\n"+DoubleToString(handle3,Digits()));
   return(INIT_SUCCEEDED);
  }

Non importa come cambio o aggiungo una linea iCustom - continuo ad ottenere la stessa cosa nel log:

2021.06.26 17:59:42.251 Proba (EURUSD,M15) 1.00000

E il commento: 1.00000 e 1.00000 ancora.

Aiutatemi a capire - è adatto per creare un EA, o devo raffinarlo, o forse sto facendo qualcosa di sbagliato?


File:
StepMA_NRTR.mq5  13 kb
 

In MT5 è usato diversamente. Guardate l'esempio nell'aiuto.

iCustom

Restituisce l'handle dell'indicatore personalizzato specificato.

https://www.mql5.com/ru/docs/indicators/icustom

Документация по MQL5: Технические индикаторы / iCustom
Документация по MQL5: Технические индикаторы / iCustom
  • www.mql5.com
iCustom - Технические индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Aleksei Stepanenko:

In MT5 è usato diversamente. Date un'occhiata all'esempio nella guida.

iCustom

Restituisce l'handle dell'indicatore personalizzato specificato.

https://www.mql5.com/ru/docs/indicators/icustom

Ho già letto questa documentazione, ma non sono sicuro di dove.... o come mettere il numero del buffer e della spina?

Ho appena iniziato a programmare e vi chiedo di essere indulgenti con me.

Comincio a sospettare che questo richieda una funzione aggiuntiva

int copy=CopyBuffer(MA_handle,0,0,rates_total,Label1Buffer); 

Si prega di spiegare.... dove .... e come....?

 
Sprut 185:

Ciao a tutti!
Ho un indicatore - scritto in mql5 che vorrei usare per creare un EA.
Quando creo un EA, non riesco a trovare i buffer di cui ho bisogno, è come se non li avessi affatto.
Ecco come faccio io:

Non importa come cambio o aggiungo una linea iCustom - continuo ad ottenere la stessa cosa nel log:

2021.06.26 17:59:42.251 Proba (EURUSD,M15) 1.00000

E il commento: 1.00000 e 1.00000 ancora.

Aiutatemi a capire - è adatto per creare un EA, o devo raffinarlo, o forse sto facendo qualcosa di sbagliato?


Codice:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double up_buffer[],dn_buffer[],buy_buffer[],sell_buffer[];
   ArraySetAsSeries(up_buffer,true);
   ArraySetAsSeries(dn_buffer,true);
   ArraySetAsSeries(buy_buffer,true);
   ArraySetAsSeries(sell_buffer,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iCustom,0,start_pos,count,up_buffer) ||
      !iGetArray(handle_iCustom,1,start_pos,count,dn_buffer) ||
      !iGetArray(handle_iCustom,2,start_pos,count,buy_buffer) ||
      !iGetArray(handle_iCustom,3,start_pos,count,sell_buffer))
      return;
//---
   string text=" | UpBuffer | DnBuffer | BuyBuffer | SellBuffer"+"\n";
   for(int i=0; i<count; i++)
     {
      text=text+"#"+IntegerToString(i)+" | "+DoubleToString((up_buffer[i]==EMPTY_VALUE?0.0:up_buffer[i]),Digits())
           +" | "+DoubleToString((dn_buffer[i]==EMPTY_VALUE?0.0:dn_buffer[i]),Digits())
           +" | "+DoubleToString((buy_buffer[i]==EMPTY_VALUE?0.0:buy_buffer[i]),Digits())
           +" | "+DoubleToString((sell_buffer[i]==EMPTY_VALUE?0.0:sell_buffer[i]),Digits())+"\n";
     }
   Comment(text);
  }

Risultato:


 
Sprut 185:

Ciao a tutti!
Ho un indicatore - scritto in mql5 - che vorrei usare per creare un EA.

Qui l'ho fatto - sembra funzionare! (dove il giallo è per i buffer)

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

Ho anche bisogno di uno stop loss(non sono riuscito a capire perché ha chiuso immediatamente).

BTCUSDM1 3

BTCUSDM1 4

//+------------------------------------------------------------------+
//|                                                    Sprut 185.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#define    UNO_MAGIC 2344701
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
double            m_adjusted_point;             // point value adjusted for 3 or 5 points
CTrade            m_trade;                      // trading object
CSymbolInfo       m_symbol;                     // symbol info object
CPositionInfo     m_position;                   // trade position object
CAccountInfo      m_account;                    // account info wrapper
//---
enum PRICE_MODE
  {
   HighLow,     // High/Low
   CloseClose   // Close/Close
  };
//---
input group      "---- : StepMA_NRTR:  ----"
input int        Length        = 10;      // Volty Length
input double     Kv            = 1.0;     // Sensivity Factor
input int        StepSize      = 0;       // Constant Step Size (if need)
input double     Percentage    = 0;       // Percentage of Up/Down Moving
input PRICE_MODE Switch        = HighLow; // High/Low Mode Switch (more sensitive)
input int        Shift         = 0;       // Shift
input group      "---- : Parameters:  ----"
input uint       InpStopLoss   = 90;      // : Stop Loss
input uint       InpTakeProfit = 36;      // : Take Profit
input double     InpLots       = 0.1;     // : Lots
input bool       InpClOp       = true;    // : Close opposite
//---
int      price_uno;           //
double   m_stop_loss   = 0.0; // Stop Loss
double   m_take_profit = 0.0; // Take Profit
datetime m_last_open   = 0;   // "0" -> D'1970.01.01 00:00';
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- initialize common information
   if(!m_symbol.Name(Symbol()))             // sets symbol name
      return(false);
   RefreshRates();
   m_trade.SetExpertMagicNumber(UNO_MAGIC); // magic
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=m_symbol.Point()*digits_adjust;
//--- set default deviation for trading in adjusted points
   m_stop_loss   = InpStopLoss*m_adjusted_point;
   m_take_profit = InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints(3*digits_adjust);
//---- получение хендла индикатора StepMA_NRTR
   StepMA_NRTR_Handle=iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift);
   if(StepMA_NRTR_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора StepMA_NRTR");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return;
//---
   if(!SearchTradingSignalsOpen())
     {
      return;
     }
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenBuy(void)
  {
   bool res=false;
//--- check for long position (BUY) possibility
   double price=m_symbol.Ask();
   double tp   =m_symbol.Bid()+m_take_profit;
   double sl   =m_symbol.Bid()-m_stop_loss;
//--- check for free money
   if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_BUY,InpLots,price)<0.0)
      printf("We have no money. Free Margin = %f",m_account.FreeMargin());
   else
     {
      //--- open position
      if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,InpLots,price,sl,tp))
         printf("Position by %s to be opened",Symbol());
      else
        {
         printf("Error opening BUY position by %s : '%s'",Symbol(),m_trade.ResultComment());
         printf("Open parameters : price=%f,SL=%f,TP=%f",price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res=true;
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenSell(void)
  {
   bool res=false;
//--- check for short position (SELL) possibility
   double price=m_symbol.Bid();
   double tp   =m_symbol.Ask()-m_take_profit;
   double sl   =m_symbol.Ask()+m_stop_loss;
//--- check for free money
   if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_SELL,InpLots,price)<0.0)
      printf("We have no money. Free Margin = %f",m_account.FreeMargin());
   else
     {
      //--- open position
      if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,InpLots,price,sl,tp))
         printf("Position by %s to be opened",Symbol());
      else
        {
         printf("Error opening SELL position by %s : '%s'",Symbol(),m_trade.ResultComment());
         printf("Open parameters : price=%f,SL=%f,TP=%f",price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res=true;
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseBuy(void)
  {
//--- close position
   ClosePositions(POSITION_TYPE_BUY);
//---
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseSell(void)
  {
//--- close position
   ClosePositions(POSITION_TYPE_SELL);
//---
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
void FreezeStopsLevels(double &freeze,double &stops)
  {
//--- check Freeze and Stops levels
   double coeff=(double)1;
   if(!RefreshRates() || !m_symbol.Refresh())
      return;
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();
   if(freeze_level==0.0)
      if(1>0)
         freeze_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();
   if(stop_level==0.0)
      if(1>0)
         stop_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//---
   freeze=freeze_level;
   stops=stop_level;
//---
   return;
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   double freeze=0.0,stops=0.0;
   FreezeStopsLevels(freeze,stops);
   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()==m_symbol.Name() && m_position.Magic()==UNO_MAGIC)
            if(m_position.PositionType()==pos_type)
              {
               if(m_position.PositionType()==POSITION_TYPE_BUY)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     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());
                 }
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     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());
                 }
               PlaySound("ok.wav");
              }
  }
//+------------------------------------------------------------------+
//| Filling the indicator buffers from the indicator                 |
//+------------------------------------------------------------------+
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))
     {
      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)
     {
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignalsOpen(void)
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(Symbol(),Period(),0);
   if(time_0==m_last_open)
      return(true);
   m_last_open=time_0;
//--- we work only at the time of the birth of new bar
   double StepMA_NRTR[],StepMA_NRTRS[];
   bool StNRUp,StNRDn;
   ArraySetAsSeries(StepMA_NRTR,true);
   ArraySetAsSeries(StepMA_NRTRS,true);
   int start_pos=0,count=3;
   if(!iGetArray(StepMA_NRTR_Handle,0,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle,1,start_pos,count,StepMA_NRTRS))
     {
      return(false);
     }
//+------------------------------------------------------------------+
   StNRUp=StepMA_NRTR[0]<StepMA_NRTRS[0];
//---
   StNRDn=StepMA_NRTR[0]>StepMA_NRTRS[0];
//+------------------------------------------------------------------+
//--- BUY Signal
   if(StNRUp)
     {
      if(InpClOp)
         CheckForCloseSell();
      Sleep(1000);
      if(price_uno<0)
         CheckForOpenBuy();
      price_uno=+1;
      return(true);
     }
//--- SELL Signal
   if(StNRDn)
     {
      if(InpClOp)
         CheckForCloseBuy();
      Sleep(1000);
      if(price_uno>0)
         CheckForOpenSell();
      price_uno=-1;
      return(true);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+


 
Sprut 185:

Comincio a sospettare che questo richieda una funzione extra

Proprio così. Si collega l'indicatore in OnInit, si impostano i parametri lì e si ottiene il suo handle. E poi usare il CopyBuffer.


https://www.mql5.com/ru/docs/series/copybuffer

Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
  • www.mql5.com
CopyBuffer - Доступ к таймсериям и индикаторам - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
SanAlex:

Ho fatto questo - sembra funzionare! (dove il giallo è il buffer)

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

Si scopre che ho bisogno di uno stop loss - (non riusciva a capire perché ha chiuso immediatamente) ha aggiunto uno stop loss



Grazie mille!!!

Hai fatto un buon lavoro, ma sono interessato a un algoritmo completamente diverso per l'EA. Vorrei usare una semplice Martingala (setaccio) con questi parametri personalizzabili:

input group "======== МАРТИН ========"; 
input int      MMType        = 1;        // 1 - вкл. , 2 - выкл.
input double   Multiplikator = 1.667;    // множитель следующего лота
input double   Step          = 150.0;    // Расстояние между ордерами
input group "==== МАНИ МЕНЕДЖМЕНТ ====; 
input bool     LotConst      = true;     // фиксированный - true, или от  баланса - false
input group "-: фиксированный лот :--"; 
input double   Lot           = 0.01;     // первый фиксированный лот, если МАРТИН включен
input group "---: лот от баланса :---"; 
input double   RiskPercent   = 30.0;     // первый лот в процентах от баланса, если МАРТИН включен
input group "== ПРИБЫЛЬ В ПУНКТАХ ==="; 
input double   TakeProfit    = 56.0;     // параметры тейкпрофита в пунктах
input group "========= Шаг =========="; 
input double   Step          = 150.0;    // шаг в пунктах между ордерами
input group "===== ОГРАНИЧИТЕЛЬ =====";  
input int      MaxTrades     = 15;       // Максимальное количество ордеров одного направления
input group "=== ПРОСКАЛЬЗОВАНИЕ ====";  
input double   Slippage      = 5.0;      // Допустимое проскальзывание на новостях в пунктах
input group "== МАГИЧЕСКИЙ  НОМЕР ===";  
input int      Magic         = 1111111 ; // Идентификатор ордера (Магик №)

, ma aggiungeteci l'indicatore che ho messo - sopra. E usarlo come trigger (falso - funziona solo in SHORT e vero - funziona solo in LONG).

Ho scelto questo indicatore - solo perché funziona come le medie mobili, ma ha alcuni filtri di lisciatura e punti di cambio di direzione del prezzo, che possono essere utilizzati come trigger per l'EA per lavorare solo sulla tendenza utilizzando le impostazioni di profitto dal menu.

E non appena il take profit è chiuso, apriamo l'ordine successivo nella stessa direzione (nella tendenza), fino a quando la tendenza è finita e il nostro trigger è cambiato. Se un ordine appare fuori tendenza (nel momento in cui la tendenza cambia da uno stato all'altro), dobbiamo usare Martins con le impostazioni dal menu per esso.

Se volete aiutare a scrivere un tale EA, ve ne sarei molto grato.

Ora sull'argomento:
Capisco che nel mio codice dell'indicatore stesso - non sono buffer di indicatori, ma array di buffer e tu - nell'Expert Advisor li hai portati nell'indicatore.
Per favore, fatemi sapere se ho capito bene?


 
Sprut 185:

Ora per il soggetto:

Ho capito che nel mio codice dell'indicatore stesso - non si trovano buffer di indicatori, ma array di buffer e tu - nell'Expert Advisor li hai portati all'indicatore.
Per favore consigliatemi se ho capito bene?


Sono autodidatta e non sono in grado di spiegarlo, ho solo selezionato le funzioni di cui ho bisogno.

Praticamente copio i codici da Vladimir Karputov, grazie mille! - Se avete delle domande ve lo dirà lui.

Vladimir Karputov
Vladimir Karputov
  • 2021.06.25
  • www.mql5.com
Профиль трейдера
 
SanAlex:

Ho capito che hai bisogno di un indicatore per filtrare!

Devi far passare il tuo Expert Advisor attraverso questo filtro

Non mi hai capito bene!!!
Motivazione: