A group of functions intended for trading management.
Trading functions of OrderSend(), OrderClose, OrderCloseBy, OrderDelete, and OrderModify cannot be called from custom indicators.
Trading functions can be used in experts and scripts. Trading functions can be called only if the "Allow live trading" property of this particular expert is checked.
To trade from experts and scripts, only one thread was provided that was launched in the program trade context (context of automated trading from experts and scripts). This is why, if this context is occupied with an expert trading operation, another expert or script cannot call trading functions at that moment due to error 146
(ERR_TRADE_CONTEXT_BUSY). To check whether it is possible to trade or not, one has to use the IsTradeAllowed() function. To make a clear sharing of access to the trading context, one can use a semaphore on the basis of a global variable the value of which must be changed using the GlobalVariableSetOnCondition() function.
EXECUTION ERRORS
Any trading operation (functions
of OrderSend(), OrderClose, OrderCloseBy, OrderDelete or OrderModify) can fail, for a number of reasons, and return either negative ticket number or FALSE. One can find out about the reason for fail by calling of the GetLastError() function. Every error must be processed in a special way. The most common recommendations are given below. Error codes returned from trade server.
Constant Value Description
ERR_NO_ERROR 0 Trade operation succeeded.
ERR_NO_RESULT 1
OrderModify attempts to replace the values already set with the same values. One or more values must be changed, then
modification attempt can be repeated.
ERR_COMMON_ERROR 2
Common error. All attempts to trade must be stopped until reasons are clarified. Restart of operation system and client terminal will possibly be needed. ERR_INVALID_TRADE_PARAMETERS 3 Invalid parameters were
149
passed to the trading function, for example, wrong symbol,
unknown trade operation, negative slippage, non- existing ticket number, etc. The program logic must be changed.
ERR_SERVER_BUSY 4
Trade server is busy. The attempt can be repeated after a rather long period of time (over several minutes).
ERR_OLD_VERSION 5
Old version of the client terminal. The latest version of the client terminal must be installed.
ERR_NO_CONNECTION 6
No connection to the trade server. It is necessary to make sure that connection has not been broken (for example, using the IsConnected
function) and repeat the attempt after a certain period of time (over 5 seconds).
ERR_TOO_FREQUENT_REQUESTS 8
Requests are too frequent. The frequency of
requesting must be reduced, the program logic must be changed. ERR_ACCOUNT_DISABLED 64
The account was disabled. All attempts to trade must be stopped.
ERR_INVALID_ACCOUNT 65
The account number is invalid. All attempts to trade must be stopped.
ERR_TRADE_TIMEOUT 128
Timeout for the trade has been reached. Before retry (at least, in 1-minute time), it is necessary to make sure that trading operation has not really succeeded (a new position has not been opened, or
150
the existing order has not been modified or deleted, or the existing position has not been closed)
ERR_INVALID_PRICE 129
Invalid bid or ask price, perhaps, unnormalized price. After 5-second (or more) delay, it is
necessary to refresh data
using the RefreshRates
function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed.
ERR_INVALID_STOPS 130
Stops are too close, or prices are ill-calculated or unnormalized (or in the open price of a pending order). The attempt can be repeated only if the error occurred due to the price obsolescense. After 5- second (or more) delay, it is necessary to
refresh data using
the RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed.
ERR_INVALID_TRADE_VOLUME 131
Invalid trade volume, error in the volume granularity. All attempts to trade must be stopped, and the program logic must be changed.
ERR_MARKET_CLOSED 132
Market is closed. The attempt can be repeated after a rather long period of time (over several minutes).
ERR_TRADE_DISABLED 133
Trade is disabled. All attempts to trade must be stopped.
151
ERR_NOT_ENOUGH_MONEY 134
Not enough money to make an operation. The trade with the same parameters must not be repeated. After 5-second (or more) delay, the attempt can be repeated with a smaller volume, but it is necessary to make sure that there is enough money to complete the operation.
ERR_PRICE_CHANGED 135
The price has changed. The data can be refreshed without any delay using the RefreshRates function and make a retry.
ERR_OFF_QUOTES 136
No quotes. The broker has not supplied with prices or refused, for any reason (for example, no prices at the session start, unconfirmed prices, fast market). After 5-second (or more) delay, it is necessary to refresh data
using the RefreshRates
function and make a retry.
ERR_REQUOTE 138
The requested price has become out of date or bid and ask prices have been mixed up. The data can be refreshed without any delay using
the RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed.
ERR_ORDER_LOCKED 139
The order has been locked and under processing. All attempts to make trading operations must be stopped, and the program logic must be changed. ERR_LONG_POSITIONS_ONLY_ALLOWED 140 Only buying operation is
152
operation must not be repeated.
ERR_TOO_MANY_REQUESTS 141
Too many requests. The frequency of requesting must be reduced, the program logic must be changed.
142
The order has been enqueued. It is not an error but an interaction code between the client terminal and the trade server. This code can be got rarely, when the disconnection and the reconnection happen during the execution of a trade operation. This code should be processed in the same way as error 128.
143
The order was accepted by the dealer for
execution. It is an
interaction code between the client terminal and the trade server. It can appear for the same reason as code 142. This code should be processed in the same way as error 128.
144
The order was discarded by the client during manual confirmation. It is an interaction code
between the client terminal and the trade server.
ERR_TRADE_MODIFY_DENIED 145
Modifying has been denied since the order is too close to market and locked for possible soon execution. The data can be refreshed after more than 15 seconds using the RefreshRates
function, and a retry can be made.
153
ERR_TRADE_CONTEXT_BUSY 146
The trade thread is busy. Retry only after
the IsTradeContextBusy
function has returned FALSE.
ERR_TRADE_EXPIRATION_DENIED 147
The use of pending order expiration date has been denied by the broker. The operation can only be repeated if the expiration parameter has been zeroized.
ERR_TRADE_TOO_MANY_ORDERS 148
The amount of open and pending orders has reached the limit set by the broker. New open positions and pending orders can be placed only after the existing
positions or orders have been closed or deleted.
ERR_TRADE_HEDGE_PROHIBITED 149
An attempt to open a position opposite to the existing one when
hedging is disabled. First the existing opposite position should be closed, all attempts of such trade operations must be stopped, or the program logic must be changed.
ERR_TRADE_PROHIBITED_BY_FIFO 150
An attempt to close a symbol position contravening the FIFO rule. First earlier existing position(s) should be closed, all attempts of such trade operations must be stopped, or the program logic must be changed.
ORDERCLOSE
bool
OrderClose(
int ticket, double lots, double price, int slippage,
154
Closes opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). Parameters:
ticket - Unique number of the order ticket.
lots - Number of lots.
price - Preferred closing price.
slippage - Value of the maximum price slippage in points.
Color - Color of the closing arrow on the chart. If the parameter is missing or has
CLR_NONE value closing arrow will not be drawn on the chart. Sample: if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderClose(order_id,1,Ask,3,Red); return(0); } ORDERCLOSEBY
bool OrderCloseBy( int ticket, int opposite, color Color=CLR_NONE)
Closes an opened order by another opposite opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters:
ticket - Unique number of the order ticket.
opposite - Unique number of the opposite order ticket.
Color - Color of the closing arrow on the chart. If the parameter is missing or has
CLR_NONE value closing arrow will not be drawn on the chart. Sample: if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderCloseBy(order_id,opposite_id); return(0); } ORDERCLOSEPRICE double OrderClosePrice( )
Returns close price for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Close price for the order ",ticket," = ",OrderClosePrice());
else
Print("OrderSelect failed error code is",GetLastError());
ORDERCLOSETIME
155
Returns close time for the currently selected order. If order close time is not 0 then the order selected and has been closed and retrieved from the account history. Open and pending orders close time is equal to 0.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true) {
datetime ctm=OrderOpenTime();
if(ctm>0) Print("Open time for the order 10 ", ctm); ctm=OrderCloseTime();
if(ctm>0) Print("Close time for the order 10 ", ctm); }
else
Print("OrderSelect failed error code is",GetLastError());
ORDERCOMMENT
string OrderComment( )
Returns comment for the selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
string comment;
if(OrderSelect(10,SELECT_BY_TICKET)==false) {
Print("OrderSelect failed error code is",GetLastError()); return(0); } comment = OrderComment(); // ... ORDERCOMMISSION double OrderCommission( )
Returns calculated commission for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Commission for the order 10 ",OrderCommission()); else
Print("OrderSelect failed error code is",GetLastError());
ORDERDELETE
bool OrderDelete( int ticket, color Color=CLR_NONE)
Deletes previously opened pending order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters:
ticket - Unique number of the order ticket.
Color - Color of the arrow on the chart. If the parameter is missing or has
CLR_NONE value arrow will not be drawn on the chart. Sample:
156 if(Ask>var1) { OrderDelete(order_ticket); return(0); } ORDEREXPIRATION datetime OrderExpiration( )
Returns expiration date for the selected pending order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10, SELECT_BY_TICKET)==true)
Print("Order expiration for the order #10 is ",OrderExpiration()); else
Print("OrderSelect returned error of ",GetLastError());
ORDERLOTS
double OrderLots( )
Returns amount of lots for the selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("lots for the order 10 ",OrderLots()); else
Print("OrderSelect returned error of ",GetLastError());
ORDERMAGICNUMBER
int OrderMagicNumber( )
Returns an identifying (magic) number for the currently selected order. Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Magic number for the order 10 ", OrderMagicNumber()); else
Print("OrderSelect returned error of ",GetLastError());
ORDERMODIFY
bool
OrderModify(
int ticket, double price, double stoploss, double takeprofit,
datetime expiration, color arrow_color=CLR_NONE)
Modification of characteristics for the previously opened position or pending orders. If the function succeeds, the returned value will be TRUE. If the function fails, the
returned value will be FALSE. To get the detailed error information, call GetLastError()
function.
Notes: Open price and expiration time can be changed only for pending orders. If unchanged values are passed as the function parameters, the error 1
(ERR_NO_RESULT) will be generated.
157
a non-zero value is specified in the expiration parameter, the error 147 (ERR_TRADE_EXPIRATION_DENIED) will be generated.
Parameters:
ticket - Unique number of the order ticket.
price - New open price of the pending order.
stoploss - New StopLoss level.
takeprofit - New TakeProfit level.
expiration - Pending order expiration time.
arrow_color - Arrow color for StopLoss/TakeProfit modifications in the chart. If the
parameter is missing or has CLR_NONE value, the arrows will not be shown in the chart.
Sample: if(TrailingStop>0) { OrderSelect(12345,SELECT_BY_TICKET); if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()<Bid-Point*TrailingStop) { OrderModify(OrderTicket(),OrderOpenPrice(),Bid- Point*TrailingStop,OrderTakeProfit(),0,Blue); return(0); } } } ORDEROPENPRICE double OrderOpenPrice( )
Returns open price for the currently selected order.
Order must be first selected by the OrderSelect() function. Sample:
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open price for the order 10 ",OrderOpenPrice()); else
Print("OrderSelect returned the error of ",GetLastError());
ORDEROPENTIME
datetime OrderOpenTime( )
Returns open time for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open time for the order 10 ",OrderOpenTime()); else
Print("OrderSelect returned error of ",GetLastError());
ORDERPRINT
158
Prints information about the selected order in the log in the following format:
ticket number;open time;trade operation;amount of lots;open price;Stop Loss;Take Profit;close time;close price;commission;swap;profit;comment;magic
number;pending order expiration date.
Order must be selected by the OrderSelect() function. Sample:
if(OrderSelect(10, SELECT_BY_TICKET)==true) OrderPrint();
else
Print("OrderSelect failed error code is",GetLastError());
ORDERPROFIT
double OrderProfit( )
Returns the net profit value (without swaps or commissions) for the selected order. For open positions, it is the current unrealized profit. For closed orders, it is the fixed profit. Returns profit for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("Profit for the order 10 ",OrderProfit()); else
Print("OrderSelect returned the error of ",GetLastError());
ORDERSELECT
bool OrderSelect( int index, int select, int pool=MODE_TRADES)
The function selects an order for further processing. It returns TRUE if the function succeeds. It returns FALSE if the function fails. To get the error information, one has to call the GetLastError() function.
The pool parameter is ignored if the order is selected by the ticket number. The ticket number is a unique order identifier. To find out from what list the order has been selected, its close time must be analyzed. If the order close time equals to 0, the order is open or pending and taken from the terminal open positions list. One can distinguish an open position from a pending order by the order type. If the order close time does not equal to 0, the order is a closed order or a deleted pending order and was selected from the terminal history. They also differ from each other by their order types.
Parameters:
index - Order index or order ticket depending on the second parameter. select - Selecting flags. It can be any of the following values:
SELECT_BY_POS - index in the order pool, SELECT_BY_TICKET - index is order ticket.
pool - Optional order pool index. Used when the selected parameter is
SELECT_BY_POS. It can be any of the following values:
MODE_TRADES (default)- order selected from trading pool(opened and pending orders),
MODE_HISTORY - order selected from history pool (closed and canceled order).
Sample:
159 {
Print("order #12470 open price is ", OrderOpenPrice()); Print("order #12470 close price is ", OrderClosePrice()); }
else
Print("OrderSelect returned the error of ",GetLastError());
ORDERSEND
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) The main function used to open a position or place a pending order.
Returns number of the ticket assigned to the order by the trade server or -1 if it fails. To get additional error information, one has to call the GetLastError() function.
Notes:
At opening of a market order (OP_SELL or OP_BUY), only the latest prices of Bid (for selling) or Ask (for buying) can be used as open price. If operation is performed with a security differing from the current one, the MarketInfo() function must be used with MODE_BID or MODE_ASK parameter for the latest quotes for this security to be obtained. Calculated or unnormalized price cannot be applied. If there has not been the requested open price in the price thread or it has not been normalized according to the amount of digits after decimal point, the error 129 (ERR_INVALID_PRICE) will be generated. If the requested open price is fully out of date, the error 138
(ERR_REQUOTE) will be generated independently on the slippage parameter. If the requested price is out of date, but present in the thread, the position will be opened at the current price and only if the current price lies within the range of price+-slippage. StopLoss and TakeProfit levels cannot be too close to the market. The minimal distance of stop levels in points can be obtained using the MarketInfo() function with
MODE_STOPLEVEL parameter. In the case of erroneous or unnormalized stop levels, the error 130 (ERR_INVALID_STOPS) will be generated.
At placing of a pending order, the open price cannot be too close to the market. The minimal distance of the pending price from the current market one in points can be obtained using the MarketInfo() function with the MODE_STOPLEVEL parameter. In case of false open price of a pending order, the error 130 (ERR_INVALID_STOPS) will be generated.
Applying of pending order expiration time can be disabled in some trade servers. In this case, when a non-zero value is specified in the expiration parameter, the error 147 (ERR_TRADE_EXPIRATION_DENIED) will be generated.
On some trade servers, the total amount of open and pending orders can be limited. If this limit has been exceeded, no new position will be opened (or no pending order will be placed) and trade server will return error 148
(ERR_TRADE_TOO_MANY_ORDERS). Parameters:
symbol - Symbol for trading.
160
volume - Number of lots.
price - Preferred price of the trade.
slippage - Maximum price slippage for buy or sell orders.
stoploss - Stop loss level.
takeprofit - Take profit level.
comment - Order comment text. Last part of the comment may be changed by
server.
magic - Order magic number. May be used as user defined identifier.
expiration - Order expiration time (for pending orders only).
arrow_color - Color of the opening arrow on the chart. If parameter is missing or
has CLR_NONE value opening arrow is not drawn on the chart. Sample:
int ticket;
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) {
ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,Ask- 25*Point,Ask+25*Point,"My order #2",16384,0,Green); if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError()); return(0);
} }
ORDERSHISTORYTOTAL
int OrdersHistoryTotal( )
Returns the number of closed orders in the account history loaded into the terminal. The history list size depends on the current settings of the "Account history" tab of the terminal.
Sample:
// retrieving info from trade history int i,hstTotal=OrdersHistoryTotal(); for(i=0;i<hstTotal;i++)
{
//---- check selection result
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) {
Print("Access to history failed with error (",GetLastError(),")");
break; }
// some work with order }
ORDERSTOPLOSS
double OrderStopLoss( )
Returns stop loss value for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
161
if(OrderSelect(ticket,SELECT_BY_POS)==true)
Print("Stop loss value for the order 10 ", OrderStopLoss()); else
Print("OrderSelect failed error code is",GetLastError());
ORDERSTOTAL
int OrdersTotal( )
Returns market and pending orders count. Sample:
int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"\t"); if(handle<0) return(0);
// write header
FileWrite(handle,"#","open price","open time","symbol","lots"); int total=OrdersTotal();
// write open orders
for(int pos=0;pos<total;pos++) { if(OrderSelect(pos,SELECT_BY_POS)==false) continue; FileWrite(handle,OrderTicket(),OrderOpenPrice(),OrderOpenTime(),OrderS ymbol(),OrderLots()); } FileClose(handle); ORDERSWAP double OrderSwap( )
Returns swap value for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(order_id, SELECT_BY_TICKET)==true)
Print("Swap for the order #", order_id, " ",OrderSwap()); else
Print("OrderSelect failed error code is",GetLastError());
ORDERSYMBOL
string OrderSymbol( )
Returns the order symbol value for selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
if(OrderSelect(12, SELECT_BY_POS)==true)
Print("symbol of order #", OrderTicket(), " is ", OrderSymbol()); else
Print("OrderSelect failed error code is",GetLastError());
ORDERTAKEPROFIT
double OrderTakeProfit( )
Returns take profit value for the currently selected order.
Note: The order must be previously selected by the OrderSelect() function. Sample:
162
Print("Order #",OrderTicket()," profit: ", OrderTakeProfit()); else
Print("OrderSelect() returns error - ",GetLastError());
ORDERTICKET
int OrderTicket( )
Returns ticket number for the currently selected order.