Ayuda con la codificación... ¿Cómo puedo hacer que el indicador filtre en lugar de alertar? - página 8

 

¡Eres el hombre!

Así que .... vamos a ver si entiendo esto correctamente ...

si quisiera cerrar posiciones basadas en el cruce posterior de una media móvil todo lo que tendría que codificar es esto....

if(currentlong>minorts) {CloseOrder(OP_SELL); // Cerrar todas las órdenes de venta}

donde currentlong es la 20ema y minorts es la 150ema por lo que la posición abierta habría sido o ES una posición corta que ha seguido su curso y ahora la 20ema se está moviendo por encima de la 150ema que es la señal de cierre para la operación corta.

y...

if (currentlong<minorts) {CloseOrder(OP_BUY); // Cerrar todas las órdenes de compra}

donde currentlong es la 20ema y minorts es la 150ema por lo que la posición abierta habría sido o ES un largo que ha seguido su curso y ahora la 20ema se está moviendo por debajo de la 150ema que es la señal de cierre para la operación larga.

Así que podría poner estas dos líneas

if (currentlong<minorts) {CloseOrder(OP_BUY); // Cerrar todas las órdenes de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL); // Cerrar todas las órdenes de venta}

justo después del código de entrada y antes de todas las demás cosas de cierre y trailing stop así? y funcionará?

if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("SELL order opened : ",OrderOpenPrice());

}

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

return(0);

}

}

//+---------end of order entry-------------------------+

//+------close on moving average cross-----------------+

if(currentlong<minorts) {CloseOrder(OP_BUY);} // Close all buy orders}

if(currentlong>minorts) {CloseOrder(OP_SELL);} // Close all sell orders}

//+--------end of close on moving average cross--------+

//+-------------------------Trailing Stop Code------------------------------------+

for(cnt=0;cnt<total;cnt++) {

OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) {

if(OrderType()==OP_BUY){

el compilador dice esto:

')' - recuento de parámetros erróneo C:\NFicheros de programa\NInterbank FX Trader 4-live mini\Nexperts\whatever.mq4 (85, 43)

')' - parámetros incorrectos cuentan C:\gram Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (86, 44)

no le gustan esas líneas. Siento que no me estoy comunicando muy bien.

 

esto es interesante de repente mi función de búsqueda en el metaeditor funciona?

bool OrderCloseBy( int ticket, int opposite, color Color=CLR_NONE)

Cierra una orden abierta por otra orden abierta opuesta. Si la función tiene éxito, el valor de retorno es verdadero. Si la función falla, el valor de retorno es falso. Para obtener la información detallada del error, llame a GetLastError().

Parámetros:

ticket - Número único del ticket del pedido.

opposite - Número único del ticket de pedido opuesto.

Color - Color de la flecha de cierre en el gráfico. Si el parámetro falta o tiene el valor CLR_NONE la flecha de cierre no se dibujará en el gráfico.

Ejemplo:

if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}

así que estoy visualizando algo como esto...

if(currentlong<minorts)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}[/PHP]

thing is this doesn't distinguish what kind of position I'm into first, long or short. So if I put the opposite side of this with it...like this...

[PHP] if(currentlong>minorts)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}

juntos cerrarían todo no? tiene que haber más...me siento tan frustrado como un niño que no puede hablar todavía para comunicar frases completas, cuando TENGO ideas completas dentro de mí que no puedo sacar.

 
elihayun:
Me olvido de este
void CloseOrder(int ticket,double numLots,double close_price)

{

int CloseCnt, err;

// try to close 3 Times

CloseCnt = 0;

color clr = Violet;

if (OrderType() == OP_SELL)

clr = Orange;

while (CloseCnt < 3)

{

if (OrderClose(ticket,numLots,close_price,Slippage,clr))

{

CloseCnt = 3;

}

else

{

err=GetLastError();

Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));

if (err > 0) CloseCnt++;

}

}

}

[/PHP]

and dont forget to add this line after #property link

[PHP]#property link "http://www.elihayun.com"

#include

¿Qué hace esto? ¿Es algo más que tengo que descargar para tenerlo disponible para ser llamado? Quiero entender cómo esto hace lo que hace, cómo distingue las posiciones largas de las cortas. Quiero aprender.

 
Aaragorn:
¡U da man!

Así que .... a ver si lo entiendo bien...

Así que podría poner estas dos líneas

if (currentlong<minorts) {CloseOrder(OP_BUY); // Cerrar todas las órdenes de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL); // Cerrar todas las órdenes de venta}

//+------close on moving average cross-----------------+

if(currentlong<minorts) {CloseOrder(OP_BUY);} //Cierre todas las órdenes de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL);} // Cierra todas las órdenes de venta}

if(OrderType()==OP_BUY){[/PHP]

el compilador dice esto

')' - recuento de parámetros erróneo C:\NFicheros de programa\NInterbank FX Trader 4-live mini\Nexperts\whatever.mq4 (85, 43)

')' - parámetros erróneos cuentan C:\gram Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (86, 44)

no le gustan esas líneas. No siento que me esté comunicando muy bien.

Tienes que llamar a CloseOrders con s al final no a CloseOrder (que cierra sólo una orden)

 
Aaragorn:
¿Qué hace esto? ¿Es algo más que tengo que descargar para tenerlo disponible para ser llamado? Quiero entender cómo esto hace lo que hace, cómo distingue las posiciones largas de las cortas. Quiero aprender.

Es parte de MQL4 y contiene la función ErrorDescription

 
elihayun:
Es parte de MQL4 y contiene la función ErrorDescription

ok Necesito un código que me permita cerrar en base al cruce de medias móviles.

 

Este trozo de código debería ponerte en marcha...

Por supuesto, tendrá que modificarlo para adaptarlo a sus propias necesidades. Sin embargo, esto debería proporcionarle un punto de partida. Esta rutina utiliza la línea SMA1 como trailing stop. Así que tome esta idea y vea lo que puede hacer con ella.

//these two lines within start()

SMA1 = iMA(NULL,TimePeriod,SlowPeriod,0,SlowMode,SlowPrice,1);

TrailingAlls(TrailStart, SMA1);

// trailing routine using the value of SMA1

void TrailingAlls(int start, double currvalue)

{

int profit;

double stoptrade;

double stopcal;

// if(stop==0) return;

int trade;

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

{

if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

continue;

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

{

if(OrderType()==OP_BUY)

{

profit=NormalizeDouble((Bid-OrderOpenPrice())/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Bid-(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);

}//Long

if(OrderType()==OP_SELL)

{

profit=NormalizeDouble((OrderOpenPrice()-Ask)/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Ask+(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);

}//Shrt

}

}//for

}

 

un trailing stop de cierre es posiblemente útil si puedo averiguar esto primero....

este snippet que me dio elihayun creo que podría funcionar si alguien puede averiguar cómo conseguir que responda al ma backcross y en la dirección correcta. Estoy confundido con el op_buy y op_sell cual es cual. y cual usar para cerrar posiciones largas y cual usar para cerrar posiciones cortas.

//+------close on moving average cross-----------------+

void CloseOrders(int op)

{

int tik[30], t = 0;

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

if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){

if(OrderSymbol()==Symbol() && MagicNum==OrderMagicNumber() && OrderType() == op){

tik[t] = OrderTicket(); t++;

}

}

}

for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

CloseOrder(tik, OrderLots(), prc);

}

}

}

//+--------end of close on moving average cross--------+[/PHP]

I think I see that at this point in the code it has selected the orders by ticket and it's figuring out to set the close price based on the bid or the ask. So I'm not sure which is which for long or short positions. If the ticket is a long position that means it was opened at the ask price right? so it should close on the bid price? so this snippet is saying use the bid price to close so I assume that's for a long position. THEN it asks the

if (op == OP_SELL) prc = Ask;

so I assume this is the first place in this code where we now know if we are looking at a long or a short position ticket.

Then it moves immediately to close. But if I can put my closing criteria in here BEFORE it does that???

here it is as I received it...

for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

CloseOrder(tik, OrderLots(), prc);

}[/PHP]

so what I'm thinking is that this is the place in the code where I should insert the moving average criteria to trigger the close for long or short positions. Something like this...

[PHP]for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

if (prc == Bid && currentlong minorts);

CloseOrder(tik, OrderLots(), prc);

}

Will this do it? I think it might if I understand correctly..

Please tell me coders if this is correct??

I think this connects the direction of the moving average cross to the type of position that the ticket is identifed as being.

if the bid is to close long positions so we know the ticket is for a long position then it can close long positions if the currentlongema < minortsEMA because it knows that the ticket is for a long position and the 20ema has moved below the 150ema.

If the ask is for closing short positions and the ticket is identified as a short position because it wants to close at the ask price and the currentlongEMA has moved above the minortsEMA because it knows the ticket is for a short position and the 20ema has moved above the 150ema.

if that is correct will adding this line to the code,

if (prc == Bid && currentlong minorts)

stop it from closing UNLESS each ticket fits this criteria?

...that for the long position the 20ema150ema?

if that is ok then the logic for deciding to close long or short based on the emacrossback is ok and it's worth fixing these errors

I get these errors from the compiler...

[PHP]Compiling 'whatever.mq4'...

'(' - function definition unexpected C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (85, 17)

'MagicNum' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (90, 40)

'op' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (90, 87)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 13)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 17)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 37)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (96, 18)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (98, 22)

'op' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (100, 14)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (102, 21)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 5)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 5)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 11)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 11)

'total' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 15)

'total' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 15)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 21)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 21)

'{' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 28)

'i' - variable is already defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (135, 11)

'}' - unbalanced parentheses C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (165, 1)

16 error(s), 5 warning(s)

 

Una sugerencia a todos los miembros, no utilicen rutinas de "cuenta atrás" para cerrar las operaciones. Por ejemplo, no utilice algo como esto

for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Oferta;

if (op = OP_SELL) prc = Ask;

CloseOrder(tik, OrderLots(), prc);

}

Si está usando múltiples órdenes, no cerrará la última orden. Utilice una rutina de "cuenta atrás". Aquí está mi discusión con los desarrolladores de Metaquotes cuando me topé por primera vez con este irritante "bug".

http://www.metaquotes.net/forum/2018/

 
Maji:
Este trozo de código debería ponerte en marcha...

Por supuesto, tendrá que modificarlo para adaptarlo a sus propias necesidades. Sin embargo, esto debería proporcionarle un punto de partida. Esta rutina utiliza la línea SMA1 como trailing stop. Así que tome esta idea y vea lo que puede hacer con ella.

//these two lines within start()

SMA1 = iMA(NULL,TimePeriod,SlowPeriod,0,SlowMode,SlowPrice,1);

TrailingAlls(TrailStart, SMA1);

// trailing routine using the value of SMA1

void TrailingAlls(int start, double currvalue)

{

int profit;

double stoptrade;

double stopcal;

// if(stop==0) return;

int trade;

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

{

if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

continue;

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

{

if(OrderType()==OP_BUY)

{

profit=NormalizeDouble((Bid-OrderOpenPrice())/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Bid-(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);

}//Long

if(OrderType()==OP_SELL)

{

profit=NormalizeDouble((OrderOpenPrice()-Ask)/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Ask+(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);

}//Shrt

}

}//for

}

Muchas gracias. Estoy deseando diseccionar esto y ver lo que puedo hacer de él ...

la razón por la que quiero conseguir el emacrossback trabajando primero es que básicamente será mi stoploss y mi estrategia de salida por defecto.

Una vez que eso funcione entonces añadiré cosas como esta para aumentar la rentabilidad. Pero como no puedo tener un stop loss sin estropearlo y como no estoy dispuesto a permitir parámetros de stop loss enormes quiero conseguir que el cierre de la media móvil crossback funcione primero. Si tienes la oportunidad de verificar lo que he hecho hasta ahora con el cierre cruzado te lo agradecería.

Razón de la queja: