Preguntas de los principiantes MQL5 MT5 MetaTrader 5 - página 1324

 
Alexey Viktorov:

Ayer me descargué este milagro para verlo... De repente me quedé sin internet. Después de una tormenta eléctrica tuve trabajos técnicos durante el resto del día. Así que decidí reescribirlo en MQL5 por ociosidad y lo publiqué aquí.

Así que todas las nubes tienen un forro de plata.........

He añadido un indicador a su Asesor Experto - ¡creo que no le importará! Creo que ha funcionado como Sprut quería 185

(en amarillo lo añadí a mi Asesor Experto existente aquí).

//+------------------------------------------------------------------+
//|                                                 2 DVA_Martin.mq5 |
//|                                          © 2021, Alexey Viktorov |
//|                     https://www.mql5.com/ru/users/alexeyvik/news |
//+------------------------------------------------------------------+
#property copyright "© 2021, Alexey Viktorov"
#property link      "https://www.mql5.com/ru/users/alexeyvik/news"
#property version   "2.00"
//---
#include <Trade\Trade.mqh>
CTrade trade;
//---
input int     TakeProfit1         = 300;  // профит первой позиции
input int     TakeProfit2         = 250;  // профит второй позиции
input int     TakeProfit3         = 200;  // профит третьей позиции
input int     TakeProfit4         = 100;  // профит четвертой и следующих позиций
input int     Step                = 200;  // шаг первой позиции
input int     Delta               = 100;  // добавка к шагу
// со второй позиции увеличивает расстояние последующих позиций на величину "дельта" от предыдущего
input double  Lot                 = 0.03; // первый лот открытия
input double  MaximalLot          = 0.5;  // максимальный лот, который мы разрешаем
input int     MaxTrades           = 9;    // максимальное количество позиций одного направления
input double  MultiplicatorLot    = 1.6;  // умножаем последующие позиции
input int     Magic               = 123;  // идентификатор советника
//--- Пременные для хранения собранной информации
double MaxLot  = 0;
double LotBuy  = 0;
double LotSell = 0;
//---
int m_bar_current=0;
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   trade.SetExpertMagicNumber(Magic);
   MaxLot = contractSize(MaximalLot);
//--- create StepMA_NRTR indicator
   StepMA_NRTR_Handle=iCustom(NULL,0,"StepMA_NRTR");
   if(StepMA_NRTR_Handle==INVALID_HANDLE)
     {
      printf("Error creating StepMA_NRTR indicator");
      return(false);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double StepMA_NRTR[],StepMA_NRTRS[];
   ArraySetAsSeries(StepMA_NRTR,true);
   ArraySetAsSeries(StepMA_NRTRS,true);
   int start_pos=1,count=3;
   if(!iGetArray(StepMA_NRTR_Handle,0,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle,1,start_pos,count,StepMA_NRTRS))
     {
      return;
     }
//---
   int posTotal = PositionsTotal();
   double BuyMinPrice = DBL_MAX, //  Минимальная цена Buy позиции
          SelMaxPrice = DBL_MIN, //  Максимальная цена Sell позиции
          BuyMinLot = 0,         //  Лот самой нижней Buy позиции
          SelMaxLot = 0,         //  Лое самой верхней Sell позиции
          posPrice = 0.0,
          posLot = 0.0,
          BuyAwerage = 0,
          SelAwerage = 0,
          BuyPrice = 0,
          SelPrice = 0,
          BuyLot = 0,
          SelLot = 0;
   MqlTick tick;
   if(!SymbolInfoTick(_Symbol, tick))
      return;
   int b = 0,
       s = 0;
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         posPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         posLot = PositionGetDouble(POSITION_VOLUME);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            b++; // Считаем открытые позиции на покупку
            if(posPrice < BuyMinPrice)
              {
               BuyMinPrice = posPrice;
               BuyMinLot = posLot;
               BuyPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               BuyLot += posLot;             // суммируем лоты
              }
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            s++; // Считаем открытые позиции на продажу
            if(posPrice > SelMaxPrice)
              {
               SelMaxPrice = posPrice;
               SelMaxLot = posLot;
               SelPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               SelLot += posLot;             // суммируем лоты
              }
           }
        }
     }
   LotBuy = b == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(BuyMinLot*MultiplicatorLot));
   LotSell = s == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(SelMaxLot*MultiplicatorLot));
