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

 
Andy Dufresne:

Ciao, puoi spiegare a un babbeo come inizializzare un array di strutture? Per un array normale, è semplice

int HiddenFunc[3,2] = {1,2,3,4,5,6};

Ma che dire della serie di strutture? Inizializzare un array con questa struttura, per esempio

struct MODE_KEY {stringa Key; bool Act;};

proprio come le classi:
https://www.mql5.com/ru/docs/basis/types/classes


o array)

struct trade_settings
  {
   double take;         // значения цены фиксации прибыли
   double stop;         // значение цены защитного стопа
   uchar  slippage;     // значение допустимого проскальзывания
  };



   trade_settings ss[]={
                        {1.0, 2.0, 5},
                        {1.0, 2.0, 5},
                        {1.0, 2.0, 5}
                        };  
Документация по MQL5: Основы языка / Типы данных / Структуры, классы и интерфейсы
Документация по MQL5: Основы языка / Типы данных / Структуры, классы и интерфейсы
  • www.mql5.com
Структуры, классы и интерфейсы - Типы данных - Основы языка - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Salve.

test dei gufi. (il codice è allegato qui sotto).

owl usa una martingala basata sulla storia degli ordini precedenti (se in perdita, allora moltiplica il lotto per il coefficiente martin...).

l'ordine precedente è stato chiuso da uno stop con ad esempio 0,2 lotti a (Martin = 2...). poi spengo "auto-trading" nel terminale MT4, o spengo completamente il terminale e il gufo smette di fare trading.

Poi quando accendo il pulsante "auto-trading" - Poi il gufo si accende e apre il lotto successivo con un volume di 0,4.

Quindi, come correggere il codice, in modo che quando si disattiva "auto-trading", si spegne il terminale e poi lo si accende, il gufo inizia la prossima sessione di trading con il lotto di partenza,

specificato nelle impostazioni (ad esempio 0,01) invece di moltiplicare l'ultimo chiuso nella cronologia?

//+------------------------------------------------------------------+
#property copyright "Copyright © 2018, http://cmillion.ru"
#property link      "cmillion@narod.ru"
#property strict
#property description "Советник открывает позиции по индикатору RSI после SL увеличивает лот"
#property description "Следующая сделка не открывается, пока не закрыта предыдущая"
//-------------------------------------------------------------------
extern ENUM_TIMEFRAMES timeframe_RSI = 60;
extern int    period_RSI   = 14;
extern int    level_buy    = 30;
extern int    level_sell   = 70;

extern double Lot          = 0.1;
extern double K_Martin     = 2.0;

extern int    Stoploss     = 10,
              Takeprofit   = 50;
extern int    OrdersClose  = 5;

extern int    Magic        = 0;
extern int    DigitsLot    = 2;
extern int    slippage     = 3;
//-------------------------------------------------------------------
string AC;
datetime OpenTime;
double MINLOT,MAXLOT;
//-------------------------------------------------------------------
void OnTick()
{
   if (!IsTradeAllowed()) 
   {
      DrawLABEL("Торговля",0,0,0,Red,"Торговля запрещена");
      return;
   } 
   else DrawLABEL("Торговля",0,0,0,Lime,"Торговля разрешена");

   //---

   double STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);
   //---
   double OSL,OTP,OOP,SL,TP,Profit=0;
   int b=0,s=0,tip;
   for (int i=0; i<OrdersTotal(); i++)
   {    
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      { 
         if (OrderSymbol()==Symbol() && Magic==OrderMagicNumber())
         { 
            tip = OrderType(); 
            OSL = NormalizeDouble(OrderStopLoss(),Digits);
            OTP = NormalizeDouble(OrderTakeProfit(),Digits);
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            SL=OSL;TP=OTP;
            Profit+=OrderProfit()+OrderCommission()+OrderSwap();
            if (tip==OP_BUY)             
            {  
               b++; 
               if (OSL==0 && Stoploss!=0)
               {
                  if ((Bid-NormalizeDouble(OOP - Stoploss * Point,Digits)) / Point>=STOPLEVEL) SL = NormalizeDouble(OOP - Stoploss * Point,Digits);
               } 
               if (OTP==0 && Takeprofit!=0)
               {
                  if ((NormalizeDouble(OOP + Takeprofit * Point,Digits)-Ask) / Point>=STOPLEVEL) TP = NormalizeDouble(OOP + Takeprofit * Point,Digits);
               } 
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            }                                         
            if (tip==OP_SELL)        
            {
               s++;
               if (OSL==0 && Stoploss!=0)
               {
                  if ((NormalizeDouble(OOP + Stoploss * Point,Digits)-Ask) / Point>=STOPLEVEL) SL = NormalizeDouble(OOP + Stoploss   * Point,Digits);
               }
               if (OTP==0 && Takeprofit!=0)
               {
                  if ((Bid-NormalizeDouble(OOP - Takeprofit * Point,Digits)) / Point>=STOPLEVEL) TP = NormalizeDouble(OOP - Takeprofit * Point,Digits);
               }
               if (SL != OSL || TP != OTP)
               {  
                  if (!OrderModify(OrderTicket(),OOP,SL,TP,0,White)) Print("Error OrderModify ",GetLastError());
               }
            } 
         }
      }
   }
   
   
   //---
   
   double AB = AccountBalance();
   
   //---
   
   DrawLABEL("Balance"        ,1,5,0,clrGreen,StringConcatenate("Balance ",DoubleToStr(AB,2),AC));
   DrawLABEL("Equity"         ,1,5,0,clrGreen,StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2),AC));
   DrawLABEL("FreeMargin"     ,1,5,0,clrGreen,StringConcatenate("FreeMargin ",DoubleToStr(AccountFreeMargin(),2),AC));
   DrawLABEL("Take"           ,1,5,0,Color(Profit>0,Lime,Red),StringConcatenate("Profit ",DoubleToStr(Profit,2),AC));
   
   double Lots=0,RSI1=0,RSI0=0;
   if (b+s==0)
   {
      RSI0= iRSI (NULL,timeframe_RSI,period_RSI,PRICE_CLOSE,0);
      RSI1= iRSI (NULL,timeframe_RSI,period_RSI,PRICE_CLOSE,1);
   }
   else return;

   //---
   if (RSI0>=level_buy && RSI1<=level_buy)
   {
      Lots=LOT();

      if (Lots>MAXLOT) Lots = MAXLOT;
      if (Lots<MINLOT) Lots = MINLOT;
      
      if(SendOrder(OP_BUY, Lots, NormalizeDouble(Ask,Digits)))OpenTime=iTime(NULL,timeframe_RSI,1); 
   }

   //---
   
   if (RSI0<=level_sell && RSI1>=level_sell)
   {
      Lots=LOT();

      if (Lots>MAXLOT) Lots = MAXLOT;
      if (Lots<MINLOT) Lots = MINLOT;

      if(SendOrder(OP_SELL, Lots, NormalizeDouble(Bid,Digits))) OpenTime=iTime(NULL,timeframe_RSI,1); 
   }
}
//------------------------------------------------------------------
bool SendOrder(int tip, double lots, double price, double sl=0, double tp=0)
{
   if (tip<2)
   {
      if (AccountFreeMarginCheck(Symbol(),tip,lots)<0)
      {
         Alert("Недостаточно средств");
         return(0);
      }
   }
   for (int i=0; i<10; i++)
   {    
      if (OrderSend(Symbol(),tip, lots,price,slippage,sl,tp,NULL,Magic,0,clrNONE)!=-1) return(1);
         Alert(" попытка ",i," Ошибка открытия ордера ",Strtip(tip)," <<",(GetLastError()),">>  lot=",lots,"  pr=",price," sl=",sl," tp=",tp);
      Sleep(500);
      RefreshRates();
      if (IsStopped()) return(0);
   }
   return(0);
}
//------------------------------------------------------------------
string Strtip(int tip)
{
   switch(tip) 
   { 
   case OP_BUY:
      return("BUY"); 
   case OP_SELL:
      return("SELL"); 
   case OP_BUYSTOP:
      return("BUYSTOP"); 
   case OP_SELLSTOP:
      return("SELLSTOP"); 
   case OP_BUYLIMIT:
      return("BUYLIMIT"); 
   case OP_SELLLIMIT:
      return("SELLLIMIT"); 
   }
   return("error"); 
}
//------------------------------------------------------------------
void OnDeinit(const int reason)
{
   if (!IsTesting()) 
   {
      ObjectsDeleteAll(0);
   }
}
//-------------------------------------------------------------------
void DrawLABEL(string name, int CORNER, int X, int Y, color clr, string Name)
{
   if (ObjectFind(name)==-1)
   {
      ObjectCreate(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);
}
//+------------------------------------------------------------------+
int OnInit()
{
   MINLOT = MarketInfo(Symbol(),MODE_MINLOT);
   MAXLOT = MarketInfo(Symbol(),MODE_MAXLOT);
   Comment("Start ",TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS));
   
   AC = StringConcatenate(" ", AccountCurrency());
   
   int Y=15;
   DrawLABEL("Торговля"  ,1,5,Y,Red,"Торговля ");Y += 20;
   DrawLABEL("Balance"   ,1,5,Y,clrGreen,StringConcatenate("Balance ",DoubleToStr(AccountBalance(),2),AC));Y += 15;
   DrawLABEL("Equity"    ,1,5,Y,clrGreen,StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2),AC));Y += 15;
   DrawLABEL("FreeMargin",1,5,Y,clrGreen,StringConcatenate("FreeMargin ",DoubleToStr(AccountFreeMargin(),2),AC));Y += 30;

   DrawLABEL("Take"           ,1,5,Y,Lime,"Profit ");Y += 20;
   
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
color Color(bool P,color a,color b)
{
   if (P) return(a);
   else return(b);
}
//------------------------------------------------------------------
double LOT()
{
   int n=0;
   double OL=Lot;
   for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
   {
      if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
         {
            if (OrderProfit()<0) 
            {
               if (n==0) OL=NormalizeDouble(OrderLots()*K_Martin,DigitsLot);
               n++;
               if (n>=OrdersClose) {Comment("1");return(Lot);}
            }
            else
            {
               if (n==0) {Comment("2");return(Lot);}
               else {Comment("3");return(OL);}
            }
         }
      }
   }
   return(OL);
}
//------------------------------------------------------------------


