![MQL5 - Lenguaje de estrategias comerciales para el terminal de cliente MetaTrader 5](https://c.mql5.com/i/registerlandings/logo-2.png)
Está perdiendo oportunidades comerciales:
- Aplicaciones de trading gratuitas
- 8 000+ señales para copiar
- Noticias económicas para analizar los mercados financieros
Registro
Entrada
Usted acepta la política del sitio web y las condiciones de uso
Si no tiene cuenta de usuario, regístrese
Necesito ayuda.
http://forum.mql4.com/ru/67309#1011467
Por favor, avisen: las órdenes no se abren todos los días el arrastre no funciona y las órdenes abiertas se cierran no según el TP. ¿Qué estoy haciendo mal?
input int StartHour = 23; // Время ачало торговли
input int TakeProfit = 40; // TakeProfit
input int StopLoss = 40; // StopLoss
input int Lots = 0.1; // Лот для торговли
input int Magic = 22; // Магическое число
input int Trals = 20; // Дистанция тралинга в пунктах
input int _Step = 1; // Шаг
input bool _StepUse = true; // Использовать шаг или нет
void OnTick()
{
static bool IsFirstTick = false;
static int ticket = 0;
double lot=Lot_Normalize(Symbol(),Lots,1);
double sl= Dist_Normalize(Symbol(),Trals);
double step= Dist_Normalize(Symbol(),_Step);
int h= TimeHour(TimeCurrent());
if(h == StartHour)
{
Alert("TimeHor: ", h);
if (IsFirstTick == true)
IsFirstTick = false;
bool res;
res= OrderSelect(ticket, SELECT_BY_TICKET);
if(res == true)
{
if(OrderCloseTime() == 0)
{
bool res2;
res2 = OrderClose(ticket, Lots, OrderClosePrice(), 10);
if(res2 == false)
{
Alert("Error Closing Order #", ticket);
} Alert("Closing Order #", ticket);
}
}
if(Open[0] < Open[StartHour])
{
ticket = OrderSend(Symbol(), OP_BUYLIMIT, Lots, High[1],10, Low[1]-StopLoss*Point, High[1]+TakeProfit*Point,"Set bu ForexRobot");
Tralling_Stop(OrderSymbol(),Magic,sl,step,_StepUse);
if(ticket < 0)
{
Alert("Error Sending Order!");
} Alert("Sending Order! BUY_LIMIT");
}
else
{
ticket = OrderSend(Symbol(), OP_SELLLIMIT, Lots, Low[1],10, High[1]+StopLoss*Point, Low[1]+TakeProfit*Point,"Set bu ForexRobot");
Tralling_Stop(OrderSymbol(),Magic,sl,step,_StepUse);
if(ticket < 0)
{
Alert("Error Sending Order!");
} Alert("Sending Order! SEL_LLIMIT");
}
}
}
double Dist_Normalize(string Smv, int _Distancia)
{
int Dig= int(MarketInfo(Smv,MODE_DIGITS));
double Pip=MarketInfo(Smv,MODE_POINT);
if(Dig==3 || Dig==5)
return NormalizeDouble(_Distancia*10*Pip,Dig);
else return NormalizeDouble(_Distancia*Pip,Dig);
}
double Lot_Normalize(string Smv, double _lot, double _mult)
{
double minlot=MarketInfo(Smv,MODE_MINLOT);
double maxlot=MarketInfo(Smv,MODE_MAXLOT);
double steplot=MarketInfo(Smv,MODE_LOTSTEP);
double lot= _lot*_mult;
if(lot<=minlot) lot+minlot;
else if(lot>=maxlot) lot=minlot;
else if(lot>minlot && lot<maxlot)
{
int k=int((lot-minlot)/steplot);
lot=NormalizeDouble(minlot+k*steplot,2);
}
return(lot);
}
void Tralling_Stop(string Smv, int _Magic, double _Tral, double _Step, bool _Step_Use)
{
int Dig=int(MarketInfo(_Symbol,MODE_DIGITS));
for(int pos=OrdersTotal()-1; pos>=0;pos--)
{
if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Smv &&
OrderMagicNumber()==_Magic && OrderType()<2)
{
double SLPrice;
if(OrderType()==OP_BUY)
{
if(_Step_Use)
{
RefreshRates();
if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral+_Step,Dig))
{
SLPrice=NormalizeDouble(Ask-_Tral,Dig);
if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
Alert("Error modifi Order!: ",GetLastError());
}
}
else
{
RefreshRates();
if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral,Dig))
{
SLPrice=NormalizeDouble(Bid+_Tral,Dig);
if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
Alert("Error modifi Order!: ",GetLastError());
}
}
}
}
}
}
Por favor, avisen: las órdenes no se abren todos los días el arrastre no funciona y las órdenes abiertas se cierran no según el TP. ¿Qué estoy haciendo mal?
input int StartHour = 23; // Время ачало торговли
input int TakeProfit = 40; // TakeProfit
input int StopLoss = 40; // StopLoss
input int Lots = 0.1; // Лот для торговли
input int Magic = 22; // Магическое число
input int Trals = 20; // Дистанция тралинга в пунктах
input int _Step = 1; // Шаг
input bool _StepUse = true; // Использовать шаг или нет
void OnTick()
{
......
IsFirstTick = false;
Yo sustituiría esta pieza por
Donde la variable TM se declara como DateTime fuera de la función OnTick(), es decir, es global para este módulo.
No entiendo este código: if(Open[0] < Open[StartHour])
El StartHour es igual a 23 y sugiere que el precio de apertura de la barra cero se comparará con el precio de apertura de la barra 23 anterior. Bueno, vale, quizá sea un truco del Asesor Experto.
Pero este diseño no es apropiado en absoluto.
¿Qué pasa si la variable del ticket es igual a cero, o se ha reiniciado el EA y esta variable se ha restablecido por defecto?
La hora de inicio es la hora en la que debe funcionar el EA. Debería ser la 1:00 a.m. ¿Por qué no funciona la pesca de arrastre?
Hay que analizar el código para entender por qué no funciona.
Intente insertarla función Print("Tralling_Stop") en la funciónTralling_Stop(), y vea si este mensaje (Tralling_Stop) aparece en el registro, si no es así, entonces esta función no es llamada. Si lo tienes, analiza la propia función Tralling_Stop(), quizá contenga algún error lógico.
En general, siempre que haya condiciones lógicas if, inserte Print(" condición 1" ), Print(" condición 2" ), etc. Ejecute el Asesor Experto en el probador de estrategias y en el diario podrá rastrear la lógica de su EA.
Hay que analizar el código para entender por qué no funciona.
Intente insertarla función Print("Tralling_Stop") en la funciónTralling_Stop(), y vea si este mensaje (Tralling_Stop) aparece en el registro, si no es así, entonces esta función no es llamada. En caso afirmativo, analice la propia función Tralling_Stop() - tal vez haya algunos errores lógicos en ella.
En general, siempre que haya condiciones lógicas if, inserte Print(" condición 1" ), Print(" condición 2" ), etc. Ejecute el Asesor Experto en el probador de estrategias y en el diario podrá rastrear la lógica de su EA.
He intentado reescribirlo pero sigue sin funcionar como necesito. Los pedidos no se abren cuando yo quiero, luego no trinan. Según la idea, el Asesor Experto debería funcionar así: al cierre de la última vela de un día (a las 00:00) debería abrir dos órdenes pendientes: Alta (para comprar) y Baja (para vender) y luego sólo trillarlas.
input int StartHour = 1; // Начало торговли
input int TakeProfit = 40; // TakeProfit
input int StopLoss = 10; // StopLoss
extern double Lots = 0.1; // Лот для торговли
input int Magic = 22; // Магическое число
input int Trals = 5; // Дистанция тралинга в пунктах
input int _Step = 1; // Шаг
input bool _StepUse = false; // Использовать шаг или неT
void OnTick()
{
static bool IsFirstTick = false;
Trailing();
if (StartHour != Hour()) { return;}
if (OrdersTotal()>0)
{
OrderSend(Symbol(), OP_BUYLIMIT, Lots, High[1],10, Low[1]-StopLoss*Point, High[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);
OrderSend(Symbol(), OP_SELLLIMIT, Lots, Low[1],10, High[1]+StopLoss*Point, Low[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);
}
}
//+------------------------------------------------------------------+
void Trailing()
{
if (_StepUse)
{
for (int trall=0; trall<OrdersTotal(); trall++) {
if (!(OrderSelect(trall, SELECT_BY_POS, MODE_TRADES))) continue;
if (OrderSymbol() != Symbol()) continue;
if (OrderType() == OP_BUY ) {
if (Bid-OrderOpenPrice() > StopLoss*Point || OrderMagicNumber()==Magic) {
if (OrderStopLoss() < Bid-(StopLoss+_Step-1)*Point || OrderStopLoss() == 0) {
OrderModify(OrderTicket(), OrderOpenPrice(), Bid-StopLoss*Point, OrderTakeProfit(), 0, Blue);
}
}
}
if (OrderType() == OP_SELL) {
if (OrderOpenPrice()-Ask > StopLoss*Point || OrderMagicNumber()==Magic) {
if (OrderStopLoss() > Ask+(StopLoss+_Step-1)*Point || OrderStopLoss() == 0) {
OrderModify(OrderTicket(), OrderOpenPrice(), Ask+StopLoss*Point, OrderTakeProfit(), 0, Blue);
}
}
}
}
}
}
//+------------------------------------------------------------------+
Prueba con
Sustitúyelo por:
Sustitúyelo por:
Además, los precios deben ser normalizados utilizando NormalizeDouble(). Es decir, en lugar deLow[1]-StopLoss*Point debe escribir NormalizeDouble(Low[1]-StopLoss*Point,Digits()).
Además, según su código, si la variable _StepUse es igual a false, su trailing stop no funcionará. Fíjate bien en el código de la función Trailing()
Prueba con
Sustitúyelo por:
Sustitúyelo por:
Además, los precios deben ser normalizados utilizando NormalizeDouble(). Es decir, en lugar deLow[1]-StopLoss*Point debe escribir NormalizeDouble(Low[1]-StopLoss*Point,Digits()).
Además, según su código, si la variable _StepUse es igual a false, su trailing stop no funcionará. Fíjate bien en el código de la función Trailing().
¿Estás en contacto? Envíame un mensaje a http://vk.com/computerwizard116. Ya no sé cómo resolver el problema de EA. He estado trabajando en esta estrategia durante una semana en una cuenta demo
Y funciona. Y en las pruebas, este bribón ni siquiera cierra la orden hasta el punto de recogida(((((( En la foto, se puede ver que el precio sobrepasó el punto de recogida y retrocedió, pero cerró en pérdidas, maldita sea !(((
¿Por qué lo hace?
¿Estás en contacto? Envíame un correo electrónico a http://vk.com/computerwizard116. Ya no sé cómo resolver el problema de EA. He estado usando esta estrategia durante una semana en una cuenta demo
y funciona. Pero al hacer la prueba, este bribón ni siquiera cierra la orden de retirada. (((((( En la foto, se puede ver que el precio superó la retirada y retrocedió, pero cerró con pérdidas.
¿Por qué hace eso?
No estoy en contacto.
Lasórdenes Take profit y Stop loss no dependen del asesor, se ejecutan en el servidor del broker. El EA sólo establece el take profit y el stop loss, no los ejecuta. Comprueba si la toma de beneficios ya fue establecida después de que el precio alcanzara este valor. En otras palabras, la orden se abrió primero, y luego el precio se movió hacia adelante y hacia atrás, y luego se estableció el take profit.
No estoy en contacto.
La ejecución de las órdenes take profit y stop loss no depende del EA, se ejecutan en el servidor del broker. El EA sólo establece las órdenes de compra y de parada, no las ejecuta. Comprueba si la toma de beneficios ya fue establecida después de que el precio alcanzara este valor. En otras palabras, primero se abrió la orden, luego el precio fue avanzando y retrocediendo, y después se fijó el take profit.