彻底平仓的一个写法
bool CloseOrders(int orderMode,string myType){
int OrderCount=0, gle=0;
int cnt,mode;
int TicketArray;
double ClosePrice=0;
string stringOrderMode;
if (orderMode==OP_BUY)stringOrderMode="BUY";
if (orderMode==OP_SELL) stringOrderMode="SELL";
// first, we retrieve all ticket IDs for existing orders to close out
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
mode=OrderType();
if (isOrder(OrderSymbol(), OrderMagicNumber(), OrderComment(), myType))
{
if (mode==orderMode)
{
TicketArray=OrderTicket();
Print("OrderCount: ",OrderCount,", Ticket: ",TicketArray," Selected for closure.");
OrderCount++;
}
}
}
else
{
gle=GetLastError();
Print("Error selecting an order in CloseAllOrders!!! Error #",gle,": ",ErrorDescription(gle));
return(false); //Since returning false, the caller will retry this function again
}
}
// second, we close out all applicable orders in the array.this two step method prevents problems closing out all orders successfully at once.
int retries=0;
while(retries<20)
{
for(cnt=0;cnt<OrderCount;cnt++)
{
if (TicketArray>0)
{
if (OrderSelect(TicketArray, SELECT_BY_TICKET, MODE_TRADES))
{
mode=OrderType();
GetTradeContext(); RefreshRates();
if (mode==OP_BUY)ClosePrice=NormalizeDouble(Bid,Digits);
if (mode==OP_SELL) ClosePrice=NormalizeDouble(Ask,Digits);
if (mode == (orderMode+2) || mode == (orderMode+4))
{
if (OrderDelete(OrderTicket()))
{
TicketArray=0;
}
else
{
gle=GetLastError();
Print("Error closing pending order #",TicketArray,": Error #",gle,": ",ErrorDescription(gle));
}
}
else
{
if (CloseOrder(OrderTicket(), OrderLots(), OrderType()))
{
TicketArray=0;
}
else
{
gle=GetLastError();
Print("Error closing order #",TicketArray,": Error #",gle,": ",ErrorDescription(gle));
}
}
}
else
{
gle=GetLastError();
Print("Error selecting order #",TicketArray,": Error #",gle,": ",ErrorDescription(gle));
}
}
}
retries++;
}
bool CloseAllSuccess=true;
for(cnt=0;cnt<OrderCount;cnt++)
{
if (TicketArray>0)
{
CloseAllSuccess=false;
Alert("Could not close ticket #",TicketArray,"! Will keep retrying.");
}
}
if(CloseAllSuccess)
{
return(true);
}
else
{
Print("There was a critical error closing one or more ",stringOrderMode," orders when trying to CLOSE ALL!");
return(false); //Since returning false, the caller will retry this function again
}
}
页:
[1]