Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 1543

 
Andy Dufresne:

Hola, ¿podríais explicarle a un pringado cómo se inicializa un array de estructuras? Para una matriz normal, es sencillo

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

¿Pero qué pasa con el conjunto de estructuras? Inicializar un array con esta estructura, por ejemplo

struct MODE_KEY {secuencia Key; bool Act;};

al igual que las clases:
https://www.mql5.com/ru/docs/basis/types/classes


o matrices)

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
 

Hola.

probando búhos. (el código se adjunta a continuación).

owl utiliza la martingala basada en el historial de órdenes anteriores (si hay pérdidas, entonces multiplica el lote por el coeficiente martin...).

la orden anterior se cerró con un stop con, por ejemplo, 0,2 lotes en (Martin = 2...). entonces desactivo el "auto-trading" en el terminal MT4, o apago el terminal completamente y el búho deja de operar.

Entonces, cuando conecto el botón "auto-trading" - A continuación, el búho se enciende y abre el siguiente lote con un volumen de 0,4.

Entonces, cómo corregir el código, para que al desactivar el "auto-trading", apagar el terminal y luego encenderlo, el búho inicie la siguiente sesión de trading con el lote inicial,

especificado en los ajustes (por ejemplo, 0,01) en lugar de multiplicar el último cerrado en el historial?

//+------------------------------------------------------------------+
#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 свечей. Таким образом можно заранее проанализировать какие пары и как коррелируют. В параметрах задаем Тф период корреляции и период анализа корреляции. Зеленым цветом выделяются пары с прямой корреляцией у которых корреляция выше...
 
законопослушный гражданин:

Hola.

Probando búhos. (el código se adjunta a continuación).

owl utiliza la martingala basada en el historial de órdenes anteriores (si hay pérdidas, entonces multiplica el lote por el coeficiente martin...).

la orden anterior se cerró con un stop con, por ejemplo, 0,2 lotes en (martin =2...) entonces desactivo el "auto-trading" en el terminal MT4 o apago el terminal completamente y el búho deja de operar.

Entonces, cuando conecto el botón "auto-trading" - A continuación, el búho se enciende y abre el siguiente lote con un volumen de 0,4.

Entonces, cómo corregir el código, para que al desactivar el "auto-trading", apagar el terminal y luego encenderlo, el búho inicie la siguiente sesión de trading con el lote inicial,

especificado en los ajustes (por ejemplo, 0,01) en lugar de multiplicar el último cerrado en el historial?

Se crea una variable global

datetime Start;

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

y luego, si no hay órdenes abiertas/cerradas, más tarde, "Inicio"

Lots=Lot;
 
MakarFX:

Se crea una variable global

y luego, si no hay órdenes abiertas/cerradas, más tarde, "Iniciar".

Gracias.

Ya tengo un datetime OpenTime; - ¿se debe reemplazar condatetime Start o además?

"Si no hay órdenes abiertas/cerradas más tarde de "Inicio "Lotes=Lote; " - no está nada claro qué hacer con él?

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

Gracias.

Ya tengo el datetime OpenTime; - ¿se debe reemplazar con eldatetime Start o además?

" y luego si no hay órdenes abiertas/cerradas más tarde "Inicio "Lotes=Lote; " - no está nada claro a donde referirse?

Describa en pocas palabras lo que quiere de este EA (la lógica de su trabajo),

Creo que tienes muchas cosas innecesarias en tu código o no entiendo algo.

 
¿Para añadir un indicador cuando se le pasa el mango de otro indicador (como applied_price) este otro debe tener un solo buffer? ¿O es posible tener varios buffers? Si hay más de uno, en este caso el primero toma los datos sólo del buffer cero del segundo indicador?
 

Buenas tardes. Ayuda con el EA. De acuerdo con la estrategia, si un stop se dispara, entonces el EA debería añadir (el número de puntos) a la siguiente toma establecida
del historial por ID, pero no lo hace por alguna razón.

¿Qué ocurre con el código?

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:

Buenas tardes. Ayuda con el EA. De acuerdo con la estrategia, si un stop se dispara, entonces el EA debería añadir (el número de puntos) a la siguiente toma establecida
del historial por ID, pero no lo hace por alguna razón.

¿Qué ocurre con el código?

no está claro que es "OrderMagicNumber()" y es "stop_loss"
 
¿Verificado?
 
Hola, necesito un asesor. ¿Dónde puedo conseguir uno de confianza?
Razón de la queja: