¿Cómo codificar? - página 284

 

He ordenado una solución para el filtro de tiempo Cerrar todo

Variables externas

extern string timefilter="Time Filter";

extern int gmtshift=1; // gmt offset of the broker

extern bool generalfilter=false; // enable time filter

extern int starthour=7; // start hour to trade after this hour

extern int startminutes=0; // minutes of the start hour

extern int endhour=21; // stop to trade after this hour

extern int endminutes=0; // minutes of the start hour

extern bool tradesunday=true; // trade on sunday

extern bool fridayfilter=false; // enable special time filter on friday

extern int fridayhour=21; // stop to trade after this hour

extern int fridayminutes=0; // minutes of the friday hour

[/CODE]

int nstarthour,nendhour,nfridayhour;

string istarthour,istartminutes,iendhour,iendminutes,ifridayhour,ifridayminutes;

datetime tstart,tend,tfriday;[/CODE]

Place Code in Start,

[CODE] if(generalfilter){

nstarthour=starthour+(gmtshift);if(nstarthour>23)nstarthour=nstarthour-24;

if(nstarthour<10)istarthour="0"+nstarthour;

if(nstarthour>9)istarthour=nstarthour;

if(startminutes<10)istartminutes="0"+startminutes;

if(startminutes>9)istartminutes=startminutes;

tstart=StrToTime(istarthour+":"+istartminutes);

nendhour=endhour+(gmtshift);if(nendhour>23)nendhour=nendhour-24;

if(endhour<10)iendhour="0"+nendhour;

if(endhour>9)iendhour=nendhour;

if(endminutes<10)iendminutes="0"+endminutes;

if(endminutes>9)iendminutes=endminutes;

tend=StrToTime(iendhour+":"+iendminutes);

}

if(fridayfilter){

nfridayhour=fridayhour+(gmtshift);if(nfridayhour>23)nfridayhour=nfridayhour-24;

if(nfridayhour<10)ifridayhour="0"+nfridayhour;

if(nfridayhour>9)ifridayhour=nfridayhour;

if(fridayminutes<10)ifridayminutes="0"+fridayminutes;

if(fridayminutes>9)ifridayminutes=fridayminutes;

tfriday=StrToTime(ifridayhour+":"+ifridayminutes);

}

if((generalfilter && (nstarthour<nendhour && TimeCurrent()tend) || (nstarthour>nendhour && TimeCurrent()tend))

|| (tradesunday==false && DayOfWeek()==0) || (fridayfilter && DayOfWeek()==5 && TimeCurrent()>tfriday))

{

CloseAll();

Comment("Non-trading Hours All Positions Closed");

return(0);

}

and the CloseAll function.

[CODE]

void CloseAll(){

int total = OrdersTotal();

for(int i=total-1;i>=0;i--){

OrderSelect(i, SELECT_BY_POS);

int type = OrderType();

bool result = false;

switch(type){

//Close opened long positions

case OP_BUY : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Lime); break;

//Close opened short positions

case OP_SELL : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, LightGreen );

} if(result == false){

Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );

Sleep(3000);

}

}

return(0);

}

gracias por los consejos y sugerencias Kalenzo

 

StopLoss

Gidday

He estado probando un experimento para calcular un SL basado en el tickvalue un dd máximo y el porcentaje por operación.

double lotSize = NormalizeDouble(Kellylot(),2);

double Pip = Point;

if(Digits==3 || Digits==5) Pip = 10*Point;

double Bal = AccountBalance(); // $1000

double TV = MarketInfo(Symbol(), MODE_TICKVALUE); // $1

double Risk = 2; // 2%

double MaxDD = 10; // 10%

double RiskCapital = Bal*MaxDD/100; // Total Exposure 10% of $1000 = $100

double RPT = Bal*Risk/100; // 2% of $1000 = $20

double stopLoss = NormalizeDouble(RPT/TV*lotSize/Pip,Digits); //$20/1*0.01/10 = 0.02000

double Positions = MathAbs(RiskCapital/RPT); // Maximum 5 positions 100 / 20

La idea es que dependiendo del par y del tickvalue individual de los pares y del tamaño del lote se puede establecer el 2% de sl.

Creo que es correcto pero me gustaría que alguien lo revisara si es posible.

 
Beno:
Gidday

He estado probando un experimento para calcular un SL basado en el tickvalue un dd máximo y el porcentaje por operación.

double lotSize = NormalizeDouble(Kellylot(),2);

double Pip = Point;

if(Digits==3 || Digits==5) Pip = 10*Point;

double Bal = AccountBalance(); // $1000

double TV = MarketInfo(Symbol(), MODE_TICKVALUE); // $1

double Risk = 2; // 2%

double MaxDD = 10; // 10%

double RiskCapital = Bal*MaxDD/100; // Total Exposure 10% of $1000 = $100

double RPT = Bal*Risk/100; // 2% of $1000 = $20

double stopLoss = NormalizeDouble(RPT/TV*lotSize/Pip,Digits); //$20/1*0.01/10 = 0.02000

double Positions = MathAbs(RiskCapital/RPT); // Maximum 5 positions 100 / 20

La idea es que dependiendo del par y del tickvalue individual de los pares y del tamaño del lote se puede establecer el 2% de sl.

Creo que es correcto pero me gustaría que alguien lo revisara si es posible.

Buen trabajo Beno,

Siempre es mejor dar una caña de pescar que un pez. Me alegro mucho de haberte ayudado con algunos comentarios.

En cuanto al stop loss, la idea es buena, sin embargo intenta también considerarlo de forma inversa:

primero fijar el stop loss

en segundo lugar establecer el tamaño de la operación

De esta forma ajustarás la entrada/salida del sistema a las condiciones del mercado, y no arriesgarás más del X% de tu cuenta, pero la salida dependerá de la lógica del sistema en lugar del porcentaje de riesgo.

 
Kalenzo:
Buen trabajo Beno,

Siempre es mejor dar una caña de pescar que un pez. Me alegro mucho de haberte podido ayudar con algunos comentarios.

En cuanto al stop loss, la idea es buena, sin embargo intenta también considerarlo de forma inversa:

primero fijar el stop loss

en segundo lugar establecer el tamaño de la operación

De esta manera usted ajustará la entrada/salida del sistema a las condiciones del mercado, y no arriesgará más del X% de su cuenta, pero la salida dependerá de la lógica del sistema en lugar del porcentaje de riesgo.

Gidday Kalenzo

Me sale un error al abrir la orden de VENTA: stops inválidos con el EA está en la cuenta demo y en la cuenta real y no se abre ninguna operación. pero funciona bien en el tester y no tiene mensajes de error.

EURUSD,Diario: modificar #1 comprar 0.01 EURUSD a 1.43348 sl: 1.43895 tp: 0.00000 ok

El SL 0.00547 puntos de diferencia

He comprobado el

MODE_FREEZELEVEL 0.0000

MODE_STOPLEVEL 0.0000

double lotSize = NormalizeDouble(Kellylot(),2);

double Bal = AccountFreeMargin();

double TV = MarketInfo(Symbol(), MODE_TICKVALUE);

double Risk = 0.3;

double MaxDD = 10;

double RiskCapital = Bal*MaxDD/100;

double RPT = Bal*Risk/100;

double stopLoss = NormalizeDouble((RPT/TV)*lotSize/pips2dbl,Digits);

double Positions = MathAbs(RiskCapital/RPT);

double SL;

//---- sell conditions

if(sellsig && ttime!=Time[0]){

double bid = NormalizeDouble(Bid, Digits);

SL = NormalizeDouble(Bid + stopLoss * pips2dbl, Digits);

res=OrderSend(symbol,OP_SELL,lotSize,bid,slippage * pips2dbl,SL,0,"Pivot_Sell",SpecificMagic,0,Red);

if( res<0 )

{

Print("Error opening SELL order : ",ErrorDescription(GetLastError()));

Print("Bid=" + DoubleToStr(bid,Digits) + " : SL=" + DoubleToStr(SL,Digits));

res=0;

}

else //now enter in the SL and TP via OrderModify to make compatible with ECN broker

{

if (OrderSelect(res, SELECT_BY_TICKET))

{

if (!OrderModify(res, Bid, SL, 0, 0, Red))

Print("Error modifying order");

}

}

ttime=Time[0];

return;

}

//---- buy conditions

if(buysig && ttime!=Time[0]) {

double ask = NormalizeDouble(Ask, Digits);

SL = NormalizeDouble(Ask - stopLoss * pips2dbl, Digits);

res=OrderSend(symbol,OP_BUY,lotSize,ask,slippage * pips2dbl,SL,0,"Pivot Buy",SpecificMagic,0,Blue);

if( res<0 )

{

Print("Error opening BUY order : ",ErrorDescription(GetLastError()));

Print("Ask=" + DoubleToStr(ask,Digits) + " : SL=" + DoubleToStr(SL,Digits));

res=0;

}

else //now enter in the SL and TP via OrderModify to make compatible with ECN broker

{

if (OrderSelect(res, SELECT_BY_TICKET))

{

if (!OrderModify(res, Ask, SL, 0, 0, Blue))

Print("Error modifying order");

}

}

ttime=Time[0];

return;

}

}

Nunca me había encontrado con esto.

Saludos

Beno

 

Función Latch/Unlatch

¿Existe una manera de codificar una función latch/unlatch en mq4? Se podría enganchar un bit true basado en una condición y se almacenaría este valor hasta que se desenganche por otra condición.

cmfxtrader

 
Beno:
Día de la semana Kalenzo

Estoy recibiendo un error de apertura de la orden de venta: paradas no válidas con el EA está en la cuenta demo y en la cuenta real y no se abren las operaciones. pero funciona bien en el probador y no tiene mensajes de error.

EURUSD,Diario: modificar #1 comprar 0.01 EURUSD a 1.43348 sl: 1.43895 tp: 0.00000 ok

El SL 0.00547 puntos de diferencia

He comprobado el

MODE_FREEZELEVEL 0.0000

MODE_STOPLEVEL 0.0000

double lotSize = NormalizeDouble(Kellylot(),2);

double Bal = AccountFreeMargin();

double TV = MarketInfo(Symbol(), MODE_TICKVALUE);

double Risk = 0.3;

double MaxDD = 10;

double RiskCapital = Bal*MaxDD/100;

double RPT = Bal*Risk/100;

double stopLoss = NormalizeDouble((RPT/TV)*lotSize/pips2dbl,Digits);

double Positions = MathAbs(RiskCapital/RPT);

double SL;

//---- sell conditions

if(sellsig && ttime!=Time[0]){

double bid = NormalizeDouble(Bid, Digits);

SL = NormalizeDouble(Bid + stopLoss * pips2dbl, Digits);

res=OrderSend(symbol,OP_SELL,lotSize,bid,slippage * pips2dbl,SL,0,"Pivot_Sell",SpecificMagic,0,Red);

if( res<0 )

{

Print("Error opening SELL order : ",ErrorDescription(GetLastError()));

Print("Bid=" + DoubleToStr(bid,Digits) + " : SL=" + DoubleToStr(SL,Digits));

res=0;

}

else //now enter in the SL and TP via OrderModify to make compatible with ECN broker

{

if (OrderSelect(res, SELECT_BY_TICKET))

{

if (!OrderModify(res, Bid, SL, 0, 0, Red))

Print("Error modifying order");

}

}

ttime=Time[0];

return;

}

//---- buy conditions

if(buysig && ttime!=Time[0]) {

double ask = NormalizeDouble(Ask, Digits);

SL = NormalizeDouble(Ask - stopLoss * pips2dbl, Digits);

res=OrderSend(symbol,OP_BUY,lotSize,ask,slippage * pips2dbl,SL,0,"Pivot Buy",SpecificMagic,0,Blue);

if( res<0 )

{

Print("Error opening BUY order : ",ErrorDescription(GetLastError()));

Print("Ask=" + DoubleToStr(ask,Digits) + " : SL=" + DoubleToStr(SL,Digits));

res=0;

}

else //now enter in the SL and TP via OrderModify to make compatible with ECN broker

{

if (OrderSelect(res, SELECT_BY_TICKET))

{

if (!OrderModify(res, Ask, SL, 0, 0, Blue))

Print("Error modifying order");

}

}

ttime=Time[0];

return;

}

}

Nunca me había encontrado con esto.

Saludos

Beno

Probablemente tu stop loss está demasiado cerca. Intenta multiplicar el valor del stop loss por 10. Es un problema frecuente cuando se prueba el sistema en un broker de 4 dígitos, y se opera en un broker de 5 dígitos. También puedes probarlo en un broker de 5 dígitos, pero nunca te conectes al broker (en modo offline) y entonces metatrader tendrá la configuración antigua (de 4 dígitos).

Primero de esta línea:

NormalizeDouble(Ask - stopLoss * pips2dbl, Digits);

Imprime este valor => stopLoss*pips2dbl

entonces usted sabrá el valor real de la pérdida de la parada.

si es como 20 o 10 entonces significa que necesitas multiplicarlo por el valor del punto

NormalizeDouble(Ask - (stopLoss * pips2dbl) *Point, Digits);

si es como 0.00009 entonces necesitas multiplicarlo por 10 porque debería ser 0.0009 (por supuesto si deseas establecer un stop loss de 9 pips)

 
cmfxtrader:
Hay una manera de codificar una función de latch/unlatch en mq4. Usted podría latchear un bit true basado en una condición y almacenaría este valor hasta que sea desenganchado por otra condición. cmfxtrader

No estoy seguro de haberte entendido bien. ¿Deseas activar/desactivar una parte específica del ea(función) o deseas desactivar la función del ea A por la acción realizada en el ea B? De esta forma u otra, ambas son posibles.

 

Convertir el valor del dinero en precio (para el cálculo del objetivo de beneficio)

Me gustaría programar una función que devuelva un valor de precio para un objetivo de beneficio determinado de una cesta de operaciones, pero estoy teniendo dificultades. El objetivo que me gustaría alcanzar, es una simple línea horizontal que se dibuja en pantalla y que indica el objetivo de beneficio. Sin embargo, el objetivo de beneficio es una variable definible por el usuario en forma de valor monetario y no de precio. (por ejemplo, objetivo = 100 euros en lugar de objetivo = 1.2000)

La rutina que tengo hasta ahora:

(¡Mi cuenta está en EUR!)

1) Digamos que abro varias posiciones de compra para el USDJPY (en posiciones aleatorias para crear una situación de ejemplo)

2) Calculo el precio medio abierto de la cesta (digamos 1,1500, de nuevo hipotéticamente) y muestro una línea horizontal para indicarlo

3) Tengo una variable con un objetivo de beneficios: digamos objetivo = 100 euros

4) Puedo cerrar con éxito todas las posiciones abiertas cuando el beneficio de la cesta >= objetivo

Falta el paso intermedio. Necesito una función: double targetPrice(){} que devuelva el targetPrice. El problema no es dibujar la línea horizontal, sino calcular el precio objetivo.

El targetPrice = precio medio abierto + valor monetario-objetivo (100 euros)

Así que lo que básicamente me gustaría saber: cómo convierto un money-value en pips. De esta forma puedo sumar los pips al precio medio y voilá tengo mi targetPrice. Recuerda que esto también tiene que tener en cuenta el hecho de que tengo una cuenta en EUR y estoy operando en USDJPY. ¿Supongo que también hay trampas ahí?

 

ECN SL no funciona

Gidday

Estoy tratando de configurar un EA que funcione en un ECN, entiendo que el SL y el TP tienen que ser colocados / modificados y creo que la configuración es correcta, la orden se abre ahora, pero el SL no se coloca externamente doble StopLoss = 100; cualquier ayuda sería genial.

//---- buy conditions

if(buysig && ttime!=Time[0]) {

ticket = OrderSend(Symbol(), OP_BUY, lotSize, MarketInfo(Symbol(), MODE_ASK), 2, 0, 0, "", 12345);

if(ticket > -1){

if (!OrderSelect(ticket, SELECT_BY_TICKET)) {

error_code = GetLastError();

Print("Error: " + ErrorDescription(error_code));

return(-1);

}

Print("order "+ticket+" successfully opened");

//now enter in the SL and TP via OrderModify to make compatible with ECN broker

SL = MarketInfo(Symbol(), MODE_ASK) - (StopLoss * pips2points);

Print("Ask = " + DoubleToStr(Ask,Digits) + " : SL = " + DoubleToStr(SL,Digits));

//round to nearest Tickvalue

SL = DoubleRound(SL, MarketInfo(Symbol(), MODE_TICKSIZE));

Print("SL rounded: " + SL);

if(!OrderModify(ticket, entry_price, SL, 0, Blue)) {

error_code = GetLastError();

Print("Error: " + ErrorDescription(error_code));

return(-1);

}

Print("Stoploss successfully set");

ttime=Time[0];

return(0);

}

}

}

//Tickvalue Rounding

double DoubleRound(double number, double step){

double mod = MathMod(number, step);

if(mod < step/2.0)

step = 0;

double rounded = number - mod + step;

return (rounded);

}
 

,,,,,,,,,,,,,.,,,,,,,,,

Archivos adjuntos:
test_ea.txt  10 kb
aizig.ex4  10 kb