HELP -simple code for sl , something is not working and I cant figure it it out

 

im trying to code a simple trailing EA, here it is below.


if the trade is a buy it moves the stop loss up and a sell it moves it down.

but something is not working and I cant figure it it out.




//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
//
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+


extern double trail=0.00050;
int i;
double pips;
int ticket;
double pBid;
double ldStopLoss;
double price;


int start()
{ //start of prog


if(OrdersTotal() !=0) // if total orders are not zero
{
int total = OrdersTotal(); // the word total represents total orders
Print ("total orders=", OrdersTotal());
for(i = total - 1; i >= 0; i--)// count each order backwards
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES); //select each order by postiton

if(OrderSymbol() != Symbol()) continue; //if it is not equal to our symbol, skip it
Print ("order=",i);
if((OrderType() == OP_BUY) || (OrderType() == OP_SELL))


//----buy-----

{
if (OrderType() == OP_BUY)
price = MarketInfo(Symbol(), MODE_BID);
ldStopLoss = price + trail;
double ostop = OrderStopLoss();
Print ("buy price=",price);
Print ("buy order-stoploss=",OrderStopLoss());
Print ("buy idstoploss=",ldStopLoss);
{
if (ldStopLoss > ostop)
Print ("buy modify order");
OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,White);
}

}
//---end buy----

//----sell----

{
if (OrderType()==OP_SELL) continue;
price = MarketInfo(Symbol(), MODE_BID);
ldStopLoss = price - trail;
double oostop = OrderStopLoss();
Print ("sell price=",price);
Print ("sell order-stoploss=",OrderStopLoss());
Print ("sell idstoploss=",ldStopLoss);
{
if (ldStopLoss < oostop)
Print ("sell modify order");
OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,White);
}

}
//----end sell----
}
}
}

 

Hi buju

After just a quick look, I think your stop loss calculation is wrong.

For OP_BUY, you have: ldStopLoss = price + trail;

Should be: ldStopLoss = price - trail;

For OP_SELL, you have: ldStopLoss = price - trail;

Should be: ldStopLoss = price + trail;

Cheers

Jellybean

Reason: