Ayuda a la codificación - página 156

 
Marco320:
Estimado MLaden,

Siguiente indi puedo conseguir en el gráfico en mi cuenta real y en la demo de Markets.com (CFD's). O bien hay un problema para conseguirlo en el gráfico en Liquid Markets en la demo. Debido a que Liquid ofrece varias opciones de instrumentos (particularmente Futuros en MT4) me gustaría tenerlo en el gráfico en esa plataforma. ¿Puede usted ver un problema de aumento de esta cuestión, porque no puedo encontrar.

Gracias Marco

Probablemente se deba a que ese indicador es un indicador descompilado. A partir de la build 500 metarader impide que se compilen este tipo de indicadores

 
mladen:
Probablemente se deba a que ese indicador es un indicador descompilado. A partir de la build 500 metarader impide que se compilen este tipo de indicadores

Hola MLaden,

Thx, pero es extraño porque todas las plataformas MT4 de los brokers que uso, son la versión 500.

Saludos Marco

 

Tengo un EA en el que me gustaría utilizar la función de toma de beneficios parcial. He codificado esta función en y una vez que funciona bien, otras veces no lo hace. No he sido capaz de averiguar cuál es el problema...

Estimado Mladen o MrTools, ¿Serían tan amables de mirar el código y darme un consejo sobre cómo podría encontrar el error y resolver la función de toma parcial?

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

//| expert start function |

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

int start()

{

int signal;

CheckOrders();

int numTrades = GetNumTickets();

signal = CheckSignal();

if (signal == OP_BUY)

{

OpenBuy();

lasttime = TimeCurrent();

}

if (signal == OP_SELL)

{

OpenSell();

lasttime = TimeCurrent();

}

return;

}

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

// | Order checking function

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

void CheckOrders()

{

int typ,i,cnt,ticket;

int Mv1 = 0;

int SL1 = 0;

int Mv2 = 0;

int SL2 = 0;

int Mv3 = 0;

int id;

double PipDist, CLots, buy_nextTP, sell_nextTP;

cnt = OrdersTotal();

for (i=cnt-1; i>=0; i--)

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)

{

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

{

typ = OrderType();

//

if (typ == OP_BUY)

{

if (TrailingStopLoss)

{

if (AdjTrailOnAllOrders(2, buy_Trailpips, Magic, typ, Mv1, SL1, Mv2, SL2, Mv3) == false)

Alert("Scalp_RSI: Modifying BUY order failed!");

}

PipDist = (NormalizeDouble(Bid,Digits) - NormalizeDouble(OrderOpenPrice(),Digits));

PipDist = MathFloor(PipDist/myPoint);

}

if (typ == OP_SELL)

{

if(TrailingStopLoss)

{

if (AdjTrailOnAllOrders(2, sell_Trailpips, Magic, typ, Mv1, SL1, Mv2, SL2, Mv3) == false)

Alert("Scalp_RSI: Modifying SELL order failed!");

}

PipDist = (NormalizeDouble(OrderOpenPrice(),Digits) - NormalizeDouble(Ask,Digits));

PipDist = MathFloor(PipDist/myPoint);

}

if (TakePartialProfit == true && PartCloseLots > 0)

{

if (UseMoneyMgmt != 1) Lotsi = Lots;

CLots = NormalizeDouble(Lotsi * PartCloseLots/100,Decimals); // Computing lots to close

if (CLots < MarketInfo(Symbol(), MODE_MINLOT))

CLots = MarketInfo(Symbol(), MODE_MINLOT);

PartialTP(PipDist,OrderTicket(),CLots);

}

}

}

}

}

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

//| PartialTP - i.e. TakePartialProfit function

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

void PartialTP(int pipsval, int ticket, double CLots) //

{

int gle;

int loopcount = 0;

string bER;

string myInfo = "PartialTP";

if(OrderSelect(ticket, SELECT_BY_TICKET)==true)

{

if (OrderType() == OP_BUY)

{

if ((pipsval >= buy_PartialTP) && (pipsval < buy_TakeProfit+1)) //

{

while(true)

{

OrderClose(ticket,CLots,Bid,3,YellowGreen);

gle=GetLastError();

bER=" error="+gle+" "+ErrorDescription(gle);

if(gle==0 || gle==1)

{

logwrite(TradeComment,"CLOSE BUY "+myInfo+ " " + CLots + " at Bid= " + Bid);

buy_PartialTP = buy_TakeProfit+1; //

break;

}

else

{

logwrite(TradeComment,"---ERROR--- CLOSE BUY "+myInfo+bER+ " " + CLots + " at Bid= " + Bid);

RefreshRates();

Sleep(500);

}

loopcount++;

if(loopcount>maxloop)

{

logwrite(TradeComment,"---ERROR--- Giving up on closing BUY order");

return(gle);

}

}

}

}

if (OrderType() == OP_SELL) //

{

if ((pipsval >= sell_PartialTP) && (pipsval < sell_TakeProfit)) //

{

while(true)

{

OrderClose(ticket,CLots,Ask,3,YellowGreen);

gle=GetLastError();

bER=" error="+gle+" "+ErrorDescription(gle);

if(gle==0 || gle==1)

{

logwrite(TradeComment,"CLOSE SELL "+myInfo+ " " + CLots + " at Ask= " + Ask);

sell_PartialTP = sell_TakeProfit; //

break;

}

else

{

logwrite(TradeComment,"---ERROR--- CLOSE SELL "+myInfo+bER+ " " + CLots + " at Ask= " + Ask);

RefreshRates();

Sleep(500);

}

loopcount++;

if(loopcount>maxloop)

{

logwrite(TradeComment,"---ERROR--- Giving up on closing SELL order");

return(gle);

}

}

}

}

} else {

gle=GetLastError();

bER=" Error="+gle+" "+ErrorDescription(gle);

if (gle != 0 || gle!=1)

{

logwrite(TradeComment,"---ERROR--- in selecting order in PartialTP function "+bER);

}

}

}

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

//| Get number of open trades

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

int GetNumTickets()

{

int i;

int typ;

numTickets = 0;

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

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

{

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

{

typ = OrderType();

if (typ == OP_BUY || typ == OP_SELL)

{

numTickets ++;

}

}

}

}

return (numTickets);

}

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

//| Get signal

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

int CheckSignal()

{

return (SignalScalp());

}

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

//| Get scalp signal

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

int SignalScalp()

{

int signal=6; //

if (enable_buy){

// Buy-Condition

{

signal = OP_BUY;

}

}

//

//

if (enable_sell){

// Sell-Condition

{

signal = OP_SELL;

}

}

//

//

//

return(signal);

}

//-----

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

// | Buy Order

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

void OpenBuy()

{

int gle = 0;

int ticket = 0;

double SL = 0;

double TP = 0;

double LotsB = Lots; //GetLots();

int loopcount = 0;

while(true)

{

ticket=OrderSend(Symbol(),OP_BUY,LotsB,Ask,Slippage,0,0,TradeComment,Magic,White);

}

}

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

// | Sell Order

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

void OpenSell()

{

int gle = 0;

int ticket = 0;

double SL = 0;

double TP = 0;

double LotsS = Lots;

int loopcount = 0;

while(true)

{

ticket=OrderSend(Symbol(),OP_SELL,LotsS,Bid,Slippage,0,0,TradeComment,Magic,Red);

}

}

bool AdjTrailOnAllOrders(

int TrailType,

int TrailPips,

int Magic,

int Direction,

int FirstMove,

int FirstStopLoss,

int SecondMove,

int SecondStopLoss,

int ThirdMove)

{

double retValue;

return(retValue);

}

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

//| SetComment function

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

void SetComment(string s) { TradeComment = s; }

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

// | Pip setting

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

double SetPoint()

{

double mPoint;

return(mPoint);

}

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

// | Log write function

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

void logwrite (string filename, string mydata)

{

int myhandle;

}

 
chrisstoff:
Tengo un EA en el que me gustaría utilizar la función de take profit parcial. He codificado esta función y una vez funciona bien, otras veces no. No he podido averiguar cuál es el problema...

Estimado Mladen o MrTools, ¿serían tan amables de mirar el código y aconsejarme cómo puedo encontrar el error y resolver la función de toma parcial?

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

//| expert start function |

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

int start()

{

int signal;

CheckOrders();

int numTrades = GetNumTickets();

signal = CheckSignal();

if (signal == OP_BUY)

{

OpenBuy();

lasttime = TimeCurrent();

}

if (signal == OP_SELL)

{

OpenSell();

lasttime = TimeCurrent();

}

return;

}

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

// | Order checking function

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

void CheckOrders()

{

int typ,i,cnt,ticket;

int Mv1 = 0;

int SL1 = 0;

int Mv2 = 0;

int SL2 = 0;

int Mv3 = 0;

int id;

double PipDist, CLots, buy_nextTP, sell_nextTP;

cnt = OrdersTotal();

for (i=cnt-1; i>=0; i--)

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)

{

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

{

typ = OrderType();

//

if (typ == OP_BUY)

{

if (TrailingStopLoss)

{

if (AdjTrailOnAllOrders(2, buy_Trailpips, Magic, typ, Mv1, SL1, Mv2, SL2, Mv3) == false)

Alert("Scalp_RSI: Modifying BUY order failed!");

}

PipDist = (NormalizeDouble(Bid,Digits) - NormalizeDouble(OrderOpenPrice(),Digits));

PipDist = MathFloor(PipDist/myPoint);

}

if (typ == OP_SELL)

{

if(TrailingStopLoss)

{

if (AdjTrailOnAllOrders(2, sell_Trailpips, Magic, typ, Mv1, SL1, Mv2, SL2, Mv3) == false)

Alert("Scalp_RSI: Modifying SELL order failed!");

}

PipDist = (NormalizeDouble(OrderOpenPrice(),Digits) - NormalizeDouble(Ask,Digits));

PipDist = MathFloor(PipDist/myPoint);

}

if (TakePartialProfit == true && PartCloseLots > 0)

{

if (UseMoneyMgmt != 1) Lotsi = Lots;

CLots = NormalizeDouble(Lotsi * PartCloseLots/100,Decimals); // Computing lots to close

if (CLots < MarketInfo(Symbol(), MODE_MINLOT))

CLots = MarketInfo(Symbol(), MODE_MINLOT);

PartialTP(PipDist,OrderTicket(),CLots);

}

}

}

}

}

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

//| PartialTP - i.e. TakePartialProfit function

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

void PartialTP(int pipsval, int ticket, double CLots) //

{

int gle;

int loopcount = 0;

string bER;

string myInfo = "PartialTP";

if(OrderSelect(ticket, SELECT_BY_TICKET)==true)

{

if (OrderType() == OP_BUY)

{

if ((pipsval >= buy_PartialTP) && (pipsval < buy_TakeProfit+1)) //

{

while(true)

{

OrderClose(ticket,CLots,Bid,3,YellowGreen);

gle=GetLastError();

bER=" error="+gle+" "+ErrorDescription(gle);

if(gle==0 || gle==1)

{

logwrite(TradeComment,"CLOSE BUY "+myInfo+ " " + CLots + " at Bid= " + Bid);

buy_PartialTP = buy_TakeProfit+1; //

break;

}

else

{

logwrite(TradeComment,"---ERROR--- CLOSE BUY "+myInfo+bER+ " " + CLots + " at Bid= " + Bid);

RefreshRates();

Sleep(500);

}

loopcount++;

if(loopcount>maxloop)

{

logwrite(TradeComment,"---ERROR--- Giving up on closing BUY order");

return(gle);

}

}

}

}

if (OrderType() == OP_SELL) //

{

if ((pipsval >= sell_PartialTP) && (pipsval < sell_TakeProfit)) //

{

while(true)

{

OrderClose(ticket,CLots,Ask,3,YellowGreen);

gle=GetLastError();

bER=" error="+gle+" "+ErrorDescription(gle);

if(gle==0 || gle==1)

{

logwrite(TradeComment,"CLOSE SELL "+myInfo+ " " + CLots + " at Ask= " + Ask);

sell_PartialTP = sell_TakeProfit; //

break;

}

else

{

logwrite(TradeComment,"---ERROR--- CLOSE SELL "+myInfo+bER+ " " + CLots + " at Ask= " + Ask);

RefreshRates();

Sleep(500);

}

loopcount++;

if(loopcount>maxloop)

{

logwrite(TradeComment,"---ERROR--- Giving up on closing SELL order");

return(gle);

}

}

}

}

} else {

gle=GetLastError();

bER=" Error="+gle+" "+ErrorDescription(gle);

if (gle != 0 || gle!=1)

{

logwrite(TradeComment,"---ERROR--- in selecting order in PartialTP function "+bER);

}

}

}

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

//| Get number of open trades

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

int GetNumTickets()

{

int i;

int typ;

numTickets = 0;

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

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

{

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

{

typ = OrderType();

if (typ == OP_BUY || typ == OP_SELL)

{

numTickets ++;

}

}

}

}

return (numTickets);

}

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

//| Get signal

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

int CheckSignal()

{

return (SignalScalp());

}

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

//| Get scalp signal

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

int SignalScalp()

{

int signal=6; //

if (enable_buy){

// Buy-Condition

{

signal = OP_BUY;

}

}

//

//

if (enable_sell){

// Sell-Condition

{

signal = OP_SELL;

}

}

//

//

//

return(signal);

}

//-----

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

// | Buy Order

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

void OpenBuy()

{

int gle = 0;

int ticket = 0;

double SL = 0;

double TP = 0;

double LotsB = Lots; //GetLots();

int loopcount = 0;

while(true)

{

ticket=OrderSend(Symbol(),OP_BUY,LotsB,Ask,Slippage,0,0,TradeComment,Magic,White);

}

}

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

// | Sell Order

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

void OpenSell()

{

int gle = 0;

int ticket = 0;

double SL = 0;

double TP = 0;

double LotsS = Lots;

int loopcount = 0;

while(true)

{

ticket=OrderSend(Symbol(),OP_SELL,LotsS,Bid,Slippage,0,0,TradeComment,Magic,Red);

}

}

bool AdjTrailOnAllOrders(

int TrailType,

int TrailPips,

int Magic,

int Direction,

int FirstMove,

int FirstStopLoss,

int SecondMove,

int SecondStopLoss,

int ThirdMove)

{

double retValue;

return(retValue);

}

void SetComment(string s) { TradeComment = s; }

double SetPoint()

{

double mPoint;

return(mPoint);

}

void logwrite (string filename, string mydata)

{

int myhandle;

}

christoff

No puedo ver qué valor estás utilizando para la variable "Decimales", pero probablemente esa sea la causa de tu problema. La parte resultante de la orden tiene que estar de acuerdo con el valor del paso de lote también (lo que significa: si el paso de lote es 0.1 por ejemplo, no puedes intentar cerrar 0.11 lotes). Compruebe cuál es el último error después del cierre parcial que no está teniendo éxito (puede hacerlo simplemente añadiendo un comentario después de las líneas que van como esta :

bER=" error="+gle+""+ErrorDescription(gle);

si (gle>1) Comentario(bER);

ya que la función logwrite del código no está operativa

 

Mladen,

Gracias por la respuesta.

Bueno, he acortado el código porque no hay posibilidad de que un post tenga más de 10.000 caracteres. Así, en el código original la variable Decimals está en el init() como sigue:

LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);

if(LotStep == 0.01) {Decimals = 2;}

if(LotStep == 0.1) {Decimals = 1;}

if(LotStep == 1) {Decimals = 0;}[/PHP]

Yes, logwrite function is not functionable in the code posted, also because of the shortening. Normally it looks like:

[PHP]

void logwrite (string filename, string mydata)

{

int myhandle;

string wcalend=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);

Print(mydata+" "+wcalend);

if(IsTesting()) return(0);

myhandle=FileOpen(Symbol()+"_"+filename, FILE_CSV|FILE_WRITE|FILE_READ, ";");

if(myhandle>0)

{

FileSeek(myhandle,0,SEEK_END);

FileWrite(myhandle, mydata+" "+wcalend);

FileClose(myhandle);

}

}

Por tanto, no creo que el problema surja por la variable Decimales.

 
chrisstoff:
Mladen,

Gracias por la respuesta.

Bueno, he acortado el código porque no hay posibilidad de que un post tenga más de 10.000 caracteres. Así, en el código original la variable Decimals está en el init() como sigue:

LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);

if(LotStep == 0.01) {Decimals = 2;}

if(LotStep == 0.1) {Decimals = 1;}

if(LotStep == 1) {Decimals = 0;}[/PHP]

Yes, logwrite function is not functionable in the code posted, also because of the shortening. Normally it looks like:

[PHP]

void logwrite (string filename, string mydata)

{

int myhandle;

string wcalend=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);

Print(mydata+" "+wcalend);

if(IsTesting()) return(0);

myhandle=FileOpen(Symbol()+"_"+filename, FILE_CSV|FILE_WRITE|FILE_READ, ";");

if(myhandle>0)

{

FileSeek(myhandle,0,SEEK_END);

FileWrite(myhandle, mydata+" "+wcalend);

FileClose(myhandle);

}

}
Entonces, no creo que el problema surja por la variable Decimals.

Christoff

De esta manera la variable Decimals debería estar bien

En cualquier caso, comprueba qué código de error estás obteniendo en un caso de cierre (parcial) de la orden sin éxito

 
mladen:
Veo que no está utilizando el número mágico, por lo que la suposición es que no importa lo que es el número mágico o símbolo. En ese caso primero comprueba si ya hay una orden abierta - así :
if (OrdersTotal()<1)

{

ticket=OrderSend(Symbol(), OP_BUY, lots, Ask, 3, 0, 0);

stop=(Ask-stopsize*Point);

prof=(Ask+profsize*Point);

OrderModify( ticket, OrderOpenPrice(), stop, prof, 0, Blue);

}

Si usted decide utilizar el número mágico y la comprobación del símbolo, entonces es mejor hacer una función que cuente las órdenes abiertas para el símbolo especificado y / o número mágico

Gracias mladen.

if (OrdersTotal()<1

Había resolver mi problema.

Total puede pedir uno, pero quiero que cada par de monedas puede abrir.

Lo siento por entender mal.

Pero me refiero es en cada par ejecutar una orden y parada. Ejemplo:

Ahora abro una orden en EURUSD y ejecuto una orden solamente. Entonces otras divisas también pueden abrir en el mismo tiempo ejecutar una orden . Lo siento con mi pobre Inglés.

-----------------------------------------------------------------

Gracias.

 
hock87:
Gracias mladen.

if (OrdersTotal()<1

Había resolver mi problema.

Total puede pedir uno, pero quiero que cada par de monedas puede abrir.

Lo siento por entender mal.

Pero lo que quiero decir es que en cada par de ejecutar una orden y la parada. Ejemplo:

Ahora abro una orden en EURUSD y ejecuto una orden solamente. Entonces otras divisas también pueden abrir en el mismo tiempo ejecutar una orden . Lo siento con mi pobre Inglés.

-----------------------------------------------------------------

Gracias.

hock87

Añade esto :

int TotalOrders = 0;

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

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

if (OrderSymbol() == Symbol())

TotalOrders++;

}

antes de la línea if (OrdersTotal()<1) y sustituye esa línea por if (TotalOrders<1). De esta manera sólo se permitirá una orden abierta por símbolo

 

Muchas gracias, mladen.

Ahora lo pruebo.

 
hock87:
Gracias mladen.

if (OrdersTotal()<1

Había resolver mi problema.

Total puede pedir uno, pero quiero que cada par de monedas puede abrir.

Lo siento por entender mal.

Pero lo que quiero decir es que en cada par de ejecutar una orden y la parada. Ejemplo:

Ahora abro una orden en EURUSD y ejecuto una orden solamente. Entonces otras divisas también pueden abrir en el mismo tiempo ejecutar una orden . Lo siento con mi pobre Inglés.

-----------------------------------------------------------------

Gracias.

hock87

Por favor, lea el post por encima de su puesto para una solución de ese problema

El código completo para eso es el siguiente :

int TotalOrders = 0;

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

{

if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

if (OrderSymbol() == Symbol())

TotalOrders++;

}

if (TotalOrders<1)

{

ticket=OrderSend(Symbol(), OP_BUY, lots, Ask, 3, 0, 0);

stop=(Ask-stopsize*Point);

prof=(Ask+profsize*Point);

OrderModify( ticket, OrderOpenPrice(), stop, prof, 0, Blue);

}

Razón de la queja: