Escribiré un asesor gratuito de mql4 - página 13

 
oleg3791: el asesor dibujaba cuatro líneas en cinco clics del ratón en el gráfico

Líneas obligatorias en amarillo

#property strict

int      Количество;
datetime старый, новый=0;
double   старая, новая=0;

void OnInit()
{
  Количество=0;
  ObjectsDeleteAll(0, "Линия");
}

void OnChartEvent(const int     id,  // идентификатор события   
                  const long &x, const double &yy,
                  const string& s)
{
  if(id!=CHARTEVENT_CLICK) return;
  if(Количество>4){OnInit();return;}
  string name[5]={"","Линия_1","Линия_2","Линия_3","Линия_4"};
  int y=int(yy);
  int O;
  старый=новый; старая=новая;
  ChartXYToTimePrice(0,int(x),y,O,новый,новая); // xy ---> время,цену
  if(Количество>0)
  ObjectCreate(name[Количество],OBJ_TREND,0,старый,старая,новый,новая);
  ObjectSet(name[Количество],OBJPROP_RAY,false);
  ObjectSet(name[Количество],OBJPROP_COLOR,Gold);
  ObjectSet(name[Количество],OBJPROP_WIDTH,2);
  Количество++; 
}

void OnDeinit(const int причина)
{
  OnInit();
}
 
STARIJ:

Líneas amarillas necesarias

¡¡¡Gracias!!!
 
oleg3791:   ¡¡¡Gracias!!!

Ahora dime cómo obtener un beneficio aquí... ¿O es para construir un juego?

 

¡Hola a todos, podéis ayudarme a encontrar un error en el código del EA, creo que lo he mirado todo, parece que todo está escrito correctamente en el código, pero el programa no opera correctamente por alguna razón! La idea es la siguiente: El asesor tiene que buscar dos velas largas de la misma dirección (la longitud entre las velas es ajustable en el asesor, es decir, entre las dos velas mínimas o máximas, dependiendo de la dirección), si el precio en la dirección opuesta rompe el mínimo o el máximo de la última vela, un acuerdo debe abrirse (Ejemplo situaciones de imagen en el gráfico adjunto al archivo). El asesor debería abrir operaciones en cada situación adecuada, pero por alguna razón sólo abre operaciones en las ventanas de negociación entre días. Esta es la situación, que no es difícil de los programadores, por favor, ayuda, arreglar el error. El código de EA se encuentra a continuación, así como en el archivo adjunto.

//+-----------------------------------------------------------------------------------------------+
//|                                                                           Spacing_Candles.mq4 |
//|                                                                        Copyright 2017, Vladim |
//|                                                                            vk.com/id229534564 |
//|                                                                  Mail: Vladim120385@yandex.ru |
//+-----------------------------------------------------------------------------------------------+
#property copyright "Copyright 2017, Vladim"
#property link      "vk.com/id229534564"
#property version   "1.00"
#property strict

//--- параметры советника
extern string paramEA    = "";     // Parameters EA
extern double volume     = 0.01;   // Volume
extern double stopLoss   = 5;     // StopLoss
extern double takeProfit = 1.5;    // TakeProfit
extern double maxSpacing = 150;   // MaxSpacing
extern double minSpacing = 30;    // MinSpacing
extern double TrailingStop  = 0;   // TrailingStop
extern int    magic      = 127;    // Magic

//--- глобальные переменные
datetime newCandle;
int tip;

//+-----------------------------------------------------------------------------------------------+
int OnInit()
{
   
   return(INIT_SUCCEEDED);
}
//+-----------------------------------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   
}
//+-----------------------------------------------------------------------------------------------+
void OnTick()
{
   if(newCandle != Time[0]) FindPattern();
   newCandle = Time[0];
}
//+-----------------------------------------------------------------------------------------------+
void OpenOrder(int type)   // Откроем рыночный ордер
{
   if(type == OP_BUY)  if(OrderSend(_Symbol, OP_BUY,  volume, Ask, 0, 0, 0, "", magic, 0)) SetSLTP(OP_BUY);
   if(type == OP_SELL) if(OrderSend(_Symbol, OP_SELL, volume, Bid, 0, 0, 0, "", magic, 0)) SetSLTP(OP_SELL);
}
//+-----------------------------------------------------------------------------------------------+
void SetSLTP(int type)   // Установим стоп приказы
{
   double sl = 0;
   double tp = 0;
   
   if(type == OP_BUY)
      for(int i = 0; i < OrdersTotal(); i++)
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
            if(OrderSymbol() == _Symbol && OrderMagicNumber() == magic && OrderType() == OP_BUY && OrderStopLoss() == 0)
            {
               sl = NormalizeDouble(Low[1] - stopLoss * _Point, _Digits);
               tp = NormalizeDouble(OrderOpenPrice() + (OrderOpenPrice() - Low[1]) * takeProfit, Digits);
               if(OrderModify(OrderTicket(), OrderOpenPrice(), sl, tp, 0)) return;
            }
   if(type == OP_SELL)
      for(int i = 0; i < OrdersTotal(); i++)
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
            if(OrderSymbol() == _Symbol && OrderMagicNumber() == magic && OrderType() == OP_SELL && OrderStopLoss() == 0)
            {
               sl = NormalizeDouble(High[1] + stopLoss * _Point, _Digits);
               tp = NormalizeDouble(OrderOpenPrice() - (High[1] - OrderOpenPrice()) * takeProfit, Digits);
               if(OrderModify(OrderTicket(), OrderOpenPrice(), sl, tp, 0)) return;
            }
}
//+-----------------------------------------------------------------------------------------------+
void FindPattern()   // Ищем большое расстояние между свечами
{
   if(High[1] < High[2] && Bid > High[1] && Low[1] < Low[2])
   {
      double spacing = NormalizeDouble((High[2] - High[1]) / _Point, 0);
            
      if(maxSpacing >= spacing && minSpacing <= spacing)
         OpenOrder(OP_BUY);
   }
   if(Low[1] > Low[2] && Bid < Low[1] && High[1] > High[2])
   {
      double spacing = NormalizeDouble((Low[1] - Low[2]) / _Point, 0);
            
      if(maxSpacing >= spacing && minSpacing <= spacing)
         OpenOrder(OP_SELL);
   }   
   {
      if (TrailingStop!=0) TrailingStop();      
   }
}
//+-----------------------------------------------------------------------------------------------+
void TrailingStop()
{
   double StLo,OSL,OOP;
   bool error=true;   
   for (int i=0; i<OrdersTotal(); i++) 
   {
      if (OrderSelect(i, SELECT_BY_POS))
      {
         tip = OrderType();
         if (tip<2 && OrderSymbol()==Symbol() && OrderMagicNumber()==magic)
         {
            OSL   = NormalizeDouble(OrderStopLoss(),Digits);
            OOP   = NormalizeDouble(OrderOpenPrice(),Digits);
            if (tip==0)        
            {  
               StLo = NormalizeDouble(Bid - TrailingStop*Point,Digits);
               if (StLo < OOP) continue;
               if (StLo > OSL)
                  error=OrderModify(OrderTicket(),OrderOpenPrice(),StLo,OrderTakeProfit(),0,White);

            }                                         
            if (tip==1)    
            {                                         
               StLo = NormalizeDouble(Ask + TrailingStop*Point,Digits);           
               if (StLo > OOP) continue;
               if (StLo < OSL || OSL==0 )
                  error=OrderModify(OrderTicket(),OrderOpenPrice(),StLo,OrderTakeProfit(),0,White);
            } 
            if (!error) Alert("Error TrailingStop ",GetLastError(),"   ",Symbol(),"   SL ",StLo);
         }
      }
   }
}
//+-----------------------------------------------------------------------------------------------+


Foto del gráfico "Cómo debe apostar un EA"

Archivos adjuntos:
 
Vladim1203:

¡Hola a todos, podéis ayudarme a encontrar un error en el código del EA, creo que lo he mirado todo, parece que todo está escrito correctamente en el código, pero el programa no opera correctamente por alguna razón! La idea es la siguiente: El asesor tiene que buscar dos velas largas de la misma dirección (la longitud entre las velas es ajustable en el asesor, es decir, entre las dos velas mínimas o máximas, dependiendo de la dirección), si el precio en la dirección opuesta rompe el mínimo o el máximo de la última vela, un acuerdo debe abrirse (Ejemplo situaciones de imagen en el gráfico adjunto al archivo). El asesor debería abrir operaciones en cada situación adecuada, pero por alguna razón sólo abre operaciones en las ventanas de negociación entre días. Esta es la situación, que no es difícil de los programadores, por favor, ayuda, solucionar el error. Vea el código de EA a continuación, así como en el archivo adjunto.

Es mejor escribir primero la parte del EA que marcaría en el gráfico las velas encontradas, para que todo quede claro. Y las siguientes líneas son innecesarias en su caso:

extern string paramEA    = "";     // Parameters EA

и

//+-----------------------------------------------------------------------------------------------+
int OnInit()
{
   
   return(INIT_SUCCEEDED);
}
//+-----------------------------------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   
}
//+-----------------------------------------------------------------------------------------------+
 
STARIJ:

Ahora dime cómo obtener un beneficio aquí... ¿O lo necesitas para construir un juego?


Todavía no hay forma de obtener beneficios. Existe un algoritmo para el cálculo de dos objetivos de precio probables, a lo largo de la tendencia, por cinco puntos principales, pero se calcula en un servidor especial con una suscripción de pago. Quiero calcular los objetivos yo mismo, el trabajo en el algoritmo aún no ha terminado.

¿Qué aspecto tendrá tu programa en MQL4?

 
Anton Yakovlev:
Si tienes una buena estrategia y estás dispuesto a compartirla, puedo escribir un EA. Te invito a discutirlo públicamente o en mensaje privado.

Anton, ayúdame, he añadido la función trailing stop al EA, lo he compilado y me da dos errores. - Tengo la cabeza destrozada, no sé cómo arreglarlas para conseguir un búho. Sin embargo, las operaciones se cierran según la antigua estrategia después de que el precio haya tocado el límite superior del canal y el inferior, respectivamente. Supongo que aquí también hay que cambiar algo. - Vuelve a llamar a los chicos del ejército de DNR.

#property copyright "Copyright 2017, MetaQuotes Software Corp."

#enlace de propiedad "https://www.mql5.com"

#versión de la propiedad "1.00"

#propiedad estricta


//---------------------------------------------------------

extern double Lots = 0,01;

extern int TomaDeBeneficio = 600;

extern int StopLoss = 25;

extern int Magia = 0001;

extern int Deslizamiento = 3;

extern int TralType = 0; // 0-SAR, 1-ATR, 2-HMA.

extern double SAR_Step = 0.02;

extern double SAR_Max = 0.2;

extern int ATR_Period = 14;

extern double ATR_K = 2.0;

extern inttern HMA_Period = 16;

extern intern HMA_Method = 3;

extern inttern HMA_Shift = 0;

datetime LBT;

//---------------------------------------------------------

extern string TMA = "Parámetros del indicador TMA";

cadena externa TimeFrame = "marco temporal actual";

extern int MediaLongitud = 56;

extern int Precio = "PRICE_CLOSE;

extern double ATRMultiplier = 2.0;

extern inttern ATRPeriod = 100;

extern bool Interpolar = true;

//---------------------------------------------------------

doble PriceHigh, PriceLow, SL, TP;

int ticket;


//+------------------------------------------------------------------+

//| Función de inicialización de expertos |

//+------------------------------------------------------------------+

int OnInit()

{

si (Dígitos == 3 || Dígitos = 5)

{

TakeProfit *= 10;

StopLoss *= 10;

Deslizamiento *= 10;

}

return(INIT_SUCCEED);

}

//+------------------------------------------------------------------+

//| Función de desinicialización experta |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

{


}

//+------------------------------------------------------------------+

//| función de tic experto |

//+------------------------------------------------------------------+

void OnTick()

{

PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);

PriceLow = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);

if(CountSell() == 0 && Bid >= PriceHigh)

{

ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);

si (billete > 0)

{

SL = NormalizeDouble(Bid + StopLoss*Point, Digits);

TP = NormalizeDouble(Oferta - TakeProfit*Punto, Dígitos);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if (!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error de modificación del pedido!)

}

}

if (CountBuy() == 0 && Ask <= PriceLow)

{

ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);

si (billete > 0)

{

TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);

SL = NormalizeDouble(Ask - StopLoss*Point, Digits);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de compra!)

} else Print("Error al abrir la orden de compra");

}

//+------------------------------------------------------------------+

//| Función de inicialización de expertos |

//+------------------------------------------------------------------+

int init()

{

//--------


//--------

retorno (0);

}

//+------------------------------------------------------------------+

//| función de tic experto |

//+------------------------------------------------------------------+

void OnTick()

{

PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);

PriceLow = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);

if(CountSell() == 0 && Bid >= PriceHigh)

{

ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);

si (billete > 0)

{

SL = NormalizeDouble(Bid + StopLoss*Point, Digits);

TP = NormalizeDouble(Oferta - TakeProfit*Punto, Dígitos);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if (!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de venta!)

} else Print("¡Error al abrir la orden de venta!)

}

if (CountBuy() == 0 && Ask <= PriceLow)

{

ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);

si (billete > 0)

{

TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);

SL = NormalizeDouble(Ask - StopLoss*Point, Digits);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de compra!)

} else Print("Error al abrir la orden de compra");

}

if (Ask <= PriceLow && CountSell() > 0)

{

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

{

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderMagicNumber() == Magic && OrderType() == OP_SELL)

if (!OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Black))

Print("¡Error de orden de venta de OrderClose!)

}

}

}

if (Bid >= PriceHigh && CountBuy() > 0)

{

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

{

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderMagicNumber() == Magic && OrderType() == OP_BUY)

if(!OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Black))

Print("¡Error de compra de OrderClose!)

}

}

}

}

//+------------------------------------------------------------------+

int CuentaVenta()

{

int cuenta = 0;

for (int trade = OrdersTotal()-1; trade>=0; trade--)

{

if(OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))

{

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

cuenta++;

}

}

return(count);

}//+------------------------------------------------------------------+

int CuentaCompra()

{

int cuenta = 0;

for (int trade = OrdersTotal()-1; trade>=0; trade--)

{

if(OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))

{

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

cuenta++;

}

}

return(count);

}

//+------------------------------------------------------------------+

//| Función de desinicialización experta |

//+------------------------------------------------------------------+

int deinit()

{

//+-------


//+-------

devolver (0)

}

//+------------------------------------------------------------------+

//| función de inicio experto |

//+------------------------------------------------------------------+

int Inicio()

{

//-----

bool error = fals;

if (LBT!=Time[0]) {

if (OrdersTotal()!=0) {

for (int i=0; i<OrdersTotal(); i++) {

if (OrderSelect(i,SELECT_BY_POS)&&OrderSymbol()==Symbol()&&OrderType()<2) {

double SL = OrderStopLoss();

si OrderType()==0) {

switch (TralType) {

caso 0: SL = iSAR(NULL,0,SAR_Step,SAR_Max,0);

romper;

caso 1: SL = High[1] - iATR(NULL,0,ATR,Period,1)*ATR_K;

romper;

caso 2: SL = iCustom(NULL,0, "VininI_HMAsound&amp",HMA_Period,HMA_Method,3,HMA_Shift, fals,fals,",1,0,0);

romper;

}

si (SL<OrderStopLoss())

SL = OrderStopLoss();

}

si (OrderType()==1) {

switch (TralType) {

caso 0: SL = iSAR(NULL,0,SAR_Step,SAR_Max,0);

romper;

caso 1: SL = Low[1] + iATR(NULL,0,ATR,Period,1)*ATR_K;

romper;

caso 2: SL = iCustom(NULL,0, "VininI_HMAsound&amp",HMA_Period,HMA_Method,3,HMA_Shift, fals,fals,",1,0,0);

romper;

}

si (SL>OrderStopLoss())

SL = OrderStopLoss();

}

si (SL!=OrderStopLoss()) {

if(!OrderModify(OrderTicket(),OrderOpenPrice(),SL,OrderTakeProfit(),0))

error = true;

}

}

}

}

si (!error)

LBT = Tiempo[0];

}

retorno (0);

}

//+------------------------------------------------------------------+

Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
Выберите подходящую торговую стратегию и оформите подписку на нее в пару кликов. Все Сигналы сопровождаются подробной статистикой и графиками. Станьте Поставщиком торговых сигналов и продавайте подписку тысячам трейдеров по всему миру. Наш сервис позволит вам хорошо зарабатывать на прибыльной стратегии даже при небольшом стартовом капитале...
 
Andrey Luxe:

Para ganar experiencia en esta área, voy a escribir 25 EAs gratis para sus ideas y estrategias interesantes

Sólo quedan 19 EAs


Heañadido la función trailing stop al EA y la he comentado y produce dos errores. - Puede que tenga algunos errores, pero no sé cómo solucionarlos. Sin embargo, las operaciones se cierran según la antigua estrategia después de que el precio haya tocado el límite superior del canal y el inferior, respectivamente. Supongo que aquí también hay que cambiar algo. - Vuelve a llamar a los chicos del ejército de DNR.

#property copyright "Copyright 2017, MetaQuotes Software Corp."

#enlace de propiedad "https://www.mql5.com"

#versión de la propiedad "1.00"

#propiedad estricta


//---------------------------------------------------------

extern double Lots = 0,01;

extern int TomaDeBeneficio = 600;

extern int StopLoss = 25;

extern int Magia = 0001;

extern int Deslizamiento = 3;

extern int TralType = 0; // 0-SAR, 1-ATR, 2-HMA.

extern double SAR_Step = 0.02;

extern double SAR_Max = 0.2;

extern int ATR_Period = 14;

extern double ATR_K = 2.0;

extern inttern HMA_Period = 16;

extern intern HMA_Method = 3;

extern inttern HMA_Shift = 0;

datetime LBT;

//---------------------------------------------------------

extern string TMA = "Parámetros del indicador TMA";

cadena externa TimeFrame = "marco temporal actual";

extern int MediaLongitud = 56;

extern int Precio = "PRICE_CLOSE;

extern double ATRMultiplier = 2.0;

extern inttern ATRPeriod = 100;

extern bool Interpolar = true;

//---------------------------------------------------------

doble PriceHigh, PriceLow, SL, TP;

int ticket;


//+------------------------------------------------------------------+

//| Función de inicialización de expertos |

//+------------------------------------------------------------------+

int OnInit()

{

si (Dígitos == 3 || Dígitos = 5)

{

TakeProfit *= 10;

StopLoss *= 10;

Deslizamiento *= 10;

}

return(INIT_SUCCEED);

}

//+------------------------------------------------------------------+

//| Función de desinicialización experta |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

{


}

//+------------------------------------------------------------------+

//| función de tic experto |

//+------------------------------------------------------------------+

void OnTick()

{

PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);

PriceLow = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);

if(CountSell() == 0 && Bid >= PriceHigh)

{

ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);

si (billete > 0)

{

SL = NormalizeDouble(Bid + StopLoss*Point, Digits);

TP = NormalizeDouble(Oferta - TakeProfit*Punto, Dígitos);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if (!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error de modificación del pedido!)

}

}

if (CountBuy() == 0 && Ask <= PriceLow)

{

ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);

si (billete > 0)

{

TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);

SL = NormalizeDouble(Ask - StopLoss*Point, Digits);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de compra!)

} else Print("Error al abrir la orden de compra");

}

//+------------------------------------------------------------------+

//| Función de inicialización de expertos |

//+------------------------------------------------------------------+

int init()

{

//--------


//--------

retorno (0);

}

//+------------------------------------------------------------------+

//| función de tic experto |

//+------------------------------------------------------------------+

void OnTick()

{

PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);

PriceLow = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);

if(CountSell() == 0 && Bid >= PriceHigh)

{

ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);

si (billete > 0)

{

SL = NormalizeDouble(Bid + StopLoss*Point, Digits);

TP = NormalizeDouble(Oferta - TakeProfit*Punto, Dígitos);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if (!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de venta!)

} else Print("¡Error al abrir la orden de venta!)

}

if (CountBuy() == 0 && Ask <= PriceLow)

{

ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);

si (billete > 0)

{

TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);

SL = NormalizeDouble(Ask - StopLoss*Point, Digits);

if (OrderSelect(ticket, SELECT_BY_TICKET))

if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0))

Print("¡Error al modificar la orden de compra!)

} else Print("Error al abrir la orden de compra");

}

if (Ask <= PriceLow && CountSell() > 0)

{

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

{

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderMagicNumber() == Magic && OrderType() == OP_SELL)

if (!OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Black))

Print("¡Error de cierre de la orden de venta!)

}

}

}

if (Bid >= PriceHigh && CountBuy() > 0)

{

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

{

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderMagicNumber() == Magic && OrderType() == OP_BUY)

if(!OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Black))

Print("¡Error de compra de OrderClose!)

}

}

}

}

//+------------------------------------------------------------------+

int CuentaVenta()

{

int cuenta = 0;

for (int trade = OrdersTotal()-1; trade>=0; trade--)

{

if(OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))

{

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

cuenta++;

}

}

return(count);

}//+------------------------------------------------------------------+

int CuentaCompra()

{

int cuenta = 0;

for (int trade = OrdersTotal()-1; trade>=0; trade--)

{

if(OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))

{

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

cuenta++;

}

}

return(count);

}

//+------------------------------------------------------------------+

//| Función de desinicialización experta |

//+------------------------------------------------------------------+

int deinit()

{

//+-------


//+-------

devolver (0)

}

//+------------------------------------------------------------------+

//| función de inicio experto |

//+------------------------------------------------------------------+

int Inicio()

{

//-----

bool error = fals;

if (LBT!=Time[0]) {

if (OrdersTotal()!=0) {

for (int i=0; i<OrdersTotal(); i++) {

if (OrderSelect(i,SELECT_BY_POS)&&OrderSymbol()==Symbol()&&OrderType()<2) {

double SL = OrderStopLoss();

si OrderType()==0) {

switch (TralType) {

caso 0: SL = iSAR(NULL,0,SAR_Step,SAR_Max,0);

romper;

caso 1: SL = High[1] - iATR(NULL,0,ATR,Period,1)*ATR_K;

romper;

caso 2: SL = iCustom(NULL,0, "VininI_HMAsound&amp",HMA_Period,HMA_Method,3,HMA_Shift, fals,fals,",1,0,0);

romper;

}

si (SL<OrderStopLoss())

SL = OrderStopLoss();

}

si (OrderType()==1) {

switch (TralType) {

caso 0: SL = iSAR(NULL,0,SAR_Step,SAR_Max,0);

romper;

caso 1: SL = Low[1] + iATR(NULL,0,ATR,Period,1)*ATR_K;

romper;

caso 2: SL = iCustom(NULL,0, "VininI_HMAsound&amp",HMA_Period,HMA_Method,3,HMA_Shift, fals,fals,",1,0,0);

romper;

}

si (SL>OrderStopLoss())

SL = OrderStopLoss();

}

si (SL!=OrderStopLoss()) {

if(!OrderModify(OrderTicket(),OrderOpenPrice(),SL,OrderTakeProfit(),0))

error = true;

}

}

}

}

si (!error)

LBT = Tiempo[0];

}

retorno (0);

}

//+------------------------------------------------------------------+

Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
Выберите подходящую торговую стратегию и оформите подписку на нее в пару кликов. Все Сигналы сопровождаются подробной статистикой и графиками. Станьте Поставщиком торговых сигналов и продавайте подписку тысячам трейдеров по всему миру. Наш сервис позволит вам хорошо зарабатывать на прибыльной стратегии даже при небольшом стартовом капитале...
 
vkravtzov:

Heañadido la función de trailing stop al Asesor Experto, y lo he compilado y tengo dos errores. - He perdido la cabeza, no consigo averiguar cómo arreglarlas para conseguir un búho. Sin embargo, las operaciones se cierran según la antigua estrategia después de que el precio haya tocado el límite superior del canal y el inferior, respectivamente. Supongo que aquí también hay que cambiar algo. - Devuélvelo a los chicos del ejército de la RPD.


No es necesario hacer spam.
 
Victor Nikolaev:
No deberías hacer spam.

Pido disculpas si he hecho algo mal. Todavía no sé cómo he hecho spam... Creo que dirigí dos mensajes a dos camaradas. ¿O no está permitido? - Es culpa mía.

Razón de la queja: