brokerCommand (int Command, int Parameter): var

brokerCommand (int Command, string Text)

brokerCommand (int Command, var* Parameters)

Sets various broker plugin parameters or retrieves asset specific data for special purposes in a script. The functions can be optionally provided by the broker plugin; they return 0 when they are not supported or no broker connection is established. The number and types of parameters depend on Command. User specific commands to the broker API can be added.The following commands are predefined:
 
Command
Parameter
Internal
Returns
GET_TIME 0 Last incoming quote time in the server time zone, OLE DATE format.
GET_DIGITS Symbol   Number of relevant digits after decimal point in the price quotes.
GET_STOPLEVEL Symbol   The 'safety net' stop level of the last order (non-NFA accounts only).
GET_TRADEALLOWED Symbol   Trade is allowed for the asset.
GET_MINLOT Symbol   Minimum permitted amount of a lot.
GET_LOTSTEP Symbol   Step for changing lots.
GET_MAXLOT Symbol   Maximum permitted amount of a lot.
GET_MARGININIT Symbol   Initial margin requirements for 1 lot.

GET_MARGINMAINTAIN

Symbol   Margin to maintain open positions calculated for 1 lot.
GET_MARGINHEDGED Symbol   Hedged margin calculated for 1 lot.
GET_COMPLIANCE 0   Account restrictions, a combination of the following flags: 1 - no partial closing; 2 - no hedging; 4 - FIFO compliance; 8 - no closing of trades; 15 - full NFA compliant account.
GET_SERVERSTATE 0   State of the broker server: 1 - server connected; 2 - server disconnected; 3 - server was temporarily disconnected since the last GET_SERVERSTATE command.
GET_NTRADES 0   Number of all open trades in this account.
GET_POSITION Symbol Net open units of the given symbol; negative values for short positions.
GET_AVGENTRY 0   Average entry price for the preceding GET_POSITION command, or 0 when no position was open.
GET_ACCOUNT String   Fills the string with the account name.
GET_DATA String   General request to a REST API. The string contains the request, usually a JSON object. It can optionally begin with a '#' hash character and the last part of the post address ending with a blank, f.i. "#data "). The string is then filled with the response from the API. Returns the response size in characters, or 0 when no valid response was returned.
GET_BOOK T2* Fills the T2 array with current quotes from the order book. The asset is set with SET_SYMBOL; bid prices are negative, the time field is optional. The last T2 element is set to 0 for indicating the end of the array. Returns the number of quotes.
GET_TRADES TRADE* Fill the given TRADE array with the parameters of all open positions from the current account (see remarks). Return the number of positions.
GET_OPTIONS CONTRACT* Fill the given CONTRACT array with the option chain of the underlying set with SET_SYMBOL (see remarks).
GET_FUTURES CONTRACT* Fill the given CONTRACT array with the futures chain of the underlying set with SET_SYMBOL (see remarks).
GET_FOP CONTRACT* Fill the given CONTRACT array with the options of futures chain of the underlying set with SET_SYMBOL (see remarks).
GET_UNDERLYING 0 Get the underlying price for the preceding brokerAsset call when the asset was an option.
GET_GREEKS var[5]   Get the greeks for a preceding brokerAsset or contractPrice call. Fills the parameter array with P[0] = Implied Volatility; P[1] = Delta; P[2] = Gamma; P[3] = Vega; P[4] = Theta. Greeks cannot be retrieved with 'fast' price type.0
GET_DELAY 0   Return delay in ms between commands sent to the broker.
SET_DELAY Time in ms   Set delay in ms between commands sent to the broker.
GET_WAIT 0   Return maximum wait time for confirmation after a command was sent to the broker, in ms.
SET_WAIT Time in ms   Set maximum wait time in ms for confirmation after a command was sent to the broker. Default depends on the broker plugin; normally 60000. Increase the time when trades need longer than 1 minute to open.
GET_MAXTICKS 0 Return the maximum number of ticks to be filled by BrokerHistory2. If this command is not supported, it's 300 ticks.
GET_MAXREQUESTS 0 Return the maximum number of requests per second allowed by the broker API. Sets up MaxRequests if supported.
GET_HEARTBEAT 0 Return the maximum time in ms that the API tolerates without a request. Sets up TickTime if supported.
GET_BROKERZONE 0 Return the time zone of the timestamps set by the BrokerHistory2 function. Return 0 for UTC. Used for setting BrokerZone.
SET_DIAGNOSTICS 0, 1   1 to enable, 0 to disable diagnostics output. When enabled, communication between plugin and API and other plugin messages will be recorded in the log for diagnostic purposes.
GET_LOCK 0   Returns 1 if broker API calls must be locked for synchonizing them among several connected Zorros; returns -1 if broker API need not be locked. In this case the NOLOCK flag is automatically set.
SET_LOCK 0, 1   Set (1) or release (0) a lock for synchonizing commands among several connected Zorros (see remarks). Returns 0 if the lock was already set, otherwise 1.
SET_SLIPPAGE Pips   Set the maximum allowed slippage (default = 5 pips) in adverse direction for subsequently opening or closing trades. Higher allowed slippage causes less requotes, but allows trades to be entered at a worse price. Note that the allowed slippage is not guaranteed; trades can be still entered at higher slippage dependent on the brokerm, market access method, and server setup.
SET_SYMBOL Symbol Set the symbol for subsequent commands.
SET_MAGIC Number   Set a "magic number" for identifying trades opened by the current script.
SET_MULTIPLIER Number Set the multiplier for retrieving option and future chains.
SET_CLASS Name   Set the name of the trading class. Call this before setting the symbol for option and future chains; use an empty string ("") for retrieving all trading classes.
SET_AMOUNT var pointer Set the lot size for buy/sell orders; for assets with arbitrary small order sizes. Automatically sent before any order if the current LotAmount is less than 1.
SET_LEVERAGE Number Set the leverage for buy/sell orders; for assets with adjustable leverage. Automatically sent before any order with the current Leverage value.
SET_PATCH Patch value   Work around broker API issues that cause wrong account or asset parameters. Retrieve the following parameters in trade mode not from the broker API, but from the asset list or by calculating them on the Zorro side (numbers can be combined by addition):
1  - Balance and Equity;
2  - TradeProfit of open trades;
4  - TradeProfit of all trades;
8  - Server time;
16 - Rollover and Commission;
32 - Leverage and MarginCost;
64 - PIP, PIPCost, LotAmount.
SET_HWND HWND Set Zorro's window handle; automatically called before login. The window handle can be used to trigger asynchronous events and send messages to Zorro with the PostMessage function.
GET_CALLBACK Address
pointer
Get the address of a plugin-supplied callback function that is called at any WM_APP+3 message; automatically called after login.
SET_BROKER Text   Set the broker or exchange name when a plugin supports multiple brokers or exchanges. Returns 0 when the name did not match any, otherwise nonzero.
SET_SERVER Text Send the optional URL in the account list Server field to the broker API. Automatically called before login. Can be used to set a different URL for REST endpoints.
SET_CCY Text Send the currency part of the account list CCY field to the broker API. Automatically called before any BrokerAccount call.
SET_COMMENT Text   Display the given text (255 characters max) in the broker platform, usually at the top of the chart window.
SET_COMBO_LEGS 2, 3, 4 Declare the given number of following option trades as a combo order. Most brokers offer reduced margin and commission on combos. To use, set the combo leg number and immediately call the enter commands for the contracts. The order will be processed after the last enter command is received. If the order fails, the last enter will return 0. The script must then cancel the prior trades. All combo trades must have matching expiration dates  and underlying symbols; otherwise the order will not be accepted.
SET_ORDERTYPE 0 ... 11 Switch between order types, and return the type when it is supported by the broker plugin:
0  - Broker default (highest fill probability)
1  - AON (all.or-none); prevents partial fills
2  - GTC (good-till-cancelled); order stays open until completely filled
3 -  AON+GTC
+8 - STOP; add a stop order at distance Stop*StopFactor on NFA accounts (see remarks). 
SET_ORDERTEXT Text   Set an arbitrary order comment for the next order (255 characters max). Often also used for special orders, f.i. for trading binary options with MT4, or for special order types with IB.
GET_PRICETYPE 0   Returns the price type (see below) for BrokerAsset and BrokerHistory2. 
SET_PRICETYPE 0 ... 8   Determines the type of prices returned by BrokerAsset and BrokerHistory2, if applicable.
0
- Broker default (ask/bid if available, otherwise trades);
1
- enforce ask/bid quotes;
2
- enforce trades;
3
- special;
4
- no price requests;
8
- fast price requests.
The spread is normally only updated in type when ask/bid quotes are returned.
GET_VOLTYPE 0   Returns the volume type (see below) for BrokerAsset and BrokerHistory2.
SET_VOLTYPE 0 ... 7   Determines the type of volume data returned by BrokerAsset and BrokerHistory2, if applicable.
0 - Broker default, usually quote size;
1
- no volume;
2
- tick frequency;
3
- quote size (ask+bid);
4
- trade volume;
5
- ask size;
6
- bid size;
7
- open interest. 
GET_VALTYPE 0   Returns the type (see below) of marketVal data returned by BrokerAsset and BrokerHistory2.
SET_VALTYPE 0 .. 3   Determines the type of marketVal data returned by BrokerAsset and BrokerHistory2, if applicable. 1 - no data, 2 - spread; 3 - WAP.
GET_UUID String Copies the UUID of the last opened trade to the string.
SET_UUID String Sets the UUID for the next order from the string.
DO_EXERCISE Lots Exercise the given number of contracts of the option type set with SET_SYMBOL.
DO_CANCEL Trade ID Cancel the remaining unfilled amount of the order.
PLOT_HLINE var[5]   Place a horizontal line at a given price in the chart window of the broker platform. 5 parameters are used: P[0] = always 0; P[1] = price position; P[2] = line color; P[3] = line width; P[4] = line style. Return the identfier number of the line.
PLOT_TEXT var[4]   Place a text element at a price position at the right border of the chart window. 5 parameters are used: P[0] = always 0; P[1] = price position; P[2] = text color; P[3] = text size in points. Return the identfier number of the text element.
PLOT_MOVE var[3]   Move the graphical element with the identifier given bythe first parameter P[0], the horizontal position given by P[1] and the vertical position given by P[2].
PLOT_STRING Text   Set or modify the text content for the last created or moved text element.
PLOT_REMOVE Identifier   Delete the graphical element with the given identifier.
PLOT_REMOVEALL 0   Remove all graphical elements from the chart.
2000..2999 var   User supplied command with a single numerical parameter.
3000..3999 P[8]   User supplied command with an array of 8 var parameters..
4000..5999 char*   User supplied command with a text string.

Parameters:

Command Input, one of the commands from the list above.
Parameter Input, parameter or data to the command.
Parameters, P Input, array of up to 8 vars for commands that set or retrieve multiple parameters.
Symbol Input, char*, broker symbol of an asset (see Symbol). Complex symbols, as for selected option contracts, can have the underlying, exchange, expiry, and other parameters coded in the name as described under IB Bridge.
Text Input, char*, for commands that require a text string.
 

Returns:

0 when the command is not supported by the broker plugin, otherwise the data to be retrieved.
 

brokerAsset (string Name, var* pPrice, var* pSpread, var *pVol)

Call the BrokerAsset function with the symbol given by Name and return the price, spread, and volume.

brokerAccount (string Name, string AccountID, var *pBalance, var *pTradeVal, var *pMarginVal);

Call the BrokerAccount function for the account list entry given by Name and an optional account identifer, and return the balance, open trade value, and allocated margin. Can be used to retrieve account information when trading with multiple brokers.

brokerTrades (int Filter): int

Call the GET_TRADES command. Cancel all currently open trades, and replace them with the open positions on the broker account (if any). Filter = 0 loads all positions, Filter = 1 loads only positions matching the asset list, Filter = 2 loads only positions of assets that were already selected in the script, and Filter = 4 loads only positions of the current asset and prevents the previous cancelling of open trades. The number of positions is returned.
  This function can synchronize script trades with the broker account. The account must support the GET_TRADES command and have only open positions from the current Zorro script. The enterTrade function is used for entering the new trades. The entered trades are plain, without exit limits, TMFs, flags, TradeVars, or any other trade parameters that is not stored on the broker account. The algo identifiers of the trades are set to the current algo.
    

Remarks:

Examples:

brokerCommand(SET_COMMENT,strf("Algo %s",Algo)); // set a comment

brokerCommand(SET_PATCH,16+32); // take swap, commission, leverage from the asset list

var Greeks[5];
contractPrice(ThisContract);
brokerCommand(GET_GREEKS,Greeks); // get greeks of the current contract
// Read all positions from an asset list ///////////////////////
void main() 
{
  assetList("AssetsFix");
  string Name;
  while(Name = loop(Assets)) {
    var Position = brokerCommand(GET_POSITION,Name);
    printf("\n%6.4f %s",Position,Name);
    if(!wait(10)) break;
  }
}

// read and print the order book
void main() 
{
  static T2 Quotes[MAX_QUOTES];
  brokerCommand(SET_SYMBOL,"AAPL");
  int i,N = brokerCommand(GET_BOOK,Quotes);
  printf("\nOrderbook: %i quotes",N);
  for(i=0; i<N; i++)
    printf("\nPrice %.2f Vol %.2f",(var)Quotes[i].fVal,(var)Quotes[i].fVol);
}

// read JSON data string from the Coinigy REST API
void main() 
{
  brokerCommand(SET_BROKER,"GDAX");
  static char Buffer[MAX_BUFFER];
  strcpy(Buffer,"#data "); // target point
  strcat(Buffer,"{\n\"exchange_code\": \"GDAX\",");
  strcat(Buffer,"\n\"exchange_market\": \"BTC/USD\",");
  strcat(Buffer,"\n\"type\": \"bids\"\n}");
  int Size = brokerCommand(GET_DATA,Buffer);
  if(Size)
    printf("\nResponse: %s",Buffer);
}

See also:

Brokers, broker plugin, MTR4 bridge, FXCM plugin, IB plugin, Oanda plugin

► latest version online