Creare un robot - pagina 4

 
Sì, l'ho fatto, l'ho fatto, ci ho pensato, non l'ho detto con precisione. Ho sempre problemi ad articolare i miei pensieri. Al decimo cambiamento, le parole sembrano avere un senso
 
Роман Жилин:

Oooh, grazie mille, con tante informazioni si possono fare tante cose...

Sto per partire per un viaggio di lavoro, quindi sto pensando di approfondire il materiale che mi è stato dato, ma la codifica... Potrei farlo anche su un foglio di carta, sarebbe un buon strumento di allenamento...


Saluti, Roman

Questa è una piccola frazione di ciò che dovete sapere, un granello di sabbia nel mare del codice del programma. Ma non basta sapere cosa usare, dove usarlo e quando usarlo!

Se si procede dal nome dell'argomento"Creazione di robot", allora è necessario avere una strategia di trading in pareggio (redditizia, o come volete chiamarla), e solo allora studiare il linguaggio di programmazione MQL5.

A proposito, il MetaEditor del terminale MT5 ha il Wizard MQL5, con l'aiuto del quale è possibile ottenere facilmente il codice dell'Expert Advisor già pronto utilizzando i moduli dei segnali di trading, che a loro volta sono stati creati sulla base di indicatori popolari, senza alcuna conoscenza del linguaggio di programmazione. Con l'aiuto di MQL5 Wizard, è possibile costruire rapidamente un Expert Advisor e testare la vostra strategia, se è basata solo su indicatori. Ecco il link all'articolo sulla costruzione di un robot di trading utilizzando MQL5 Wizard: https://www.mql5.com/ru/articles/171.

Sinceramente, Vladimir.

Мастер MQL5: Создание эксперта без программирования
Мастер MQL5: Создание эксперта без программирования
  • www.mql5.com
При создании автоматических торговых систем возникает необходимость написания алгоритмов анализа рыночной ситуации и генерации торговых сигналов, алгоритмов сопровождения открытых позиций, систем управления капиталом и контроля риска торговли. После того как код модулей написан самой сложной задачей является компоновка всех частей и отладка...
 
MrBrooklin:

57 e un po'. E la risposta alla tua domanda sul modo è già nota, e cito:

"Roman Zhilin:

No, non c'è un processo nel freelance, che puoi sviluppare da solo secondo le tue necessità. E l'unico da biasimare per i miei errori sarò io, non un programmatore terzo. Quindi, dovrete imparare, imparare, codificare, inciampare, migliorare le vostre strategie e imparare di nuovo".

Sinceramente, Vladimir.

Una buona selezione, grazie.

Mi ricorda il testamento di Lenin :) Ma è giusto, non è mai troppo tardi per imparare.

Per capire di che tipo di Expert Advisor avete bisogno, dovreste iniziare a lavorarci in primo luogo.

 

Aggiunti altri due pulsanti per chiudere una posizione