Программные помощники MQL для работы на финансовых рынках
  • cmillion.ru
Скрипт показывает максимальную и минимальную корреляцию на выбранном отрезке истории, например за последние 10000 свечей. Таким образом можно заранее проанализировать какие пары и как коррелируют. В параметрах задаем Тф период корреляции и период анализа корреляции. Зеленым цветом выделяются пары с прямой корреляцией у которых корреляция выше...
 
законопослушный гражданин:

Salve.

test dei gufi. (il codice è allegato qui sotto).

owl usa una martingala basata sulla storia degli ordini precedenti (se in perdita, allora moltiplica il lotto per il coefficiente martin...).

l'ordine precedente è stato chiuso da uno stop con ad esempio 0,2 lotti a (martin =2...) poi spengo "auto-trading" nel terminale MT4 o spengo completamente il terminale e il gufo smette di fare trading.

Poi quando accendo il pulsante "auto-trading" - Poi il gufo si accende e apre il lotto successivo con un volume di 0,4.

Quindi, come correggere il codice, in modo che quando si disattiva "auto-trading", si spegne il terminale e poi lo si accende, il gufo inizia la prossima sessione di trading con il lotto di partenza,

specificato nelle impostazioni (ad esempio 0,01) invece di moltiplicare l'ultimo chiuso nella cronologia?

Si crea una variabile globale

datetime Start;

int OnInit()
{
   Start=TimeCurrent();
.....................
}
void OnTick()
{
   if (!IsTradeAllowed()) 
   {
      DrawLABEL("Торговля",0,0,0,Red,"Торговля запрещена");
      Start=TimeCurrent();
      return;
   } 
.....................
}

e poi se non ci sono ordini aperti/chiusi dopo "Inizia"

Lots=Lot;
 
MakarFX:

Si crea una variabile globale

e poi se non ci sono ordini aperti/chiusi più tardi "Inizia".

Grazie.

Ho già un datetime OpenTime; - dovrebbe essere sostituito condatetime Start o in aggiunta?

"Se non ci sono ordini aperti/chiusi dopo "Start "Lots=Lot; " - non è affatto chiaro cosa farne?

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

Grazie.

Ho già datetime OpenTime; - dovrebbe essere sostituito condatetime Start o in aggiunta?

"e poi se non ci sono ordini aperti/chiusi più tardi "Start "Lots=Lot; " - non è affatto chiaro a cosa fare riferimento?

Descrivi in poche parole cosa vuoi da questo EA (la logica del suo lavoro),

Penso che tu abbia molte cose inutili nel tuo codice o che io non capisca qualcosa.

 
Per aggiungere un indicatore quando gli si passa un altro indicatore (come applied_price) quest'altro deve avere solo un buffer? O è possibile avere diversi buffer? Se ce n'è più di uno, in questo caso il primo prende i dati solo dal buffer zero del secondo indicatore?
 

Buon pomeriggio. Aiuto con l'EA. Secondo la strategia, se uno stop è scattato, allora l'EA dovrebbe aggiungere (il numero di punti) al prossimo set takeaway
dalla storia per ID, ma non lo fa per qualche motivo.

Cosa c'è di sbagliato nel codice?

if(isLimitOn && OrderSelect(OrderMagicNumber(), SELECT_BY_TICKET, MODE_HISTORY)){
            tpc += stop_loss;
            if(OrderSelect(lastMagic, SELECT_BY_TICKET)){
               if(OrderType() == OP_BUY) {
                  double tp_price = NormalizeDouble((OrderOpenPrice() + Point() * (tp + tpc)), Digits);
                  if(!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), tp_price, OrderExpiration()))
                     Print("Ошибка модификации ордера:", GetLastError());
               }else if(OrderType() == OP_SELL){
                  double tp_price = NormalizeDouble((OrderOpenPrice() - Point() * (tp + tpc)), Digits);
                  if(!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), tp_price, OrderExpiration()))
                     Print("Ошибка модификации ордера:", GetLastError());
               }
            }
               
            isLimitOn = false;
         }
 
SGarnov:

Buon pomeriggio. Aiuto con l'EA. Secondo la strategia, se uno stop è scattato, allora l'EA dovrebbe aggiungere (il numero di punti) al prossimo set takeaway
dalla storia per ID, ma non lo fa per qualche motivo.

Cosa c'è di sbagliato nel codice?

non è chiaro che si tratta di "OrderMagicNumber()" e di "stop_loss
 
verificato?
 
Salve, ho bisogno di un consulente. Dove posso trovarne uno affidabile?