Navigation:Home > Content >

Trading.mq4

Time: 2016-08-19 | Download file:Trading.mq4

//+------------------------------------------------------------------+
//|                                                      Trading.mq4 |
//|                          Copyright © 2008, Empryean Software Ltd |
//|                                      http://finance.empryean.com |
//|                    Tinashe B Chipomho ([email protected])|
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, Empryean Software Ltd"
#property link      "http://finance.empryean.com"
#property library

#include 
#include 
#include 
#include 

string OrderType2String(int type){
  if (type==OP_BUY)
    return ("BUY");
  else if (type==OP_BUYLIMIT)
    return ("BUY LIMIT");
  else if (type==OP_BUYSTOP)
    return ("BUY STOP");
  else if (type==OP_SELL)
    return ("SELL");
  else if (type==OP_SELLLIMIT)
    return ("SELL LIMIT");
  else if (type==OP_SELLSTOP)
    return ("SELL STOP");
  return ("Unknown Order Type");  
}


/////////////////////////////////////////////////////////////////////////////////
// int _IsTradeAllowed( int MaxWaiting_sec = 30 )
//
// the function checks the trade context status. Return codes:
//  1 - trade context is free, trade allowed
//  0 - trade context was busy, but became free. Trade is allowed only after 
//      the market info has been refreshed.
// -1 - trade context is busy, waiting interrupted by the user (expert was removed from 
//      the chart, terminal was shut down, the chart period and/or symbol was changed, etc.)
// -2 - trade context is busy, the waiting limit is reached (MaxWaiting_sec). 
//      Possibly, the expert is not allowed to trade (checkbox "Allow live trading" 
//      in the expert settings).
//
// MaxWaiting_sec - time (in seconds) within which the function will wait 
// until the trade context is free (if it is busy). By default,30.
/////////////////////////////////////////////////////////////////////////////////
int _IsTradeAllowed(int MaxWaiting_sec = 30){
  // check whether the trade context is free
  if(!IsTradeAllowed()){
    int StartWaitingTime = GetTickCount();
    LogWarn("Trade context is busy! Wait until it is free...");
    // infinite loop
    while(true){
      // if the expert was terminated by the user, stop operation
      if(IsStopped()){ 
        LogWarn("The expert was terminated by the user!"); 
        return(-1); 
      }
      // if the waiting time exceeds the time specified in the 
      // MaxWaiting_sec variable, stop operation, as well
      if(GetTickCount() - StartWaitingTime > MaxWaiting_sec * 1000){
        LogWarn("The waiting limit exceeded (" + MaxWaiting_sec + " ???.)!");
        return(-2);
      }
      
      // if the trade context has become free,
      if(IsTradeAllowed()){
        LogWarn("Trade context has become free!");
        return(0);
      }
      // if no loop breaking condition has been met, "wait" for 0.1 
      // second and then restart checking            
      Sleep(100);
    }
  }
  else
   return(1);
}

int MoveToBreakEven(int ticket, double openprice, double takeprofit){
  int TradeAllow = _IsTradeAllowed();
  if (TradeAllow >= 0){
    if(TradeAllow == 0)
      RefreshRates();
      
    TradeAllow = _IsTradeAllowed();
    if (TradeAllow==0)
      RefreshRates();
    return ( OrderModify(ticket,openprice,openprice,takeprofit,0) );
  }  
  return (-1);
}


int PartiallyClose(int type,int ticket, double Lots, double openprice, double takeprofit, int Slippage=3){
  int TradeAllow = _IsTradeAllowed();
  
  double closeprice = 0.0;
    
  if (TradeAllow >= 0){

    if(TradeAllow == 0)
      RefreshRates();
      
    TradeAllow = _IsTradeAllowed();
    if (TradeAllow==0)
      RefreshRates();

    if (type==OP_BUY)
      closeprice=Bid;
    else if (type==OP_SELL)            
      closeprice=Ask;
      
    if (OrderClose(ticket,Lots,closeprice,Slippage)!=true)
      LogFatal(OrderType2String(type)+" Failed to close an open order: "+ ErrorDescription(GetLastError()));

     return (0);              
  }  
  return (-1);
}

int CreateOrder(int type,  double lots, double price,
                double stoploss, double takeprofit,
                string comment, int magicnumber,
                int slippage=3,datetime expiration=0){
                
  int digits = MarketInfo(Symbol(), MODE_DIGITS);

  int ticket = -1;
  int err=0;
  price = NormalizeDouble(price, digits);
  stoploss = NormalizeDouble(stoploss, digits);
  takeprofit = NormalizeDouble(takeprofit, digits);
 
  if (!IsConnected()){
    LogWarn("CreateOrder(): Not Connected.");
    return (-1);
  }
  
  if (IsStopped()){
    LogWarn("CreateOrder(): Stopped.");
    return (-1);
  }

  
  // check whether trade context is free
  int TradeAllow = _IsTradeAllowed();
  if(TradeAllow < 0){ 
    return(-1); 
  }
    
  if(TradeAllow == 0){
    RefreshRates();
  }
 
  LogInfo("Opening "+OrderType2String(type)+" Order: Price["+price+"] StopLoss["+stoploss+"] TakeProfit["+takeprofit+"]");
  ticket = OrderSend(Symbol(), type, lots, price, slippage, stoploss,
                     takeprofit, comment, magicnumber, expiration);
  err=GetLastError();
  if (err!=0){
    LogWarn(""+OrderType2String(type)+" Failed to create "+OrderType2String(type)+" "+ err+" "+ ErrorDescription(err));
  }                  
                    
  return (ticket);
                
}

bool HasOpenOrder(int type, string symbol, int mn){
  int i = OrdersTotal()-1;
  for(; i>=0;i--){
    if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)!=true)   
      continue;
    
    if (OrderType()!=type)
      continue;
      
    if (OrderSymbol()!= symbol)
      continue;    

    if (OrderMagicNumber()!= mn)
      continue;    
  
    if( (OrderType()==OP_BUYLIMIT) || (OrderType()==OP_SELLLIMIT) ||
        (OrderType()==OP_BUYSTOP) || (OrderType()==OP_SELLSTOP))    
      continue;
      
    if (OrderType()==type)
      return (true);
     
  }
  return (false);
}

void CloseOrders(int type, int mn, string symbol, double slippage){
  int i = OrdersTotal()-1;
  for(; i>=0;i--){
    if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)!=true)   
      continue;
    
    if (OrderType()!=type)
      continue;
      
    if (OrderSymbol()!= symbol)
      continue;    
  
    if (OrderMagicNumber()!= mn)
      continue;    
      
    if( (OrderType()==OP_BUYLIMIT) || (OrderType()==OP_SELLLIMIT) ||
        (OrderType()==OP_BUYSTOP) || (OrderType()==OP_SELLSTOP))    
      continue;
      
     
    LogDebug("Closing Order "+ OrderTicket() +" Profit ["+OrderProfit()+"]");  
    PartiallyClose(type,OrderTicket(),OrderLots(), OrderOpenPrice(), OrderTakeProfit(),slippage);
  }
}

void DeletePendingOrders(int mn, string symbol){
  int i = OrdersTotal()-1;
  for(; i>=0;i--){
    if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)!=true)   
      continue;
    
    if (OrderSymbol()!= symbol)
      continue;    

    if (OrderMagicNumber()!= mn)
      continue;    
  
    if( (OrderType()!=OP_BUYLIMIT) && (OrderType()!=OP_SELLLIMIT) &&
        (OrderType()!=OP_BUYSTOP) && (OrderType()!=OP_SELLSTOP))    
      continue;
      
    if ((OrderType()==OP_BUY)||(OrderType()==OP_SELL))      
      continue;
     
    LogDebug("Deleting Pending Order  "+ OrderTicket() +" Opened at "+ OrderOpenTime() +" Open Price "+ OrderOpenPrice());  
    if (!OrderDelete(OrderTicket()))
      LogFatal("Failed to delete Pending Order "+ OrderType2String(OrderType()) +" "+ ErrorDescription(GetLastError()));  
  }
  
}

bool HasBuyOrder(double price,int magicnumber,int slippage){
  int total = OrdersTotal();
  double min = slippage * Point;
  
  for(int i=0; i=price)){
          return (true);
        }
      }
    }
  }
  return (false);
}

bool HasSellOrder(double price,int magicnumber,int slippage){
  int total = OrdersTotal();
  double min = slippage * Point;
  for(int i=0; i=price)){
          return (true);
        }
      }
    }
  }
  return (false);
}

bool HasClosedSellOrder(double price,int magicnumber,int slippage){
  int total = OrdersHistoryTotal();
  double min = slippage * Point;
  for(int i=0; i=price)){
          return (true);
        }
      }
    }
  }
  return (false);
}

bool HasClosedBuyOrder(double price,int magicnumber,int slippage){
  int total = OrdersHistoryTotal();
  double min = slippage * Point;
  
  for(int i=0; i=price)){
          return (true);
        }
      }
    }
  }
  return (false);
}


bool ModifyOrder(int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=CLR_NONE){
  int digits = MarketInfo(Symbol(), MODE_DIGITS);

  bool result = false;
  int err=0;
  price = NormalizeDouble(price, digits);
  stoploss = NormalizeDouble(stoploss, digits);
  takeprofit = NormalizeDouble(takeprofit, digits);
 
  if (!IsConnected()){
    LogWarn("ModifyOrder(): Not Connected.");
    return (-1);
  }
  
  if (IsStopped()){
    LogWarn("ModifyOrder(): Stopped.");
    return (-1);
  }

  
  // check whether trade context is free
  int TradeAllow = _IsTradeAllowed();
  if(TradeAllow < 0){ 
    return(-1); 
  }
    
  if(TradeAllow == 0){
    RefreshRates();
  }
 
  LogInfo("Modifying Order: Ticket["+ticket+"] Price["+price+"] StopLoss["+stoploss+"] TakeProfit["+takeprofit+"]");
  result = OrderModify(ticket,price,stoploss,takeprofit,expiration,arrow_color);
  err=GetLastError();
  if (err!=0){
    LogWarn(" Failed to modify order  "+ err+" "+ ErrorDescription(err));
  }                  
                    
  return (result);
}


void TrackOrders(int stopmode, int magicnumber, string symbol, double params[]){
  switch(stopmode){
    case TRAILING_STOP_SIMPLE:
      SimpleTrailingStop(magicnumber,symbol,params);
      return;
    case TRAILING_STOP_NONE:
    default:
      return;
  }
}


/**
 * For simple trailing stop mode, the first parameter
 * in the params array is the trailing stop value.
 */
void SimpleTrailingStop(int magicnumber, string symbol, double params[]){
  //we wont do anything if we dont have a trailing stop value.
  if (ArraySize(params)<=0)
    return;
    
  int total = OrdersTotal()-1;
  double ts = params[0];
  
  for(;total>=0;total--){
    if (OrderSelect(total,SELECT_BY_POS,MODE_TRADES)!=true)
      continue;
    if (OrderSymbol()!= Symbol())  
      continue;
    if (OrderMagicNumber()!= magicnumber)
      continue;

    if (OrderType()==OP_BUY){
      if ((Bid-OrderOpenPrice()>Point*ts) &&
          (OrderStopLoss()Point*ts) &&
          (OrderStopLoss()>Ask+Point*ts) ){
        if (!ModifyOrder(OrderTicket(),OrderOpenPrice(),Ask+Point*ts,OrderTakeProfit(),0,Blue)){
          LogError("SimpleTrailingStop: SELL Failed to modify order Ticket="+OrderTicket()+", OrderOpenPrice="+OrderOpenPrice()+", OrderProfit="+OrderProfit()+", OrderComment["+OrderComment()+"]");
        }
      }
    }  
    
  }
}

Recommend