//+------------------------------------------------------------------+
//|                                                         0002.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#define    InpMagic  182979245
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position; // trade position object
CTrade         m_trade;    // trading object
CSymbolInfo    m_symbol;   // symbol info object
//---
input double InpLots          =0.01; // Lots
//---
double m_adjusted_point;   // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return(INIT_FAILED);;
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- 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;
//---
   m_trade.SetDeviationInPoints(3*digits_adjust);
   if(!m_position.Select(Symbol()))
     {
      CheckObject();
      CheckObjectClose();
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(ObjectFind(0,"BUY")==0)
     {
      ObjectDelete(0,"BUY");
     }
   if(ObjectFind(0,"SELL")==0)
     {
      ObjectDelete(0,"SELL");
     }
//---
   if(ObjectFind(0,"Close BUY")==0)
     {
      ObjectDelete(0,"Close BUY");
     }
   if(ObjectFind(0,"Close SELL")==0)
     {
      ObjectDelete(0,"Close SELL");
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   CheckButon();
   CheckButonClose();
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButon(void)
  {
//---
   bool res=false;
     {
      if(ObjectGetInteger(0,"BUY",OBJPROP_STATE)!=0)
        {
         ObjectSetInteger(0,"BUY",OBJPROP_STATE,0);
         double price=m_symbol.Ask();
           {
            //--- open position
            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,InpLots,price,0.0,0.0))
               printf("Position by %s to be opened",m_symbol.Name());
            else
              {
               printf("Error opening BUY position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());
               printf("Open parameters : price=%f,TP=%f",price,0.0);
              }
            PlaySound("ok.wav");
           }
        }
      if(ObjectGetInteger(0,"SELL",OBJPROP_STATE)!=0)
        {
         ObjectSetInteger(0,"SELL",OBJPROP_STATE,0);
         double price0=m_symbol.Bid();
           {
            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,InpLots,price0,0.0,0.0))
               printf("Position by %s to be opened",m_symbol.Name());
            else
              {
               printf("Error opening SELL position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());
               printf("Open parameters : price=%f,TP=%f",price0,0.0);
              }
            PlaySound("ok.wav");
           }
        }
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObject(void)
  {
//---
   bool res=false;
     {
      ObjectCreate(0,"BUY",OBJ_BUTTON,0,0,0);
      ObjectSetInteger(0,"BUY",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-102);
      ObjectSetInteger(0,"BUY",OBJPROP_YDISTANCE,37);
      ObjectSetString(0,"BUY",OBJPROP_TEXT,"BUY");
      ObjectSetInteger(0,"BUY",OBJPROP_BGCOLOR,clrMediumSeaGreen);
      ObjectCreate(0,"SELL",OBJ_BUTTON,0,0,0);
      ObjectSetInteger(0,"SELL",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-50);
      ObjectSetInteger(0,"SELL",OBJPROP_YDISTANCE,37);
      ObjectSetString(0,"SELL",OBJPROP_TEXT,"SELL");
      ObjectSetInteger(0,"SELL",OBJPROP_BGCOLOR,clrDarkOrange);
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButonClose(void)
  {
//---
   bool res=false;
   double level;
     {
      if(ObjectGetInteger(0,"Close BUY",OBJPROP_STATE)!=0)
        {
         ObjectSetInteger(0,"Close BUY",OBJPROP_STATE,0);
         if(FreezeStopsLevels(level))
            ClosePositions(POSITION_TYPE_BUY,level);
         PlaySound("ok.wav");
        }
      if(ObjectGetInteger(0,"Close SELL",OBJPROP_STATE)!=0)
        {
         ObjectSetInteger(0,"Close SELL",OBJPROP_STATE,0);
         if(FreezeStopsLevels(level))
            ClosePositions(POSITION_TYPE_SELL,level);
         PlaySound("ok.wav");
        }
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObjectClose(void)
  {
//---
   bool res=false;
     {
      ObjectCreate(0,"Close BUY",OBJ_BUTTON,0,0,0);
      ObjectSetInteger(0,"Close BUY",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-102);
      ObjectSetInteger(0,"Close BUY",OBJPROP_YDISTANCE,57);
      ObjectSetString(0,"Close BUY",OBJPROP_TEXT,"Close BUY");
      ObjectSetInteger(0,"Close BUY",OBJPROP_BGCOLOR,clrTomato);
      ObjectCreate(0,"Close SELL",OBJ_BUTTON,0,0,0);
      ObjectSetInteger(0,"Close SELL",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-50);
      ObjectSetInteger(0,"Close SELL",OBJPROP_YDISTANCE,57);
      ObjectSetString(0,"Close SELL",OBJPROP_TEXT,"Close SELL");
      ObjectSetInteger(0,"Close SELL",OBJPROP_BGCOLOR,clrFireBrick);
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
bool FreezeStopsLevels(double &level)
  {
//--- check Freeze and Stops levels
   if(!RefreshRates() || !m_symbol.Refresh())
      return(false);
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();
   if(freeze_level==0.0)
      freeze_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();
   if(stop_level==0.0)
      stop_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;
   if(freeze_level<=0.0 || stop_level<=0.0)
      return(false);
   level=(freeze_level>stop_level)?freeze_level:stop_level;
   double spread=m_symbol.Spread()*m_adjusted_point;
   level=(level>spread)?level:spread;
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type,const double level)
  {
   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()==InpMagic*/)
            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()>=level) || m_position.TakeProfit()==0.0;
                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()==0.0;
                  if(take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  bool take_profit_level=(m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()==0.0;
                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()==0.0;
                  if(take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               PlaySound("ok.wav");
              }
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
File:
0002.mq5  11 kb
 
MrBrooklin:

... continuo a non capire il significato della frase costante che inizia con la parola"Returns".

Chi ritorna, a chi ritorna, dove ritorna, perché ritorna? Non riesco ancora a capirlo...

Forse posso spiegare.

Supponiamo che tu abbia un simbolo (simbolo, ad esempio EUR/USD) che sta oscillando sullo schermo e un programma/advisor/robot è in esecuzione nel terminale. Il robot sta eseguendo il codice che avete inserito. E questo codice ha queste stringhe:

           ... 
 
           if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;

           double OpenPrice = OrderOpenPrice(); 

	   ...
"orderSelect" è una funzione commerciale, seleziona un ordine già aperto per lavorare ulteriormente con esso.
//In questo esempio, se la selezione dell'ordine fallisce (...==false), l'ulteriore esecuzione della funzione " if " è interrotta dal comando "break".

Il prossimo. Abbiamo selezionato l'ordine usando la funzione OrderSelect trade. Ora ci lavoriamo, con un ordine specifico. Per semplicità, prenderemo la condizione di avere solo due ordini aperti.

Poi, inseriamo una variabile OpenPrice [tipo doppio] e gli assegniamo il valore del prezzo al quale l'ordine che abbiamo selezionato è stato aperto (sezione di codice OpenPrice=OrderOpenPrice(); )

QUI c'è una spiegazione per voi su cosa significa il RETURN di un parametro. La funzione OrderOpenPrice restituisce il valore del prezzo corrente dello strumento. Cioè, dopo che il programma ha richiesto il prezzo corrente al server, vi ha restituito il valore di quel prezzo e ha assegnato quel valore a una variabile.

 

Aggiunto indicatore MACD

 //+------------------------------------------------------------------+
//|                                                         0003.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property version    "1.00"
#define   InpMagic   182979245
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position; // trade position object
CTrade         m_trade;     // trading object
CSymbolInfo    m_symbol;   // symbol info object
//---
input double InpLots= 0.01 ; // Lots
//---
double    m_adjusted_point; // point value adjusted for 3 or 5 points
int       handle_iCustom;   // variable for storing the handle of the iStochastic indicator
datetime ExtPrevBars= 0 ;     // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
   if (!m_symbol.Name( Symbol ())) // sets symbol name
       return ( INIT_FAILED );;
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- 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;
//---
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
   if (!m_position.Select( Symbol ()))
     {
      CheckObject();
      CheckObjectClose();
     }
   handle_iCustom= iMACD (m_symbol.Name(), Period (), 12 , 26 , 9 , PRICE_CLOSE );
//--- 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 handle_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 deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   if ( ObjectFind ( 0 , "BUY" )== 0 )
     {
       ObjectDelete ( 0 , "BUY" );
     }
   if ( ObjectFind ( 0 , "SELL" )== 0 )
     {
       ObjectDelete ( 0 , "SELL" );
     }
//---
   if ( ObjectFind ( 0 , "Close BUY" )== 0 )
     {
       ObjectDelete ( 0 , "Close BUY" );
     }
   if ( ObjectFind ( 0 , "Close SELL" )== 0 )
     {
       ObjectDelete ( 0 , "Close SELL" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   CheckButon();
   CheckButonClose();
   if (SearchTradingSignals())
     {
       return ;
     }
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButon( void )
  {
//---
   bool res= false ;
     {
       if ( ObjectGetInteger ( 0 , "BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "BUY" , OBJPROP_STATE , 0 );
         double price=m_symbol.Ask();
           {
             //--- open position
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
       if ( ObjectGetInteger ( 0 , "SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "SELL" , OBJPROP_STATE , 0 );
         double price0=m_symbol.Bid();
           {
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price0, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price0, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObject( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "BUY" , OBJPROP_TEXT , "BUY" );
       ObjectSetInteger ( 0 , "BUY" , OBJPROP_BGCOLOR , clrMediumSeaGreen );
       ObjectCreate ( 0 , "SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_YDISTANCE , 37 );
       ObjectSetString ( 0 , "SELL" , OBJPROP_TEXT , "SELL" );
       ObjectSetInteger ( 0 , "SELL" , OBJPROP_BGCOLOR , clrDarkOrange );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckButonClose( void )
  {
//---
   bool res= false ;
   double level;
     {
       if ( ObjectGetInteger ( 0 , "Close BUY" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_BUY ,level);
         PlaySound ( "ok.wav" );
        }
       if ( ObjectGetInteger ( 0 , "Close SELL" , OBJPROP_STATE )!= 0 )
        {
         ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_STATE , 0 );
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_SELL ,level);
         PlaySound ( "ok.wav" );
        }
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool CheckObjectClose( void )
  {
//---
   bool res= false ;
     {
       ObjectCreate ( 0 , "Close BUY" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 102 );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close BUY" , OBJPROP_TEXT , "Close BUY" );
       ObjectSetInteger ( 0 , "Close BUY" , OBJPROP_BGCOLOR , clrTomato );
       ObjectCreate ( 0 , "Close SELL" , OBJ_BUTTON , 0 , 0 , 0 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_XDISTANCE , ChartGetInteger ( 0 , CHART_WIDTH_IN_PIXELS )- 50 );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_YDISTANCE , 57 );
       ObjectSetString ( 0 , "Close SELL" , OBJPROP_TEXT , "Close SELL" );
       ObjectSetInteger ( 0 , "Close SELL" , OBJPROP_BGCOLOR , clrFireBrick );
      res= true ;
     }
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
bool FreezeStopsLevels( double &level)
  {
//--- check Freeze and Stops levels
   if (!RefreshRates() || !m_symbol.Refresh())
       return ( false );
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol. Point ();
   if (freeze_level== 0.0 )
      freeze_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol. Point ();
   if (stop_level== 0.0 )
      stop_level=(m_symbol.Ask()-m_symbol.Bid())* 3.0 ;
   if (freeze_level<= 0.0 || stop_level<= 0.0 )
       return ( false );
   level=(freeze_level>stop_level)?freeze_level:stop_level;
   double spread=m_symbol.Spread()*m_adjusted_point;
   level=(level>spread)?level:spread;
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions( const ENUM_POSITION_TYPE pos_type, const double level)
  {
   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()==InpMagic*/ )
             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()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               if (m_position.PositionType()== POSITION_TYPE_SELL )
                 {
                   bool take_profit_level=(m_position.TakeProfit()!= 0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()== 0.0 ;
                   bool stop_loss_level=(m_position.StopLoss()!= 0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()== 0.0 ;
                   if (take_profit_level && stop_loss_level)
                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
                 }
               PlaySound ( "ok.wav" );
              }
  }
//+------------------------------------------------------------------+
//| 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 );
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignals( void )
  {
//--- we work only at the time of the birth of new bar
   datetime time_0= iTime (m_symbol.Name(), Period (), 0 );
   if (time_0==ExtPrevBars)
       return ( false );
   ExtPrevBars=time_0;
   if (!RefreshRates())
     {
      ExtPrevBars= 0 ;
       return ( false );
     }
//---
   double level;
   double main[],signal[];
   ArraySetAsSeries (main, true );
   ArraySetAsSeries (signal, true );
   int start_pos= 0 ,count= 3 ;
   if (!iGetArray(handle_iCustom, MAIN_LINE ,start_pos,count,main) ||
      !iGetArray(handle_iCustom, SIGNAL_LINE ,start_pos,count,signal))
     {
      ExtPrevBars= 0 ;
       return ( false );
     }
//--- check for long position (BUY) possibility
   if (main[ 0 ]< 0 )
       if (main[ 0 ]>signal[ 0 ] && main[ 1 ]<signal[ 1 ])
        {
         double price=m_symbol.Ask();
           {
             //--- open position
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_BUY ,InpLots,price, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening BUY position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_SELL ,level);
        }
//--- check for short position (SELL) possibility
   if (main[ 0 ]> 0 )
       if (main[ 0 ]<signal[ 0 ] && main[ 1 ]>signal[ 1 ])
        {
         double price0=m_symbol.Bid();
           {
             if (m_trade.PositionOpen(m_symbol.Name(), ORDER_TYPE_SELL ,InpLots,price0, 0.0 , 0.0 ))
               printf ( "Position by %s to be opened" ,m_symbol.Name());
             else
              {
               printf ( "Error opening SELL position by %s : '%s'" ,m_symbol.Name(),m_trade.ResultComment());
               printf ( "Open parameters : price=%f,TP=%f" ,price0, 0.0 );
              }
             PlaySound ( "ok.wav" );
           }
         if (FreezeStopsLevels(level))
            ClosePositions( POSITION_TYPE_BUY ,level);
        }
//---
   return ( true );
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
double iGetArray( const int handle, const int buffer, const int start_pos, const int count, double &arr_buffer[])
  {
   bool result= true ;
   if (! ArrayIsDynamic (arr_buffer))
     {
       Print ( "This a no dynamic array!" );
       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 ( "Failed to copy data from the indicator, error code %d" , GetLastError ());
       //--- quit with zero result - it means that the indicator is considered as not calculated
       return ( false );
     }
   return (result);
  }
//+------------------------------------------------------------------+
File:
0003.PNG  107 kb
0003.mq5  15 kb
 
SanAlex:

Aggiunto indicatore MACD

Le basi ci sono - ora dipende tutto da te

 
4elovechishe:

Potrei essere in grado di spiegare.

Diciamo che attualmente hai un simbolo (ad esempio EUR/USD) che fluttua sul tuo schermo e un programma/advisor/robot in esecuzione nel terminale. Il robot sta eseguendo il codice che avete inserito. E questo codice ha queste stringhe:

"orderSelect" è una funzione commerciale, seleziona un ordine già aperto per lavorare ulteriormente con esso.
//In questo esempio, se la selezione dell'ordine fallisce (...==false), l'ulteriore esecuzione della funzione " if " è interrotta dal comando "break".

Il prossimo. Abbiamo selezionato l'ordine usando la funzione OrderSelect trade. Ora ci lavoriamo, con un ordine specifico. Per semplicità, prenderemo la condizione di avere solo due ordini aperti.

Poi, inseriamo una variabile OpenPrice [tipo doppio] e gli assegniamo il valore del prezzo al quale l'ordine che abbiamo selezionato è stato aperto (sezione di codice OpenPrice=OrderOpenPrice(); )

QUI c'è una spiegazione per voi su cosa significa il RETURN di un parametro. La funzione OrderOpenPrice restituisce il valore del prezzo corrente dello strumento. Cioè, dopo che il programma ha richiesto il prezzo corrente al server, vi ha restituito il valore di quel prezzo e lo ha assegnato a una variabile.

Grazie per il suo chiarimento. Spero che aiuterà anche Roman nell'apprendimento del linguaggio di programmazione.

Saluti, Vladimir.

 

Ciao! Beh, forse qualcuno può aiutare anche me...

Attualmente mi sto occupando dei meccanismi di apertura/chiusura degli ordini e mi sono imbattuto in un problema con la chiusura delle posizioni aperte.

Il codice è semplice. L'idea dell'algoritmo è di disegnare la MA (media mobile) con un periodo di 100 sul grafico. Se la candela precedente [1] si è aperta sopra la MA, e ha chiuso sotto la MA, allora la candela successiva [0] apre un ordine SELLper vendere.

//(Le condizioni di acquisto sono invertite, non le spiego)

Per la chiusura dell'ordine le seguenti condizioni - il prezzo corrente ha superato dal prezzo di apertura dell'ordine il valore impostato di punti, per esempio 40.

Esempio: un lotto è aperto a Bid= 1.20045, dovrebbe chiudere a Ask= 1.20005.

Il codice di apertura e chiusura è racchiuso in 2 funzioni corrispondenti che a loro volta sono chiamate con la funzione OnTick(). Infatti, ad ogni tick la condizione di chiusura dovrebbe essere controllata, ma in realtà il prezzo può scendere sotto il livello specificato (livello di chiusura) ma l'ordine non si chiude. Gli screenshot e il codice sono allegati.

 
4elovechishe:

Ciao! Beh, forse qualcuno può aiutare anche me...

Attualmente mi sto occupando dei meccanismi di apertura/chiusura degli ordini e mi sono imbattuto in un problema con la chiusura delle posizioni aperte.

Il codice è semplice. L'idea dell'algoritmo è di disegnare la MA (media mobile) con un periodo di 100 sul grafico. Se la candela precedente [1] si è aperta sopra la MA, e ha chiuso sotto la MA, allora la candela successiva [0] apre un ordine SELLper vendere.

//(Le condizioni di acquisto sono invertite, non le spiego)

Per la chiusura dell'ordine le seguenti condizioni - il prezzo corrente ha superato dal prezzo di apertura dell'ordine il valore impostato di punti, per esempio 40.

Esempio: un lotto è aperto a Bid= 1.20045, dovrebbe chiudere a Ask= 1.20005.

Il codice di apertura e chiusura è racchiuso in 2 funzioni corrispondenti che a loro volta sono chiamate con la funzione OnTick(). Infatti, ad ogni tick la condizione di chiusura dovrebbe essere controllata, ma in realtà il prezzo può scendere sotto il livello specificato (livello di chiusura) ma l'ordine non si chiude. Allego gli screenshot e il codice.

C'è un thread del forum su https://www.mql5.com/ru/forum/160683/page767#comment_10725713

Lì potresti ricevere aiuto più velocemente.

Sinceramente, Vladimir.

Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам
Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам
  • 2019.02.21
  • www.mql5.com
В этой ветке я хочу начать свою помощь тем, кто действительно хочет разобраться и научиться программированию на новом MQL4 и желает легко перейти н...
Motivazione: