// YOUR CODE HERE!
extern double TrailingStop = 100;
int MagicNumber = 101090;
//+------------------------------------------------------------------+
int start()
{
int cnt,total;
total = OrdersTotal();
// YOUR CODE HERE!
for(cnt=0;cnt
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) //<-- Long position is opened
{
TrailOrder(OrderType()); return(0); //<-- Trailling the order
}
if(OrderType()==OP_SELL) //<-- Go to short position
{
TrailOrder(OrderType()); return(0); //<-- Trailling the order
}
}
}
return(0);
}
//+------------------------------------------------------------------+
void TrailOrder(int type)
{
if(TrailingStop>0)
{
if(OrderMagicNumber() == MagicNumber)
{
if(type==OP_BUY)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-
Point*TrailingStop,OrderTakeProfit(),0,Green);
}
}
}
if(type==OP_SELL)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) ||
(OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProf
it(),0,Red);
}
}
}
}
}
}
In the code above, we are trailing all the opened positions using thefunction
TrailOrder().
It will go through all the opened positions using a loop that starts from 0 and counts orders returned by OrdersTotal() function.To be certain that we are working with the order of current chart, we will check the Symbol against the selected OrderSymbol. Then, we will call the TrailOrder(), which takes only one parameter; the type of order: OP_SELL or OP_BUY.
TrailOrder() function:
This is the function that handles the Trailing Stop for us. There are two types of orders:
Buy order:
In the case of a Buy order, we check that the profit (current Bid price minus the open price) is greater than the Trailing Stop value that we have set (or the user set). We also modify the order to new Stop Loss level, which is equal to the current Bid price minus the Trailing Stop value.
Sell order:
In the case of Sell order, we check that the profit (the open price minus current Ask price) is greater than the Trailing Stop value that we have set (or the user set). We also modify the order to new Stop Loss level which is equal to the current Ask price plus the Trailing Stop value.
No comments:
Post a Comment