# How to pair Position Buy and Sell for hedging.Please help.

435

I try to pair position Buy and sell by hedging.

position Buy condition

if profit < 0 and not have sell position to square --- open sell and pair it.

if profit < 0 and  have sell position to square and opentime > my expect time --- close this pair(buy and sell)

now my code open and pair just 1 pair.

how can I do it.
Please let me know.

Thank you.

```   void hedge_()
{
for(int i=OrdersTotal()-1;i>=0;i--)
{
bool chk4= OrderSelect(i, SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber() == MagicNumber)
if(OrderSymbol()==Symbol() && OrderProfit()<0)
{
if(OrderType()==OP_BUY)
{
int ttkbuy = OrderTicket();
datetime time_op = OrderOpenTime();
if(Count_Trade_by_side(OP_SELL)<1)
{
bool hed_ = OrderSend(Symbol(),OP_SELL,Lot,Bid,3,0,0,IntegerToString(ttkbuy),MagicNumber,0,clrRed);
if(!hed_){Print("Error Open hedge function "+IntegerToString(GetLastError()));}
else{Print("Open sell hedge function tk "+IntegerToString(ttkbuy));}
}

int a=0,b=OrdersTotal()-1;
if(Count_Trade_by_side(OP_BUY)>=Count_Trade_by_side(OP_SELL))
{
while(a<1)
{
bool chk5= OrderSelect(b, SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber() == MagicNumber)
if(OrderSymbol()==Symbol() && OrderType() ==OP_SELL)
{
if(OrderComment()==IntegerToString(ttkbuy))
{
if(TimeCurrent()-time_op >= 100)// 4hour
{
bool chk2= OrderClose(OrderTicket(),OrderLots(),Ask,5,Pink);
if( chk2){ chk2= OrderClose(ttkbuy,OrderLots(),Bid,5,Pink); }
if(!chk2){Print("Error Close hedge function "+IntegerToString(GetLastError()));}
}
a++;
}

b--;
}

b--;
}
}
}
//----------------------
if(OrderType()==OP_SELL)
{

int ttksell = OrderTicket();
datetime time_op = OrderOpenTime();
if(Count_Trade_by_side(OP_BUY)<1)
{
bool hed_ = OrderSend(Symbol(),OP_BUY,Lot,Ask,3,0,0,IntegerToString(ttksell),MagicNumber,0,clrGreen);
if(!hed_){Print("Error Open hedge function "+IntegerToString(GetLastError()));}
else{Print("Open Buy hedge function tk "+IntegerToString(ttksell));}
}

int a=0,b=OrdersTotal()-1;;
if(Count_Trade_by_side(OP_SELL)>Count_Trade_by_side(OP_BUY))
{
while(a<1)
{
bool chk5= OrderSelect(b, SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber() == MagicNumber)
if(OrderSymbol()==Symbol() && OrderType() ==OP_SELL)
{
if(OrderComment()==IntegerToString(ttksell))
{
if(TimeCurrent()-time_op >= 14400)// 4hour
{
bool chk2= OrderClose(OrderTicket(),OrderLots(),Bid,5,Pink);
if( chk2){ chk2= OrderClose(ttksell,OrderLots(),Ask,5,Pink); }
if(!chk2){Print("Error Close hedge function "+IntegerToString(GetLastError()));}
}
a++;
}

b--;
}

b--;
}
}

}

//---------------------------------
}
}
}```
To add comments, please log in or register