Saturday 9 February 2013

MQL4 OrderClose, OrderCloseBy, OrderDelete, OrderModify, OrderSend OrderClose


OrderCloseBy
OrderDelete
OrderModify
OrderSend
Trade Operation (OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP)



OrderClose Closes an open trade with the matching ticket number at the specified price. 
bool OrderClose(int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
Returns TRUE if OrderClose succeeds and the open trade is closed, and FALSE if the OrderClose function fails and order doesn't close. Detailed error information may be retrieved on failure with the GetLastError function.

Parameters:
int ticket    Order ticket number of order to close
double lots   Amount of Lots to close
double price  Requested order closing price
int slippage  Amount of slippage in pips (for 4/2 digit brokers) or pippettes (for 5/3 digit brokers)
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example: Routine to close all orders for all symbols with given Slippage and OrderMagicNumber.

void CloseAll(int Slippage, int MagicNumber) {
bool closed;
for (int i = 0; i < OrdersTotal(); i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    while(IsTradeContextBusy()) Sleep(100);
    RefreshRates();
    if (OrderType() == OP_BUY && MagicNumber == OrderMagicNumber()) {
        closed = OrderClose(OrderTicket(),OrderLots(),
         NormalizeDouble(MarketInfo(OrderSymbol(),
         MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),Slippage,White);
    }
    if (OrderType() == OP_SELL && MagicNumber == OrderMagicNumber()) {
        closed = OrderClose(OrderTicket(),OrderLots(),
         NormalizeDouble(MarketInfo(OrderSymbol(),
         MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),Slippage,White);
    }
}
}






OrderCloseBy Closes an open order by an opposite open order.
bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE)
Returns TRUE if OrderCloseBy succeeds and the open trade is closed, and FALSE if OrderCloseBy fails and the order doesn't close. Detailed error information may be retrieved on failure with the GetLastError function.

Note: lot sizes must be the same for both orders.

Parameters:
int ticket    Order ticket number of order to close
int opposite  Ticket number of the opposite order.
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example:
if (iRSI(Symbol(), 0, 30, PRICE_CLOSE, 0) < 50) {
    if( OrderCloseBy(ticket, opposite, White) == true) {
        return(-1);
    } else {
        Print("OrderCloseBy failed. Ticket #" + ticket + " opposite #" + opposite + "Error# " + GetLastError());
        return(0);
    }
}

OrderDelete Deletes previously opened pending order.
bool OrderDelete(int ticket, color Color=CLR_NONE)
Returns TRUE if OrderDelete succeeds and the order is deleted, otherwise FALSE if OrderDelete fails. Detailed error information may be retrieved on failure with the GetLastError function.

Parameters:
int ticket    Order ticket number of pending order to delete.
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example: Routine to delete all buy stop orders for the current symbol with given OrderMagicNumber.
void DeleteThis_BUYSTOP(int MagicNumber) {
bool deleted;
for (int i = 0; i < OrdersTotal(); i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    while(IsTradeContextBusy()) Sleep(100);
    if (OrderType() == OP_BUYSTOP && MagicNumber == OrderMagicNumber()
     && OrderSymbol() == Symbol() ) {           deleted = OrderDelete(OrderTicket(), CLR_NONE);
         if(deleted == false) {
             Print("Error deleting buy stop order " + OrderTicket() + " Err#:" GetLastError());
         }
    }
} }



OrderModify Modifies a pending order or open trade.
bool OrderModify(int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=CLR_NONE)
Returns TRUE if OrderModify succeeds and the order is modified otherwise FALSE if OrderModify fails. Detailed error information may be retrieved on failure with the GetLastError function.

Note: Price and expiration may only be changed on pending orders.  Error #1 (ERR_NO_RESULT) will be generated if  unchanged values are passed as function parameters. Some trade servers may disable pending order expiration time. If the broker has disabled expiration time, error #147 (ERR_TRADE_EXPIRATION_DENIED) will occur.

Parameters:
int ticket          Order ticket number of pending order to modify.
double price        Requested order price.
double stoploss     Requested stop loss level.
double takeprofit   Requested take profit level (profit target).
datetime expiration Pending order expiration time.
color arrow_color   (Optional) Color to show stoploss/takeprofit modification arrow on the chart. 
                    The default value is CLR_NONE or no arrow drawn.

Example: Function to modify a newly entered MT4 order to add the stoploss and takeprofit fields with a given ticket called OrderModify. This MQL4 function is taken from SnowRoller_1_008.
bool ModifyOrder(int ticket) {
   if(ticket == -1) return(false);
   bool dotp = false;
   double sl = 0.0, tp = 0.0;
   int repeats = 0;
   ordernumber +=1;
   if (MathMod(ordernumber,2) == 0) {
      dotp =true;
   }
   bool result = false;
  
      RefreshRates();
      while(!IsTradeAllowed()) Sleep(100);
      if (OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES) == true) {
         Print("Order Selected " + ticket);
         if(OrderType() == OP_BUY) {
            sl = NormalizeDouble(OrderOpenPrice() - stoploss * Point * NormalizeLots, Digits);
            if (takeprofit > 0 && dotp == true ) {
               tp = NormalizeDouble(takeprofit * Point * NormalizeLots + OrderOpenPrice(), Digits);
            } else {
               tp = 0.0;
            }
         }
         if(OrderType() == OP_SELL) {
            sl = NormalizeDouble(stoploss * Point * NormalizeLots + OrderOpenPrice(), Digits);
            if (takeprofit > 0 && dotp == true) {
               tp = NormalizeDouble(-takeprofit * Point * NormalizeLots + OrderOpenPrice(), Digits);
            } else {
               tp = 0.0;
            }
         }
         Print("minimum: " + MarketInfo(Symbol() , MODE_STOPLEVEL) +   " Order Type: " + OrderType() + " Entry Price: " + OrderOpenPrice() +  " Moving SL to: " + sl + " and TP to " + tp);
         result = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits), sl, tp, OrderExpiration(), CLR_NONE);
         if (result == true) return (true);
      } else
      repeats += 1;
      if (repeats > 5) {
         Print("Unable to select ticket # " + ticket);
         return(false); // failure
      }
}



OrderSend Creates a new order and sends it to the Metatrader broker.
int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)
Returns the ticket number of the order if the OrderSend function succeeds, otherwise returns -1 on failure of the OrderSend function. Detailed error information may be retrieved on failure with the GetLastError function.

Notes
MT4 requires the latest Bid (for OP_SELL orders) or Ask (for OP_BUY orders) for price. Volume is referred to in other functions as Lots. These terms are synonymous.

Use the MarketInfo function to retrieve Bid (MODE_BID) or Ask (MODE_ASK) prices for symbols other than the currently selected symbol. Prices used to open (or close) trades must be normalized using the NormalizeDouble function with Digits as the second parameter.

To reference Digits for other symbols, use the MarketInfo function to retrieve Digits (MODE_DIGITS). Failure to normalize prices will trigger error# 129 (ERR_INVALID_PRICE). Stale quotes will trigger error# 138 (ERR_REQUOTE) independent of the slippage parameter.

Use the RefreshRates function before any OrderSend function call to ensure up-to-date prices are held in the Bid/Ask variables. If price on the broker's server moves since the last variable update, on the MT4 terminal client, but is within the slippage amount entered, the order will be filled, otherwise error# 138 (ERR_REQUOTE) will trigger.

Due to U.S. brokerage rules, the best practice is to enter orders without an attached stoploss or takeprofit, then use the OrderModify function to edit the order and attach a stoploss and takeprofit amount as is shown in the ModifyOrder function example.

StopLoss, TakeProfit, and pending order levels may not be placed closer than the distance indicated by the MarketInfo function with MODE_STOPLEVEL parameter. If stop levels are too close or are not properly normalized, error# 130 (ERR_INVALID_STOPS) will be triggered.

Some brokers have disabled the expiration time on their trade servers. Transmitting a non-zero expiration parameter to a broker with disabled expiration time will lead to error# 147 (ERR_TRADE_EXPIRATION_DENIED).

If your broker limits the total number of pending and open orders and trades, error# 148 (ERR_TRADE_TOO_MANY_ORDERS) may be triggered if your order would exceed the broker's order limit.

Parameters:
string symbol       Trade symbol name.
int cmd             Trade operation type. This may be any trade operation enumeration.
double volume       Amount of Lots for order.
double price        Requested order price.
int slippage        Amount of slippage in pips (for 4/2 digit brokers) or pippettes (for 5/3 digit brokers)   
double stoploss     Requested stop loss level.
double takeprofit   Requested take profit level (profit target).
string comment      (Optional) Comment attached to order. This may be used to differentiate between orders.
                    The default value is NULL.
int magic           (Optional) Magic number attached to order. May be used to differentiate between orders.
                    The defalut value is 0.
datetime expiration (Optional) Pending order expiration time.
                    The default value is 0 (no expiration).
color arrow_color   (Optional) Color to show the opening order arrow on the chart. 
                    The default value is CLR_NONE or no arrow drawn.

Trade Operation Constants used in the OrderSend function.
Constant        Value        Description
OP_BUY          0            Buy order
OP_SELL         1            Sell order
OP_BUYLIMIT     2            Buy limit pending order
OP_SELLLIMIT    3            Sell limit pending order
OP_BUYSTOP      4            Buy stop pending order
OP_SELLSTOP     5            Sell stop pending order


Example: SendTrade function taken from SnowRoller_1_008. This function takes the trade operation as the type parameter, and returns the ticket number if the OrderSend function succeeds, otherwise -1 if OrderSend fails. On failure, use the Print routine with the GetLastError function to return the error number such as:
if(ticket == -1) Print("Error Opening Buy Order: " + GetLastError());

The ticket number returned by the OrderSend function is then sent to the ModifyOrder function (see code) to attach a stoploss and takeprofit via the OrderModify function. Normally, error checking should be done after OrderSend returns a ticket number with -1.
int SendTrade(int type)
{
   bool dotrades = false;
   int expiry = 0;
   color clr = Red;
   bool result = false;
   if (type == OP_BUY || type == OP_BUYSTOP) clr = Green;
   int ticket = -1;
  
   while(!IsTradeAllowed()) Sleep(100);
   RefreshRates();
   MaxEquity = GlobalVariableGet("SRMaxEquity");
   if (OpenTrades >= MaxTradesThis) return;
  
   if ((type == OP_BUY )) {
         if(Position == 0) {
            initialAnchor = Close[0];
         }
         if(Close[0] < initialAnchor - MaxNegExcursion * Point * NormalizeLots) return;
         if(Ask - Bid > MaxSpread * Point * NormalizeLots) return;
         ticket = OrderSend(Symbol(), type, (MinLotSize * lotsize * LotMultiplier), NormalizeDouble(Ask,Digits), Slippage * NormalizeLots, 0, 0, comment, MN, expiry, clr);
         return(ticket);
   }
   if ((type == OP_SELL)) {
         if(Position == 0) {
            initialAnchor = Close[0];
         }
         if(Close[0] > initialAnchor + MaxNegExcursion * Point * NormalizeLots) return;
         if(Ask - Bid > MaxSpread * Point * NormalizeLots) return;
         ticket = OrderSend(Symbol(), type, (MinLotSize * lotsize * LotMultiplier), NormalizeDouble(Bid,Digits), Slippage * NormalizeLots, 0, 0, comment, MN, expiry, clr);
         return(ticket);
   }
   return(-1);
}

No comments:

Post a Comment