Tutte le domande dei nuovi arrivati su MQL4 e MQL5, aiuto e discussione su algoritmi e codici - pagina 1558

 
Alexey Viktorov:

Non c'è di che, ma non mi sembra di aver fatto nulla...

Qui
 
MakarFX:
Qui

Grazie, e poi ancheAlexey Viktorov!

Alexey Viktorov
Alexey Viktorov
  • 2021.06.30
  • www.mql5.com
Профиль трейдера
 
законопослушный гражданин :


Provalo

puoi modificare la funzione "Segnale per aprire un ordine".

 //+------------------------------------------------------------------+
//|                                                 Citizen.v2.1.mq4 |
//|                                           Copyright 2020, DrMak. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, DrMak."
#property link        " https://www.mql5.com "
#property version    "1.00"
#property strict
//--- input parameters
input ENUM_TIMEFRAMES    timeframe_RSI  = PERIOD_H1 ;
input int                period_RSI     = 14 ;
input int                level_buy      = 30 ;
input int                level_sell     = 70 ;
input double             Lot            = 0.1 ;   // Размер стартового лота
input double             K_Martin       = 2.0 ;   // Размер увеличения лота(Мартин) 
input int                Stoploss       = 100 ;   // Размер StopLoss в пунктах
input int                Takeprofit     = 500 ;   // Размер TakeProfit в пунктах
input double             CountLoss      = 200 ;   // Размер максимального убытка
input double             CountProfit    = 300 ;   // Размер минимального профита
input int                Magic          = 777 ;   // Магик
input int                DigitsLot      = 2 ;     // Шаг лота
input int                slippage       = 3 ;     // Проскальзывание
//---
string AC;
datetime Start;
double AB,MINLOT,MAXLOT,RSI1,RSI0,SL,TP,sl,tp;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- create timer
   ObjectsDeleteAll ( 0 , "lab_" );
   EventSetMillisecondTimer ( 500 );
   Start  = TimeCurrent ();
   MINLOT = MarketInfo( Symbol (),MODE_MINLOT);
   MAXLOT = MarketInfo( Symbol (),MODE_MAXLOT);
   AC     = StringConcatenate ( " " , AccountCurrency());
   AB     = AccountInfoDouble ( ACCOUNT_BALANCE );
   int Y= 20 ;
   CreateButton( 0 , "lab_Button" , 0 , 79 ,Y, 77 , 25 , CORNER_RIGHT_UPPER , "Советник остановлен" , "START" , "Arial Black" , 10 , clrWhite , clrGreen ,
   false , false , false , false , false , 0 );Y += 25 ;
   DrawLABEL( "lab_Торговля"    , 1 , 5 ,Y, clrRed , "Торговля " );Y += 20 ;
   DrawLABEL( "lab_Start Time" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));Y += 15 ;
   DrawLABEL( "lab_Current Lot" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));Y += 15 ;
   DrawLABEL( "lab_Balance"     , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AccountBalance(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_Equity"      , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_FreeMargin" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));Y += 30 ;
   DrawLABEL( "lab_Take"        , 1 , 5 ,Y, clrLime , "Profit: " );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//--- destroy timer
   EventKillTimer ();
   if (!IsTesting()) 
     {
       ObjectsDeleteAll ( 0 , "lab_" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   if (IsTesting()) 
     {
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
        }
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
         Start = iTime ( _Symbol , PERIOD_D1 , 0 );
        }
     }
   if (GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*- 1 )
     {
       if (IsTesting()) 
        {
         CloseOrder(); ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_STATE , false );
        }
       else
        {
         CloseOrder();
        }
     }
   // Обновляем текст на лейблах
   DrawLABEL( "lab_Start Time" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));
   DrawLABEL( "lab_Current Lot" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));
   DrawLABEL( "lab_Balance"     , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AB, 2 ),AC));
   DrawLABEL( "lab_Equity"      , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));
   DrawLABEL( "lab_FreeMargin" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));
   DrawLABEL( "lab_Take"        , 1 , 5 , 0 ,Color(GetProfitFromStart()> 0 ,Lime,Red), StringConcatenate ( "Profit: " ,DoubleToStr(GetProfitFromStart(), 2 ),AC));
   //---
   sl  = MathMax (Stoploss, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   SL  = NormalizeDouble (sl* Point (), Digits );
   tp  = MathMax (Takeprofit, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   TP  = NormalizeDouble (tp* Point (), Digits );
   //---
   if (CountOrders()== 0 && ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE ))
     {
       if (TradeSignal()>= 0 )
        {
         SendOrder(TradeSignal());
        }
     }
   //---
   if (!IsTradeAllowed()) 
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrRed , "Торговля запрещена" ); return ;} 
   else
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrLime , "Торговля разрешена" );}
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer ()
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Сигнал для открытия ордера                                       |
//+------------------------------------------------------------------+
int TradeSignal() 
  {
   int sig=- 1 ;
   // Здесь расчет сигнала
   RSI0= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 0 );
   RSI1= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 1 );
   // Здесь определение направления сигнала sig=0-BUY, sig=1-SELL
   if (RSI0>=level_buy && RSI1<=level_buy)   sig= 0 ;
   if (RSI0<=level_sell && RSI1>=level_sell) sig= 1 ;
   return (sig);
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent ( const int id,
                   const long &lparam,
                   const double &dparam,
                   const string &sparam)
  {
//---
   if (sparam== "lab_Button" ) TradeButton();
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| ButtonSTART                                                                                                        |
//+--------------------------------------------------------------------------------------------------------------------+
void TradeButton()
  {
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
     }
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
      Start = TimeCurrent ();
     }
  }
//+------------------------------------------------------------------+
//| Расчет лота                                                      |
//+------------------------------------------------------------------+
double Lots()
  {
   double L= 0 ;
   if (GetInfoLastPos( 3 )>Start && GetInfoLastPos( 2 )< 0 )
     {L= NormalizeDouble (GetInfoLastPos( 1 )*K_Martin,DigitsLot);}
   else
     {L=Lot;}
   
   if (L>MAXLOT) L = MAXLOT;
   if (L<MINLOT) L = MINLOT;
   return (L);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  размер профита с учетом комиссии и свопа с начала цикла                   |
//+----------------------------------------------------------------------------+
double GetProfitFromStart()
  {
   double lp= 0 ,cp= 0 ;
   for ( int i= 0 ; i<OrdersHistoryTotal(); i++)
     {
       if ( OrderSelect (i, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (Start<OrderCloseTime()) {lp+=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   for ( int pos= OrdersTotal ()- 1 ;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL) {cp=OrderProfit()+OrderCommission()+OrderSwap();}
           }
        }
     }
   return (lp+cp);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  1 - размер лота последней закрытой позиции                                |
//|  2 - размер профита с учетом комиссии и свопа последней закрытой позиции   |
//|  3 - время последней закрытой позиции                                      |
//+----------------------------------------------------------------------------+
double GetInfoLastPos( int a= 1 )
  {
   datetime t= 0 ;
   double result= 0 ,l= 0 ,p= 0 ,f= 0 ;
   int i=OrdersHistoryTotal();
   for ( int pos= 0 ; pos<i; pos++)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (t<OrderCloseTime()) {t=OrderCloseTime(); l=OrderLots(); p=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   if (a== 1 ) {result=l;} else
   if (a== 2 ) {result=p;} else
   if (a== 3 ) {result=( double )t;}
   else      {result= 0 ;}
   return (result);
  }
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров                                         |
//+------------------------------------------------------------------+
int CountOrders() 
  {
   int cnt= 0 ;
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol )
           {
             if (OrderMagicNumber()==Magic) cnt++;
           }
        }
     }
   return (cnt);
  }
//+------------------------------------------------------------------+
//| Открытие ордера                                                  |
//+------------------------------------------------------------------+
void SendOrder( int so= 0 ) 
  {
   if (so== 0 )
     {
       if ( OrderSend ( Symbol (),OP_BUY, Lots(),Ask,slippage,Ask-sl,Ask+tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Buy: " , _Symbol );} else { Print ( "Error Open Buy: " , _Symbol , " / " , GetLastError ());}
     }
   if (so== 1 )
     {
       if ( OrderSend ( Symbol (),OP_SELL, Lots(),Bid,slippage,Bid+sl,Bid-tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Sell: " , _Symbol );} else { Print ( "Error Open Sell: " , _Symbol , " / " , GetLastError ());}
     }
  }
//+------------------------------------------------------------------+
//| Закрытие открытого ордера                                        |
//+------------------------------------------------------------------+
void CloseOrder() 
  {
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Bid,slippage, clrBlue )) TradeButton();
              }
             if (OrderType()==OP_SELL)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Ask,slippage, clrRed )) TradeButton();
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Установка цвета                                                  |
//+------------------------------------------------------------------+
color Color( bool P, color a, color b)
  {
   if (P) return (a);
   else return (b);
  }
//+------------------------------------------------------------------+
//| Установка лейблов/текста                                         |
//+------------------------------------------------------------------+
void DrawLABEL( string name, int CORNER, int X, int Y, color clr, string Name)
  {
   if ( ObjectFind ( 0 ,name)!= 0 )
     {
       ObjectCreate ( 0 ,name, OBJ_LABEL , 0 , 0 , 0 );
      ObjectSet(name, OBJPROP_CORNER , CORNER);
      ObjectSet(name, OBJPROP_XDISTANCE , X);
      ObjectSet(name, OBJPROP_YDISTANCE , Y);
     }
   ObjectSetText(name,Name, 10 , "Arial" ,clr);
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| Создает кнопку                                                                                                     |
//+--------------------------------------------------------------------------------------------------------------------+
bool CreateButton( const long               chart_ID= 0 ,               // ID графика
                   const string             name= "Button" ,             // имя кнопки
                   const int                sub_window= 0 ,             // номер подокна
                   const int                x= 0 ,                       // координата по оси X
                   const int                y= 0 ,                       // координата по оси Y
                   const int                width= 50 ,                 // ширина кнопки
                   const int                height= 18 ,                 // высота кнопки
                   const int                corner= 0 ,                 // угол графика для привязки
                   const string             tool= "TOOLTIP" ,           // TOOLTIP
                   const string             text= "Button" ,             // текст
                   const string             font= "Arial" ,             // шрифт
                   const int                font_size= 10 ,             // размер шрифта
                   const color              clr= clrBlack ,             // цвет текста
                   const color              back_clr= C'236,233,216' ,   // цвет фона
                   const bool               state= false ,               // нажата/отжата
                   const bool               back= false ,               // на заднем плане
                   const bool               selection= false ,           // выделить для перемещений
                   const bool               selected= false ,           // выделить для перемещений
                   const bool               hidden= true ,               // скрыт в списке объектов
                   const long               z_order= 0 )                 // приоритет на нажатие мышью
  {
//--- сбросим значение ошибки
   ResetLastError ();
//--- создадим кнопку
   if (! ObjectCreate (chart_ID,name, OBJ_BUTTON ,sub_window, 0 , 0 ))
     {
       Print ( __FUNCTION__ , ": не удалось создать кнопку! Код ошибки = " , GetLastError ()); return ( false );
     }
   ObjectSetInteger (chart_ID,name, OBJPROP_XDISTANCE ,x);
   ObjectSetInteger (chart_ID,name, OBJPROP_YDISTANCE ,y);
   ObjectSetInteger (chart_ID,name, OBJPROP_XSIZE ,width);
   ObjectSetInteger (chart_ID,name, OBJPROP_YSIZE ,height);
   ObjectSetInteger (chart_ID,name, OBJPROP_CORNER ,corner);
   ObjectSetString (chart_ID,name, OBJPROP_TOOLTIP ,tool);
   ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text);
   ObjectSetString (chart_ID,name, OBJPROP_FONT ,font);
   ObjectSetInteger (chart_ID,name, OBJPROP_FONTSIZE ,font_size);
   ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BGCOLOR ,back_clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
   ObjectSetInteger (chart_ID,name, OBJPROP_STATE ,state);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selected);
   ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
   ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
 
MakarFX:

Prova,

è possibile modificare la funzione "Segnale per aprire l'ordine".

Wow, che codice enorme è diventato questo.

Grazie mille - lo proverò oggi stesso!

 

Professionisti, un consiglio... Ho fatto un bottone sul grafico.

) {
  if(id == CHARTEVENT_OBJECT_CLICK) {
    if(sparam == button.Name()) {
      Alert("Button \""+sparam+"\" clicked!"); // Вместо этого функция с кодом...
      button.State(0);
      ChartRedraw(0);
}}}

Cercando di fare in modo che quando viene premuto il pulsante invece di allertare, venga eseguito uno script chiamato K1, quando viene premuto di nuovo lo script viene cancellato, ma senza fortuna. Grazie.

 
Константин:

Professionisti, un consiglio... Ho fatto un bottone sul grafico.

Cercando di fare in modo che quando il pulsante viene premuto, invece di avvertire, venga eseguito uno script chiamato K1, quando viene premuto di nuovo lo script viene cancellato, ma senza fortuna. Grazie.

Meglio scrivere il codice dello script dove si trova il pulsante
 
MakarFX:

Prova,

la funzione "Segnale per aprire l'ordine" si può modificare

Ho provato i gufi nel tester e tutto funziona perfettamente.

ma ho un paio di domande:

1. come ho capito dai test, i gufi tengono traccia del profitto/perdita attuale secondo i parametri che gli sono stati specificati, e non fa alcuna differenza per lui il numero di compravendite perché ciò avvenga,

Voglio sapere se ho raggiunto il profitto/perdita specificato in una sola operazione o in tre operazioni consecutive?

2. Ho impostato l'Expert Advisor un drawdown di 25$, ma è fallito con un drawdown di 40$ su un lotto grande - è normale per un tester? Forse è impossibile eseguire il test alla massima velocità?

3. è possibile fare in modo che il tracciamento del profitto/perdita corrente venga resettato dopo ogni trade, indipendentemente dal segnale con cui è stato chiuso (tp/sl o dopo aver raggiunto un determinato profitto/perdita)?

 
законопослушный гражданин:

Ho provato i gufi nel tester e tutto funziona perfettamente.

Ma ho un paio di domande:

1. come ho capito dai test, i gufi tracciano il profitto/perdita attuale secondo i parametri specificati, e non fa alcuna differenza il numero di trade perché ciò avvenga,

Voglio sapere se ho raggiunto il profitto/perdita specificato in una sola operazione o in tre operazioni consecutive?

2. Ho impostato l'Expert Advisor un drawdown di 25$, ma è fallito con un drawdown di 40$ su un lotto grande - è normale per un tester? Forse è impossibile eseguire il test alla massima velocità?

3. è possibile fare in modo che il tracciamento del profitto/perdita corrente venga resettato dopo la chiusura di ogni affare, indipendentemente dal segnale con cui è stato chiuso (tp/sl o dopo aver raggiunto un determinato profitto/perdita in denaro )?

1) Ad alta velocità o se non su ticks nel tester, chiuderà al primo prezzo disponibile.

2) Avete un grande aumento in corso e con un grande lotto 1 punto può essere più del livello ammissibile.

3)Non capisco cosa vuoi, di cosa hai bisogno per tracciare se l'azzeramento dopo ogni trade?

 

Buon pomeriggio signori programmatori!!!

Per favore aiutate un principiante con una funzione.

La funzione conta il profitto totale per storia.

Il problema è che funziona per un broker e non vuole funzionare per un altro.

Funziona su Hercic ma non su RoboForex. Ho un conto ECN su RoboForex.

Non so quale sia il problema. Ecco il codice:

doppio ultima perdita()

{

int typ = -1,cnt = 0;

doppio lastloss = 0;

for(int i = OrdersHistoryTotal()-1; i>=0; i--)

{

if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))

{

if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)

{

if(cnt == 0) typ = OrderType();

if(cnt > 0 && OrderType()!= typ) break;

lastlos += OrderProfit() + + OrderSwap() + OrderCommission();

cnt++;

}

}

}

return(lastlos);

}

Документация по MQL5: Торговые функции / OrderSelect
Документация по MQL5: Торговые функции / OrderSelect
  • www.mql5.com
OrderSelect - Торговые функции - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Salve. Qualcuno conosce qualche libreria MQL gratuita per scrivere strutture di dati in un file e caricarle successivamente? Idealmente una libreria che lavora con il formato json, parserjson, ecc.