//---
//--- BUY Signal
   if(StepMA_NRTR[m_bar_current]<StepMA_NRTRS[m_bar_current])
     {
      if(b == 0 || (b < MaxTrades && BuyMinPrice-tick.ask >= (Step+Delta*b)*_Point))
         openPos(ORDER_TYPE_BUY, LotBuy, tick.ask);
     }
//--- SELL Signal
   if(StepMA_NRTR[m_bar_current]>StepMA_NRTRS[m_bar_current])
     {
      if(s == 0 || (s < MaxTrades && tick.bid-SelMaxPrice >= (Step+Delta*s)*_Point))
         openPos(ORDER_TYPE_SELL, LotSell, tick.bid);
     }
//--- посчитаем математические формулы средних цен
   switch(b)
     {
      case 0 :
         return;
      case 1 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 2 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 3 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit3*_Point;
         break;
      default:
         BuyAwerage = BuyPrice/BuyLot+TakeProfit4*_Point;
         break;
     }
   switch(s)
     {
      case 0 :
         return;
      case 1 :
         SelAwerage = SelPrice/SelLot-TakeProfit1*_Point;
         break;
      case 2 :
         SelAwerage = SelPrice/SelLot-TakeProfit2*_Point;
         break;
      case 3 :
         SelAwerage = SelPrice/SelLot-TakeProfit3*_Point;
         break;
      default:
         SelAwerage = SelPrice/SelLot-TakeProfit4*_Point;
         break;
     }
   normalizePrice(BuyAwerage); // Произведем расчет цены TP Buy
   normalizePrice(SelAwerage); // Произведем расчет цены TP Sell
//---
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         double posTP = PositionGetDouble(POSITION_TP);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            if(fabs(posTP-BuyAwerage) > _Point && tick.ask < BuyAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, BuyAwerage))
                  Print("Ошибка ", __LINE__);
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            if(fabs(posTP-SelAwerage) > _Point && tick.bid > SelAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, SelAwerage))
                  Print("Ошибка ", __LINE__);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void openPos(ENUM_ORDER_TYPE type, double lot, double price)
  {
   trade.CheckVolume(_Symbol, lot, price, type);
   if(trade.CheckResultMarginFree() <= 0.0)
     {
      Print("Not enough money for ", EnumToString(type), " ", lot, " ", _Symbol, " Error code=", trade.CheckResultRetcode());
      return;
     }
   if(!trade.PositionOpen(_Symbol, type, LotBuy, price, 0.0, 0.0))
      Print(trade.ResultRetcode());
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double contractSize(double volume, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double v = volume;
   double volumeStep = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
   v = round(volume/volumeStep)*volumeStep;
   double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
   return((v < minLot ? minLot : v));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double normalizePrice(double &price, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
   price = round(price/tickSize)*tickSize;
   return(tickSize);
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+

Советники: DVA_Martin
Советники: DVA_Martin
  • 2021.06.30
  • www.mql5.com
Статьи и техническая библиотека по автоматическому трейдингу: Советники: DVA_Martin
 
SanAlex:

He añadido un indicador a su Asesor Experto - creo que no le importará!? parece que funciona como Sprut quería 185

(en amarillo lo añadí a mi Asesor Experto existente aquí).

¿Y por qué los valores del indicador de tres barras? ¿Y por qué cambiar la matriz a series temporales?

En general, me parece que no es el adecuado... Ningún martín funcionará.

 
Alexey Viktorov:

¿Por qué necesitas los valores del indicador de tres barras? ¿Y por qué cambiar la matriz a series temporales?

En general, me parece que este no es el caso... Ningún martin funcionará.

El indicador aquí es sólo un filtro de dirección - y su Asesor Experto hace toda la tarea

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

El indicador en sí no abre posiciones.

 
SanAlex:

El indicador aquí es sólo un filtro direccional - y su experto hace toda la tarea

El código escrito debe hacer la tarea. Pero has puesto una condición tal que el martin nunca se encenderá. Creo que sí, pero no tengo ganas ni tiempo de comprobarlo.

 
Alexey Viktorov:

La tarea debe ser realizada por el código que has escrito. Pero has puesto como condición que el martin no se encienda nunca. Creo que sí, pero no tengo ganas ni tiempo de comprobarlo.

Aquí estoy comprobando su funcionamiento - todo funciona como está previsto.

2 DVA_Martin

 
Alexey Viktorov:

¿Debe Martin activarse sólo cuando la señal del indicador es contraria o independientemente?

Ejemplo: Se abrió una posición de compra según el indicador. El precio ha caído por la distancia establecida y el indicador ya muestra Venta. ¿Debe abrirse la posición de compra?

Como prometí, he hecho un poco de photoshop.

1

Si no está claro, sólo podré explicar el significado de mi idea si hablo con usted en persona

 
SanAlex:

Algo hice mal aquí: no sé qué pasó de 100.000 rublos a dos millones.

cambió el Indicador y 5min Euro\bucks en 15 días a un millón.

LeMan_BrainTrend1Sig 2

LeMan_BrainTrend1Sig

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

añadido al Asesor Experto - para cerrar el beneficio (de todos los pares) y eliminar el Asesor Experto

input group  "---- : Parameters:  ----"
input int    TargetProfit     = 1000000; // : Balance + Profit(add to balance)
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//---
   if(AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      AllClose();
      ExpertRemove();
     }
//---

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

Necesito estos 2 indicadores (los nombres de los indicadores no deben cambiar)

Archivos adjuntos:
 
SanAlex:

cambió el Indicador y 5min euro\bucks en 15 días a un millón.

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

añadido en Expert Advisor - para cerrar el beneficio por el beneficio total (de todos los pares) y eliminar Expert Advisor

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

Necesito que estos 2 indicadores estén presentes (es decir, los nombres de los indicadores no cambiarían)

No hay suficiente stoploss en la configuración

 

Hay formas de dividir una cadena en cadenas utilizando un método como \n".

¿Hay alguna forma de dividir una variable de cadena en una sola cadena?

Es decir, escribir todos los textos, valores, parámetros, etc., que están disponibles en esta variable de cadena en una sola cadena.

El problema se produjo al escribir en csv (los valores de las variables de cadena se escriben en un montón de cadenas).

 
Vitaly Muzichenko:

No hay suficiente stoploss en la configuración

con Stop Loss ya no es el mismo beneficio

Stop Loss

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

Creo que sólo necesitas reiniciar el Asesor Experto más a menudo - por ejemplo, tomé el beneficio total (de todos los pares) para la semana y borré el Asesor Experto de todos los pares.

y reiniciar el EA hasta obtener un nuevo beneficio total de todos los pares.

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

otra idea sobre el stop - parar no para cerrar la posición sino para abrir una posición opuesta con muchas posiciones abiertas opuestas (perdedoras)

aquí hay un recuento de las posiciones abiertas en los lotes

   int total=PositionsTotal();
   for(int i=total-1; i>=0; i--) // returns the number of open positions
     {
      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol позиции
      if(position_GetSymbol==m_symbol.Name())
        {
         if(m_position.PositionType()==POSITION_TYPE_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);
            PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);
           }
         else
           {
            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);
            PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);
           }
           {
            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);
           }
        }
     }
//---

Stop Loss 777

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

La razón es que el stop no cierra la posición y el lote opuesto debería ayudar en el trading manual.

Razón de la queja: