Home
Trading Toolbox User's Guide
Contents
1. oo0oo0oo0oo d returns the historical data for 5 days When ticktype and period are not specified as input arguments history returns historical data using the default ticktype of TRADES and the default period of 1 day Each row of d contains historical data for 1 day The columns in matrix d are Numeric representation of a date Open price High price e Low price Close price e Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar history Display the open price for the most recent record in matrix d d 1 2 ans 790 0000 Close the IB Trader Workstation connection close ib Request Interactive Brokers Historical Data with BID Tick Type and 1 Week Period To request historical data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Historical Data on page 3 32 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request the last 50 days of historical data using ib ipContract and these arguments Start date is 50 days ago End date is the current moment Tick typeis BID e Bar sizeis 1W startdate floor now 50 enddate floor now ticktype BID period 1W d h
2. 8 FIX 4 4 11 338 54 2 60 21 May 2015 11 18 46 40 D 55 ABC 21 1 38 100 8 FIX 4 4 11 339 54 2 60 21 May 2015 11 18 47 40 D 55 ABC 21 1 38 100 Each string is a raw FIX message string that contains FIX tags and values The space in between the tag and value pairs is a SOH character This character is not printable and has a hexadecimal value of 0x01 Input Arguments fixstruct FIX message structure FIX message specified as a structure array The data in the structure represents one FIX message The structure fields correspond to FIX tag names The structure values are the values that you specify in the FIX message Example fixStruct BeginString 1 1 FIX 4 4 fixStruct CLOrdId 1 1 338 fixStruct Side 1 1 2 fixStruct TransactTime 1 1 datestr now fixStruct OrdType 1 1 D fixStruct Symbol 1 1 ABC fixStruct HandlInst 1 1 1 fixStruct OrderQty 1 1 100 Data Types struct struct2fix Output Arguments fixstr FIX message cell array FIX message returned as a cell array of one or more converted raw FIX message strings The number of strings depends on the number of messages that you specify in the input argument More About Workflow for FIX Flyer on page 2 10 FIX Trading Community See Also fix2struct fix2table fixflyer table2fix Introduced in R2015b 4 291 A functions Alphabetical List table2fix Convert table containing FI
3. Connect to the IB Trader Workstation using ibtws Create the IB Trader Workstation IContract object Request contract detailed data using contractdetails Request account information using accounts Request portfolio data using portfolio Close the IB Trader Workstation connection using close Related Examples Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 2 7 2 Workflow Models Workflow for CQG This diagram shows the functions you can use with CQG to monitor market price information and submit orders Establish Connection Close Create Orders Connection cqg realtime createOrder close timeseries shutDown history To request current intraday or historical data Create the CQG connection object using cqg Define the CQG event handlers Connect to CQG using startUp Subscribe to a CQG instrument to request real time data using realtime Request intraday data for a security using timeseries Request historical data for a security using history NO oO B WN Close the CQG connection using close or shutDown To submit orders to CQG Create the CQG connection object using cqg Define the CQG event handlers Connect to
4. Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx Output Arguments r Return information for all fields structure Return information for all fields returned as a structure for all fields supported by Bloomberg EMSX More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 See Also close createOrder createOrderAndRoute createOrderAndRouteWithStrat emsx 4 49 A Functions Alphabetical List Introduced in R2013a 4 50 getBrokerlnfo getBrokerlnfo Obtain Bloomberg EMSX broker and strategy information Syntax r getBrokerInfo c brokerstrat Description r getBrokerInfo c brokerstrat obtains Bloomberg EMSX broker and strategy information using the Bloomberg EMSX connection c and broker and strategy request structure brokerstrat Examples Obtain Broker Information Create a connection C to the Bloomberg EMSX c emsx blp emapisvc_beta Define the broker and strategy information structure brokerstrat Obtain broker information using the Bloomberg
5. com bloomberglp blpapi SubscriptionList 463b9287 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Unsubscribe from route events using the Bloomberg EMSX subscription list object Subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Set Up Route Subscription Using a Custom Event Handler Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Write a custom event handler function named eventhandler Run the custom event handler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t t is the timer object Set up the route subscription for Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c Use the custom event handler by setting the name value pair argument useDefaultEventHandler to false 4 125 A functions Alphabetical List 4 126 fields EMSX_BROKER EMSX_WORKING events subs routes c fields useDefaultEventHandler false events subs com bloomberglp blpapi SubscriptionList 463b9287 events is an empty double The custom event handler processes the event queue subs contains the Bloomberg EMSX subscription list object
6. Assign the customer defaults for trading an instrument orderProfile Customer lt Default gt Set up the order profile as a market order Set up the order profile as a market order for buying 225 shares orderProfile Set BuySell Buy orderProfile Set Qty 225 orderProfile Set OrderType M Check the order server status nCounter 1 while exist bServerUp var amp amp nCounter lt 20 bServerUp is created by ttorderserverstatus pause 1 nCounter nCounter 1 end 1 17 1 Getting Started 1 18 Verify the order server availability and submit the order if exist bServerUp var amp amp bServerUp Submit the order submittedQuantity c OrderSet 1 SendOrder orderProfile disp Quantity Sent num2str submittedQuantity else disp Order server is down Unable to submit order end The X_TRADER API submits the order to the exchange and returns the number of contracts sent for lot based contracts or the flow quantity sent for flow based contracts in the output argument submittedQuantity Close the connection close c See Also close createInstrument createOrderProfile createOrderSet xtrdr Related Examples Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 More About Workflows for Trading Technologies X TRADER on page 2 4 Exter
7. Event identifier Account code Event key Currency Account name Structure that repeats the contents of the columns e Request type For details about this data see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws acctno Account number string Account number specified as a string that identifies the Interactive Brokers account number Example accounts Data Types char eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types Function_handle char Output Arguments d Account information structure double Account information returned as a structure containing fields with the Interactive Brokers account information When using an event handler function d is an empty double More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace
8. Pass an additional optional request property by creating the structure x and setting the optional property To see only bid tick data for example set TickFilter to tfBid x TickFilter tfBid TickFilter and SessionsFilter are the only valid additional optional properties for calling timeseries without a timed bar request For additional property values you can set see CQG API Reference Guide Request intraday tick data for instrument XYZ XYZ for the last 2 days using the additional optional request property x instrument XYZ XYZ startdate now 2 enddate now timeseries c instrument startdate enddate x MATLAB writes the variable cqgTickData to the Workspace browser Display cqgTickData cqgTickData cqgTtickData Timestamp 2x1 cell Price 2x1 double Volume 2x1 double PriceType 2x1 cell CorrectionType 2x1 cell SalesConditionLabel 2x1 cell SalesConditionCode 2x1 double ContributorId 2x1 cell ContributorIdCode 2x1 double MarketState 2x1 cell cqgTickData returns intraday tick data for the specified instrument Display the data in the Timestamp property of cqgTickData cqgTickData Timestamp 4 182 timeseries ans 4 17 2013 2 14 00 PM 4 18 2013 2 14 00 PM Close the CQG connection close c Request CQG Timed Bar Data To request timed bar data for an instrument create the connection C using cqg and startUp Register an event handler for tracki
9. Unsubscribe from route events using the Bloomberg EMSX subscription list object subs Stop the timer to stop data updates using stop c Session unsubscribe subs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Set Up Route Subscription Using a Timeout Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Set up the route subscription for Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c Specify the name value pair argument timeOut and set it to 200 milliseconds fields EMSX_BROKER EMSX_WORKING events subs routes c fields timeOut 200 events routes MSG_TYPE 5x1 cell MSG_SUB_ TYPE 5x1 cell EVENT_STATUS 5x1 int32 subs com bloomberglp blpapi SubscriptionList 463b9287 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Unsubscribe from route events using the Bloomberg EMSX subscription list object Subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Set Up Route Subscription Using an Options Structure Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Set up the route subsc
10. on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request intraday data using ib ibContract and these arguments Start date is this morning e End date is the current moment Aggregated every 10 minutes Tick type is BID e Within regular trading hours Sample event handler function ibExampleEventHandler Use ibExampleEventHand1er or write a custom event handler function startdate floor now enddate now barsize 10 mins ticktype BID tradehours true eventhandler ibExampleEventHandler d timeseries ib ibContract startdate enddate barsize ticktype tradehours eventhandler 4853 00 Columns 1 through 3 1x1 COM TWS_TwsCtr1_1 22 00 4853 00 Columns 4 through 7 20140909 15 55 00 580 20 581 40 580 09 Columns 8 through 13 581 01 1 00 1 00 1 00 0 1x1 struct 4 221 A Functions Alphabetical List 4 222 Column 14 historicalData d is the request identifier After d ibExampleEventHandler streams intraday data to the Command Window The columns are Interactive Brokers ActiveX object Event identifier Request identifier Date Open price High price Low price Close price Volume Bar count Weighted average price Flag indicating if there are gaps in the ba
11. route EMSX_HAND_INSTRUCTION ANY route EMSX_TIF DAY route EMSX_ORDER_TYPE MKT Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 groupRouteOrderWithStrat strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Route the orders using the Bloomberg EMSX connection c route strat and options structure options options useDefaultEventHandler true options timeOut 200 events groupRouteOrderWithStrat c route strat options events EMSX_SUCCESS_ ROUTES 1x1 struct EMSX_FAILED_ ROUTES 1x1 struct MESSAGE 1 of 1 Order s Routed where events EMSX_SUCCESS ROUTES EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 and events EMSX_ FAILED ROUTES EMSX_SEQUENCE 335878 ERROR_CODE 0 ERROR_MESSAGE Order 335878 View only orders can not be routed The default event handler processes the events associated with routing the order groupRouteOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX success routing structure which contains the order number and route identifier for the orders that successfully routed Bloomberg EMSX failed ro
12. Attach an Instrument to a Notifier Assign one or more notifiers to an instrument A notifier can have one or more instruments attached to it X InstrNotify 1 AttachInstrument X Instrument 1 Define Events Assign callbacks for validating or invalidating an instrument and updating the example order book window registerevent X InstrNotify 1 OnNotifyFound ttinstrumentfound registerevent X InstrNotify 1 OnNotifyNotFound ttinstrumentnotfound registerevent X InstrNotify 1 OnNotifyDepthData ttinstrumentdepthupdate Set Up the Figure Window Set up the figure window to display depth data f figure Numbertitle off Tag TTPriceUpdateDepthFigure Listen for X_TRADER Price Market Depth Updates Name Order Book X Instrument 1 Alias pos f Position f Position pos 1 pos 2 360 315 f Resize off Create Controls Create controls for the last price data bspc 5 bwid 80 bhgt 20 uicontrol Style text String Exchange Position bspc 4 bspc 3 bhgt bwid bhgt uicontrol Style text String Product Position 2 bspct bwid 4 bspc 3 bhgt bwid bhgt uicontrol Style text String Type Position 3 bspct 2 bwid 4 bspc 3 bhgt bwid bhgt uicontrol Style text String Contract Position 4 bspct 3 bwid 4 bspc 3 bhgt bwid bhgt ui Exchange uicontrol Style text Tag Position bs
13. DU111111 p p Type Source EventID contract position marketPrice marketValue averageCost unrealizedPNL realizedPNL accountName p is a structure that contains these fields Event type Interactive Brokers ActiveX object Event identifier Contract details Number of shares for each contract Price of the shares for each contract Number of shares multiplied by the price of the shares for each contract Average price when the shares are purchased for each contract portfolio ib acctno 5x1 5x1 5x1 5x1 5x1 5x1 5x1 5x1 5x1 5x1 5x1 cell cell cell cell cell cell cell cell cell cell cell 4 259 A functions Alphabetical List 4 260 Unrealized profit and loss for each contract Actual profit and loss for each contract Account number 5x1 means there are five contracts in this portfolio For details about this data see Interactive Brokers API Reference Guide Display the market price for each contract in the portfolio p marketPrice ans 8 60 582 95 591 79 188 44 42 24 Close the IB Trader Workstation connection close ib Retrieve Current Portfolio Data Using an Event Handler Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Retrieve current Interactive Brokers portfolio data using ib account number string acctno and sample event handler ibEx
14. Side 2x1 cell TransactTime 2x1 cell OrdType 2x1 cell Symbol 2x1 cell HandlInst 2x1 cell OrderQty 2x1 cell The structure array fixstruct contains a structure for each raw FIX message string in fixstr The structure fields correspond to the FIX tags in the raw FIX message 4 284 fix2struct Display the order type for each FIX message fixstruct OrdType ans D D Both FIX messages specify previously quoted orders Input Arguments fixstr FIX message cell array FIX message specified as a cell array of one or more raw FIX message strings Example Data Types cell Output Arguments fixstruct FIX message structure FIX message specified as a structure array containing the converted raw FIX messages in fixstr The structure fields and values correspond to the FIX tag names and values in the raw FIX message string More About Workflow for FIX Flyer on page 2 10 FIX Trading Community See Also fix2table fixflyer struct2fix table2fix 4 285 A Functions Alphabetical List Introduced in R2015b 4 286 fix2table fix2table Convert FIX message string to table Syntax fixtable fix2table fixstr Description fixtable fix2table fixstr converts raw FIX message strings in the cell array fixstr toa table fixtable Examples Convert FIX String to Table For this example assume that a counterparty sends you raw FIX messages in fixstr
15. enter the following c APIConfig TimeZoneCode tzEastern c APIConfig is a CQG configuration object For details about setting API configuration properties see CQG API Reference Guide Establish the connection to CQG startUp c CELStarted DataConnectionStatusChanged GWConnectionStatusChanged The connection event handler displays event names for a successful CQG connection 3 45 3 Sample Code for Workflows 3 46 Register an event handler to track events associated with a CQG instrument subscription streamEventNames InstrumentSubscribed InstrumentChanged IncorrectSymbol for i 1 length streamEventNames registerevent c Handle streamEventNames i varargin cqgrealtimeeventhandler varargin end Register an event handler to track events associated with a CQG order and account orderEventNames AccountChanged OrderChanged AllOrdersCanceled for i 1 length orderEventNames registerevent c Handle orderEventNames i varargin cqgordereventhandler varargin end Subscribe to the CQG Instrument With the connection established subscribe to the CQG instrument The instrument must be successfully subscribed first before it is available for transactions You must format the instrument name in the CQG long symbol view For example to subscribe to a security tied to the EURIBOR enter the following realtime c F US IE pause 2 F US IEK13 subscribed
16. ibContract1 secType OPT ibContract1 expiry 201408 ibContract1 strike 535 ibContract1 right C ibContract1 multiplier 100 ibContract1 exchange SMART ibContract1 currency USD Request contract details for ioContract1 cd1 ibContractID1 contractdetails ib ibContract1 cd1 returns the contract details data for ipoContract1 ibContractID1 returns the request identifier for this contract details request Create the IB Trader Workstation IContract object ibContract2 Here this object describes the second call option in the calendar spread Create an IContract object with these property values Google symbol Stock option Expiry date is September 2014 Strike price is 535 00 Call option Number of shares is 100 Aggregate exchange USD currency ibContract2 ib Handle createContract ibContract2 symbol GOOG ibContract2 secType OPT ibContract2 expiry 201409 ibContract2 strike 535 ibContract2 right C ibContract2 multiplier 100 ibContract2 3 40 exchange SMART Create Interactive Brokers Combination Order ibContract2 currency USD Request contract details for ioContract2 cd2 ibContractID2 contractdetails ib ibContract2 cd2 returns the contract details data for ipnContract12 ibContractID2 returns the request identifier for this contract details request Create IB Trader Workstation IComboLegList
17. modifyRoute c modroute timeOut timeout modifyRoute _ useDefaultEventHandler false modifyRoute c modroute options Description events modifyRoute c modroute modifies a Bloomberg EMSX route using the Bloomberg EMSX connection c and route request modroute modif yRoute returns a status message using the default event handler events modifyRoute c modroute timeOut timeout specifies a timeout value timeout for the execution of the default event handler modifyRoute _ useDefaultEventHandler false modifies a Bloomberg EMSX route using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with modifying routes This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true ___ modifyRoute c modroute options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when the flag useDefaultEventHand1ler is set to true and omit this output argument when useDefaultEventHandler is set to false
18. s Guide using the WAPI lt GO gt option from the Bloomberg terminal 3 Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 deleteRoute See Also timer close createOrder createOrderAndRoute delete deleteOrder emsx modifyOrder modifyRoute orders routeOrder routes start stop Introduced in R2013a 4 47 A functions Alphabetical List getAllFieldMetaData Obtain Bloomberg EMSX field information Syntax r getAllFieldMetaData c Description r getAllFieldMetaData c returns the Bloomberg EMSX field information using the Bloomberg EMSX connection C Examples Request All Field Information Create a connection C to the Bloomberg EMSX c emsx blp emapisvc_beta Request all fields supported by Bloomberg EMSX service using the Bloomberg EMSX connection C r getAllFieldMetaData c r EMSX_FIELD NAME 113x1 cell EMSX_DISP_NAME 113x1 cell EMSX_TYPE 113x1 cell EMSX_LEVEL 113x1 double EMSX_LEN 113x1 double Display all field information for the first Bloomberg EMSxX field using a cell array Create a cell array from the fields in the returned data structure r r EMSX_FIELD_NAME 1 r EMSX_DISP_NAME 1 r EMSX_TYPE 1 r EMSX_LEVEL 1 r EMSX_LEN 1 4 48 getAllFieldMetaData MSG_TYPE Msg Type String 0 1 Close the Bloomberg EMSX connection close c
19. strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Route the order using the Bloomberg EMSX connection c route and strat Set the timeout value to 200 milliseconds events routeOrderWithStrat c route strat timeOut 200 events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed 4 117 A functions Alphabetical List 4 118 The default event handler processes the events associated with routing the order routeOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Route an Order Using a Custom Event Handler To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route
20. 1475 1475 1475 MNONMNNNND 1475 1475 1475 1475 1475 NNNNND 1475 1475 1475 1475 1475 NONNNND 1475 1475 1475 1475 1475 NMNNNNND 1475 1475 1475 1475 1475 NONNMNNND 1475 1475 1475 1475 1475 NMNNNNND low price close price mid price HLC3 average price and tick volume Close the CQG Connection close c See Also close cqg createOrder history realtime shutDown startuUp timeseries Related Examples Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 gt Request CQG Real Time Data on page 3 57 More About Workflow for CQG on page 2 8 External Websites CQG API Reference Guide 1475 1475 1475 1475 1475 Request CQG Real Time Data Request CQG Real Time Data This example shows how to connect to CQG define event handlers and request current data Connect to CQG Create the CQG connection object using cqg c cqg Define Event Handlers Register the sample event handler cqgconnectioneventhandler to track events for the connection status eventNames CELStarted DataError IsReady DataConnectionStatusChanged GWConnectionStatusChanged GWEnvironmentChanged for i 1 length eventNames registerevent c Handle eventNames i varargin cqgconnectioneventhandler varargin e
21. A functions Alphabetical List 4 184 close c Request CQG Timed Bar Data with Additional Properties To request timed bar data for an instrument with an additional property create the connection C using cqg and startUp Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output data structure For an example demonstrating these activities see Request CQG Intraday Tick Data on page 3 53 See CQG API Reference Guide to learn more about event handlers and the API configuration properties Pass an additional optional request property by creating the structure x and setting the optional property x UpdatesEnabled false For additional optional properties you can set see CQG API Reference Guide Request timed bar data for instrument XYZ XYZ for the last fraction of a day using the additional optional request property xX instrument XYZ XYZ startdate now 1 enddate now intraday 1 timeseries c instrument startdate enddate intraday x MATLAB writes the variable cqgTimedBarData to the Workspace browser Display cqgTimedBarData cqgTimedBarData cqgTimedBarData 1 0e 09 0007 0007 0007 0007 0007 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 147
22. A functions Alphabetical List 4 188 COM TWS_TwsCtr1_1 Close the IB Trader Workstation connection close ib Connect to the IB Trader Workstation on Another Machine Note The IP address for this example does not represent a real Interactive Brokers machine Use IP address 1111 222 333 44 and port number 7496 to connect to the IB Trader Workstation on another machine ib ibtws 1111 222 333 44 7496 ib ibtws with properties ClientId 0 Handle 1x1 COM TWS_TwsCtr1_1 Host 1111 222 333 44 Port 7496 MATLAB returns ib as the connection to the IB Trader Workstation with the Interactive Brokers ActiveX object the IP address that you choose and the port number that you choose Display the Handle property of ib ib Handle ans COM TWS_TwsCtr1_1 Close the IB Trader Workstation connection close ib Create an Order Using IB Trader Workstation on page 1 7 ibtws Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 Input Arguments host IP address of machine where IB Trader Workstation is running string for IP address IP address of the machine where the IB Trader Workstation is running specified as either an empty string to specify the local machine or an IP address
23. Bloomberg EMSX order number Bloomberg EMSX route identifier Create an Order Using Bloomberg EMSX Bloomberg EMSX message Close the Bloomberg EMSX connection close c See Also close createOrderAndRoute emsx Related Examples Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 More About Workflow for Bloomberg EMSX on page 2 2 1 Getting Started Create an Order Using X_TRADER 1 16 This example shows how to connect to Trading Technologies X_TRADER and create a market order Connect to Trading Technologies X_TRADER c xtrdr Create an instrument for a contract Create an instrument for a contract of CAISO NP15 EZ Gen Hub 5 MW Peak Calendar Day Real Time LMP Futures with an expiration date of August 2014 on the Chicago Mercantile Exchange createInstrument c Exchange CME Product 2F ProdjType Future Contract Augi4 ssi Alias SuobmitOrderInstrument3 Register an event handler for the order server Register an event handler to check the order server status sExchange c Instrument Exchange c Gate registerevent OnExchangeStateUpdate varargin ttorderserverstatus varargin sExchange Create an order set and set order properties Create an empty order set Then set order set properties Setting the firs
24. Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide 4 229 A Functions Alphabetical List See Also close createOrder history ibtws timeseries Introduced in R2015a 4 230 contractdetails contractdetails Request Interactive Brokers contract details Syntax d reqid contractdetails ib ibContract d reqid contractdetails ib ibContract eventhandler Description d reqid contractdetails ib ibContract requests Interactive Brokers contract details using IB Trader Workstation connection ib and IB Trader Workstation IContract object ipbContract d reqid contractdetails ib ibContract eventhandler requests Interactive Brokers contract details using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Request Interactive Brokers Contract Details Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Create the IB Trader Workstation IContract object ibContract Here this object describ
25. IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide ibOrder IB Trader Workstation order IOrder object IB Trader Workstation order specified as an IB Trader Workstation IOrder object This object contains the order conditions which are the action of the order for example buy or sell the order quantity and the type of order for example market or limit Create this object by calling the Interactive Brokers API function createOrder For details about the attributes that you can set and createOrder see Interactive Brokers API Reference Guide id IB Trader Workstation order unique identifier scalar IB Trader Workstation order unique identifier specified as a scalar Data Types double eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 4 197 A Functions Alphabetical List 4 198 Example eventhand
26. ProdType Option Contract Juni4 P127 Alias PriceInstrumentEurex Create another X_TRADER instrument for CAISO NP15 EZ Gen Hub 5 MW Peak Calendar Day Real Time LMP Futures using name value pair arguments corresponding to valid X_TRADER API options This contract expires in April 2014 createInstrument c Exchange CME Product 2F ProdType Future Contract Apri4 Alias PriceInstrumentCMEApr14 Create another X_TRADER instrument for CAISO NP15 EZ Gen Hub 5 MW Peak Calendar Day Real Time LMP Futures using name value pair arguments corresponding to valid X_TRADER API options This contract expires in October 2014 createInstrument c Exchange CME Product 2F ProdType Future Contract Oct14 Alias PriceInstrumentCMEOct14 Retrieve the exchange and product identifier for all three X_TRADER instruments d getData c Exchange Product d Exchange 3x1 cell Product 3x1 cell d is a structure containing the Exchange and Product fields The fields are cell arrays Display the Exchange field d Exchange ans Eurex CME CME createlnstrument The Exchange field contains the exchange names Eurex and CME for the three X_TRADER instruments Close the connection close c i Create an Order Using X_ TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Update
27. Syntax events modifyRouteWithStrat c modroute strat events modifyRouteWithStrat c modroute strat timeOut timeout modifyRouteWithStrat _ useDefaultEventHandler false modifyRouteWithStrat c modroute strat options Description events modifyRouteWithStrat c modroute strat modifies a Bloomberg EMSX route with strategies using the Bloomberg EMSX connection cC route request modroute and order strategy strat modifyRouteWithStrat returns the order sequence number route identifier and status message using the default event handler events modifyRouteWithStrat c modroute strat timeOut timeout specifies a timeout value timeout for the execution of the default event handler modifyRouteWithStrat _ useDefaultEventHandler false modifies a Bloomberg EMSX route with strategies using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with modifying routes This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true _____ modifyRouteWithStrat c modroute strat options uses the options structure to customize the output which is useful to preconfigure and
28. The FIX protocol version is 4 4 Convert the raw FIX messages in fixstr to a table fixtable There are two raw FIX messages in fixstr fixtable fix2table fixstr fixtable BeginString C10rdID Side TransactTime OrdType Symbol Hi FIX 4 4 338 2 19 May 2015 15 00 38 D IBM FIX 4 4 338 2 19 May 2015 15 00 38 D TBM 4 287 A Functions Alphabetical List 4 288 The table fixtable contains a row for each raw FIX message string in fixstr The variable names in the table correspond to the FIX tags in the raw FIX message Input Arguments fixstr FIX message cell array FIX message specified as a cell array of one or more raw FIX message strings Example Data Types cell Output Arguments fixtable FIX message table FIX message specified as a table containing the converted raw FIX messages in fixstr The table variables correspond to the FIX tag names that are specified in the raw FIX message string The table row contains the values that are specified for each tag in the raw FIX message string More About i Workflow for FIX Flyer on page 2 10 FIX Trading Community See Also fix2struct fixflyer struct2fix table2fix Introduced in R2015b struct2fix struct2fix Convert structure array containing FIX tags to cell array of FIX message strings Syntax fixstr struct2fix fixstruct Description fixstr struct2fix fixstruct converts FIX m
29. X xtrdr Define an input structure S with fields corresponding to valid X_TRADER API options S S Instrument S Customer S Alias S ReadProperties b S WriteProperties b createOrderProfile Customers lt Default gt RoundOption 2 CustomerDefaults S S Instrument Customer Alias ReadProperties b WriteProperties b Customers lt Default gt RoundOption 2 CustomerDefaults Create an order profile P createOrderProfile X S Close the connection close X Create an Order Profile Using Name Value Pairs Start X_TRADER X xtrdr Create an order profile using name value pairs corresponding to valid X_TRADER API options createOrderProfile X Instrument Customer Alias ReadProperties b WriteProperties b Customers lt Default gt RoundOption 2 CustomerDefaults Close the connection close X Create an Order Using X_TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 4 147 A Functions Alphabetical List Submit X_TRADER Orders on page 3 8 Input Arguments X X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr S xtrdr input structure with fields structure xtrdr input st
30. and request other information using FIX messages you can use the FIX Flyer Engine with these functions 1 Connect to the FIX Flyer Engine using fixflyer 2 To monitor events associated with the connection and FIX messages add an event handling listener using addListener 3 Send a FIX message to the FIX Flyer Engine using sendMessage Close the FIX Flyer connection using close Workflow for FIX Flyer Receive a FIX Message Receive a FIX message string from the counterparty after completing a transaction To convert between FIX message strings and structure arrays or tables use these functions 1 Convert a FIX message to a structure array using fix2struct 2 Convert a FIX message to a table using fix2table Related Examples Create an Order Using FIX Flyer on page 1 19 External Websites 7 FIX Trading Community 2 11 Sample Code for Workflows Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 e Create and Manage a Bloomberg EMSX Order on page 3 12 e Create and Manage a Bloomberg EMSX Route on page 3 16 e Manage a Bloomberg EMSX Order and Route on page 3 21 e Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 e Request Interactive Brokers Real Time Data on page 3 35 e Create Interacti
31. close c See Also close createOrder deleteOrder emsx modifyOrder orders Related Examples Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 More About Workflow for Bloomberg EMSX on page 2 2 3 15 3 Sample Code for Workflows Create and Manage a Bloomberg EMSX Route 3 16 This example shows how to connect to Bloomberg EMSX set up a route subscription create and route an order and interact with the route For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Connect to Bloomberg EMSX Connect to the Bloomberg EMSxX test service Display the current event queue contents using processEvent c emsx blp emapisvc_beta processEvent c G emsx with properties Session 1x1 com bloomberglp blpapi Session Service 1x1 com bloomberglp blpapi impl aQ Ipaddress localhost Port 8194 SessionConnectionUp server localhost 127 0 0 1 8194 SessionStarted ServiceOpened serviceName blp emapisvc_beta MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSX test service Port number of the m
32. lt Default gt Alias RoundOption 2 CustomerDefaults Data Types char Output Arguments P Order profile structure Order profile returned as a structure More About i Workflows for Trading Technologies X TRADER on page 2 4 X_TRADER API See Also createInstrument createNotifier createOrderSet xtrdr Introduced in R2013a 4 149 A Functions Alphabetical List 4 150 createOrderSet Create order set for X_ TRADER Syntax createOrderSet X createOrderSet X S createOrderSet X Name Value Description createOrderSet X creates an xtrdr order set with empty properties You can set the properties individually using X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference createOrderSet X S creates an xtrdr order set defined by the structure S with fields corresponding to X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference createOrderSet X Name Value creates an order set using X_TRADER API options specified by one or more Name Value pair arguments with names and values corresponding to X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Examples Create an Empty Order Set Start X_TRADER X xtrdr Create an order set without any pro
33. on page 3 4 Submit X_TRADER Orders on page 3 8 Input Arguments X X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr S xtrdr input structure with fields structure xtrdr input structure specified with fields corresponding to valid X TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example S S Exchange Eurex S Product OGBM S ProdType Option S Contract Jan12 P12300 S Alias TestInstrument3 Data Types struct Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example createNotifier X Instrument UpdateFilter EnablePriceUpdates 1 EnableDepthUpdates 0 DebugLogL DeliverAllPriceUpdates 0 Property1 Valid X_TRADER API options string 4 144 createNotifier Valid X_TRADER API options specified using the details described in Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example createNotifier X Instrument UpdateFilter EnablePriceUpdates 1 EnableDepthUpdates 0 DebugLogL DeliverAllPrice
34. order EMSX_SIDE BUY Create the order using the Bloomberg EMSX connection c and order events createOrder c order events EMSX_SEQUENCE 354646 MESSAGE Order created The default event handler processes the events associated with creating the order createOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection createOrder close c Create an Order Using a Timeout To create a Bloomberg EMSX order create the connection C using emsx and set up the order subscription using orders For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_INSTRUCTION ANY order EMSX_SIDE BUY Create the order using the Bloomberg EMSX connection c and order Set the timeout
35. string Valid X_TRADER API options specified using information in the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Requirements e When using the Alias name value pair argument ensure that every Alias name is unique across all X_TRADER instruments Restart the MATLAB session before reusing an Alias name Otherwise createInstrument returns an error Data Types char Property2 Valid X_TRADER API options string Valid X_TRADER API options specified using information in the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Data Types char More About 7 Workflows for Trading Technologies X TRADER on page 2 4 createlnstrument X_TRADER API See Also createNotifier createOrderProfile createOrderSet xtrdr Introduced in R2013a 4 141 A functions Alphabetical List 4 142 createNotifier Create instrument notifier for X_TRADER Syntax createNotifier X S createNotifier X Name Value Description createNotifier X S creates the xtrdr instrument notifier defined by the structure S with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference createNotifier X Name Value creates the instrument notifier using X_TRADER API options specified by one or more Name Value pair arguments w
36. 2 8 External Websites CQG API Reference Guide Create an Order Using Bloomberg EMSX Create an Order Using Bloomberg EMSX This example shows how to connect to Bloomberg EMSX and create and route a market order For details about connecting to Bloomberg EMSX and creating orders see the EMSX API Programmer s Guide Connect to Bloomberg EMSX 1 If you are using emsx for the first time you need to install a Java archive file from Bloomberg for emsx and other Bloomberg commands to work correctly If you already have blpapi3 jar downloaded from Bloomberg you can find it in your Bloomberg folders at b1lp api APIv3 JavaAPI lib blpapi3 jaror blp api APIv3 JavaAPI v3 x lib blpapi3 jar If you have blpapi3 jar go to step 3 If blpapi3 jar is not downloaded from Bloomberg then download it as follows a b In your Bloomberg terminal type WAPI GO to open the API Developer s Help Site screen Click API Download Center then click Desktop API After downloading blpapi3 jar on your system add it to the MATLAB Java class path using javaaddpath You need to do this for every session of MATLAB To avoid repeating this at every session add javaaddpath to your startup m file or add the full path for blpapi3 jar to your javaclasspath txt file For details about javaclasspath txt see Java Class Path For details about editing your startup m file see Startup Options in MATLAB Startup File Conn
37. BB route EMSX_HAND_INSTRUCTION ANY Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Route the order using the Bloomberg EMSX connection c and route Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with routing an order routeOrder c route useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop 4 99 A functions Alphabetical List 4 100 c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Route an Order Using an Options Structure To route a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see
38. Close the CQG connection shutDown c Alternatively close the CQG connection using close close c Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 shutDown Input Arguments c CQG connection connection object CQG connection specified as a CQG connection object created using cqg More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also close cqg startUp Introduced in R2013b 4 177 A Functions Alphabetical List 4 178 startUp Create CQG connection Syntax startUp c Description startUp c creates the CQG connection c Examples Create the CQG Connection Create the CQG connection object using cqg c cqg Create the CQG connection startUp c Close the CQG connection close c Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 Input Arguments c CQG connection connection object startUp CQG connection specified as a CQG connection object created using cqg More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also close cqg shutDown Introduced in R2013b 4 179 A Functions Alphabetical
39. Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BB route EMSX_HAND_INSTRUCTION ANY Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Route the order using the Bloomberg EMSX connection c route and options structure options options useDefaultEventHandler true options timeOut 200 events routeOrder c route options events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed routeOrder The default event handler processes the events associated with routing the order routeOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c
40. Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx route Route request structure Route request specified as a structure containing these fields Convert the numbers to 32 bit signed integers using int32 EMSX_SEQUENCE must denote an existing order sequence number Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number EMSX_TICKER Bloomberg EMSX ticker symbol 4 101 A Functions Alphabetical List 4 102 Field Description EMSX_AMOUNT Bloomberg EMSX number of shares EMSX_BROKER Bloomberg EMSX broker name EMSX_HAND_ INSTRUCTION Bloomberg EMSX hand instruction Example route EMSX_SEQUENCE int32 728918 route EMSX_TICKER XYZ route EMSX AMOUNT int32 100 route EMSX BROKER BB route EMSX HAND INSTRUCTION ANY Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Ty
41. Description processEvent c displays and flushes the event queue associated with the Bloomberg EMSX connection c processEvent is a sample event handler function You can build a custom event handler function to process Bloomberg EMSX events Examples Continually Process the Bloomberg EMSX Event Queue Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Use timer to continually process the Bloomberg EMSX event queue t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate tis the MATLAB timer object For details see timer Close the Bloomberg EMSX connection close c Process the Bloomberg EMSX Event Queue Once Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Use the default event handler function processEvent to process the Bloomberg EMSX event queue once 4 93 A Functions Alphabetical List 4 94 processEvent c SessionConnectionUp server localhost 127 0 0 1 8194 SessionStarted ServiceOpened serviceName blp emapisvc_beta processEvent clears the Bloomberg EMSX event queue Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service
42. Functions with Bloomberg EMSX on page 1 23 routes See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx getAllFieldMetaData modifyOrder modifyRoute orders routeOrder start stop Introduced in R2013a 4 131 A Functions Alphabetical List 4 132 xtrdr Create X_TRADER connection Syntax X xtrdr Description X xtrdr starts X_TRADER or connects to an existing X_TRADER session Examples Create a Connection to X_TRADER X xtrdr X xtrdr with properties Gate 1x1 COM Xtapi_TTGate_1 InstrNotify Instrument OrderSet Create an Order Using X_TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 Output Arguments X X_TRADER connection connection object xtrdr X_TRADER connection returned as a connection object for an X_TRADER session Limitations You should only create one X_TRADER connection per MATLAB session To create a new X_TRADER connection start a new MATLAB session More About Workflows for Trading Technologies X_TRADER on page 2 4 X_TRADER API See Also close Introduced in R2013a 4 133 A Functions Alphabetical List 4 134 close Close X_TRADER connection Syntax close X Description c
43. Linux or Mac the JAR file path has a different format For example FIXFlyer fix flyer 5 0 1 devkit lib fix flyer jar Import the FIX Flyer Java libraries 4 271 A functions Alphabetical List 4 272 import flyer apps import flyer apps FlyerApplicationManagerFactory import flyer core session Create the FIX Flyer Engine connection C using these arguments User name username e Password password IP address ipaddress e Port number port username user password pwd ipaddress 127 0 0 1 port 7002 c fixflyer username password ipaddress port C fixflyer with properties User user Ipaddress 127 0 0 1 Port 7002 00 FlyerApplicationManager 1x1 flyer apps FlyerApplicationManager SessionID c is the FIX Flyer Engine connection object with these properties User name IP address e Port number FIX Flyer application manager instance FIX Flyer session identifier Close the FIX Flyer connection close c Create an Order Using FIX Flyer on page 1 19 fixflyer Input Arguments username FIX Flyer user name string FIX Flyer user name specified as a string Data Types char password FIX Flyer password string FIX Flyer password specified as a string Data Types char ipaddress IP address string IP address specified as a string to denote the IP address of the computer where the FIX Flyer Engine is running Example D
44. MESSAGE Route cancellation request sent to broker The default event handler processes the events associated with deleting the active shares deleteRoute returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection 4 41 A functions Alphabetical List 4 42 close c Delete Active Shares Using a Timeout To delete the active shares that are routed but not filled for a Bloomberg EMSX order 1 Create the connection c using emsx 2 Set up an order and route subscription using orders and routes 3 Create and route an order using createOrderAndRoute For an example showing these activities see Create and Manage a Bloomberg EMSX Route on page 3 16 Define the structure routenum that contains the order sequence number EMSX_SEQUENCE for the routed order and route number EMSX_ROUTE_ID routenum EMSX_SEQUENCE 335877 routenum EMSX_ROUTE_ID 1 Il Delete the active shares that are routed but not filled using the Bloomberg EMSX connection c and routenum Set the timeout value to 200 milliseconds options useDefaultEventHandler true options timeOut 200 events deleteRoute c routenum tim
45. Request intraday data using ib ibContract and these arguments Start date is this morning e End date is the current moment Aggregated every 10 minutes Tick typeis BID e Within regular trading hours startdate floor now enddate now barsize 10 mins 4 219 A functions Alphabetical List 4 220 ticktype BID tradehours true d timeseries ib ibContract startdate enddate barsize ticktype tradehours d Columns 1 through 5 735852 40 580 70 582 12 580 12 580 27 735852 40 580 27 580 75 579 70 579 80 735852 40 579 80 579 88 578 33 579 44 Columns 6 through 9 1 00 1 00 1 00 0 1 00 1 00 1 00 0 1 00 1 00 1 00 0 d returns the aggregated 10 minute data for BID tick type Each row in matrix d represents a 10 minute interval The columns in matrix d are Numeric representation of a date Open price High price Low price Close price e Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Display the high price for the most recent bar in matrix d d 1 3 ans 582 12 Close the IB Trader Workstation connection timeseries close ib Request Interactive Brokers Intraday Data Using an Event Handler To request intraday data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data
46. Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx ordernum Order numbers to delete structure integer Order numbers to delete specified as a structure or an integer to denote one or more order sequence numbers Data Types struct int32 timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure deleteOrder Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an
47. Sample Create a Stop Market Order Create a stop market order and set the order restriction to a stop order and a stop price orderProfile Set OrderType M orderProfile Set OrderRestr S orderProfile Set Stop 129800 3 9 3 Sample Code for Workflows 3 10 Sample Create a Stop Limit Order Create a stop limit order and set the order restriction type limit price and stop price orderProfile Set orderProfile Set orderProfile Set orderProfile Set OrderType L OrderRestr S Limit 128000 Stop 127500 a Ei i Check the Order Server Status Check the order server status before submitting the order and add a counter so the example doesn t delay nCounter 1 while exist bServerUp var amp amp nCounter lt 20 pause 1 nCounter nCounter 1 end Verify the Order Server Availability Verify that the exchange s order server in question is available before submitting the order if exist bServerUp var amp amp bServerUp submittedQuantity X OrderSet 1 SendOrder orderProfile disp Quantity Sent num2str submittedQuantity else disp Order Server is down Unable to submit order end Close the Connection close X See Also close createInstrument createOrderProfile createOrderSet xtrdr Related Examples Create an Order Using X_ TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Submit X_TRADE
48. The last command instructs X_TRADER to start monitoring the attached instruments using the specified event settings 3 6 Listen for X_TRADER Price Market Depth Updates Close the Connection close X See Also close createInstrument createNotifier getData xtrdr Related Examples Create an Order Using X_ TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Submit X_TRADER Orders on page 3 8 More About 2 Workflows for Trading Technologies X TRADER on page 2 4 3 7 3 Sample Code for Workflows Submit X_TRADER Orders 3 8 This example shows how to connect to X_TRADER and submit orders Connect to X_TRADER X xtrdr Create an Instrument createInstrument X Exchange CME Product 2F ProdType Future Contract Aug13 Alias SubmitOrderInstrument1 Register Event Handlers Register event handlers for the order server The callback ttorderserverstatus is assigned to the event OnExchangeStateUpdate to verify that the requested instrument s exchange order server is running Otherwise no orders can be submitted sExchange X Instrument Exchange registerevent X Gate OnExchangeStateUpdate varargin ttorderserverstatus varargin sExchange Create an Order Set The OrderSet object sends orders to X_TRADER Set properties of the OrderSet object and detail the level of the order status events Enable order update and rej
49. Timer Object timer 1 Timer Settings ExecutionMode fixedRate Period 1 BusyMode drop Running on Callbacks TimerFcn processEventToBlotter 1x1 emsx ErrorFcn StartFen 4 89 A functions Alphabetical List 4 90 StopFcn subs com bloomberglp blpapi SubscriptionList 3e24da58 emsxOrderBlotter returns the timer object output and the Bloomberg EMSX subscription list object For details about the timer object see timer EJ MSX Order Blotter LLL Sees File Edit View Insert Tools Desktop Window Help 7 SEQUENCE TICKER SIDE TYPE WORKING FILLED TIF BROKER STATUS HANDLING AVGPRC LMTPRC TRADER GTD STOPPRC 381417 GOOG BUY MKT 0 0 DAY B8 0 0 CGARVIN 0 381490 BM BUY MKT 0 250 DAY BB 189 79 0 CGARVIN 0 381491 BM BUY MKT 200 200 DAY B8 189 38 0 CGARVIN 0 381492 BM BUY MKT 0 DAY BB 0 0 CGARVIN 0 381494 BM BUY MKT 0 0 DAY BB 0 0 CGARVIN 0 381495 BM BUY MKT 0 0 DAY B8 0 0 CGARVIN 0 381496 BM BUY MKT 0 0 DAY BB 0 0 CGARVIN 0 J Update Orders Close The order blotter displays the current order information for a trader Create the order request structure order to define the order parameters This code creates a buy market order for 330 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 330 order EMSX_ORDER_TYPE
50. and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder history ibtws timeseries Introduced in R2015a 4 235 A functions Alphabetical List 4 236 executions Request Interactive Brokers execution data Syntax d executions ib filter d executions ib filter eventhandler Description d executions ib filter requests Interactive Brokers execution data using the IB Trader Workstation connection ib and the Interactive Brokers execution filter filter d executions ib filter eventhandler requests Interactive Brokers execution data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Request Execution Filter Data Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Create the IB Trader Workstation execution filter IEXecutionFilter object filter Here this object specifies these property values Buy side Stock security type Aggregate exchange Google symbol filter ib Handle cr
51. as an IB Trader Workstation connection object created using ibtws client Client flag true default false Client flag specified as a logical true denotes returning data from the current client only false denotes returning data from all clients Data Types logical eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types Function_handle char Output Arguments o Interactive Brokers open order data structure double Interactive Brokers open order data returned as a structure or an empty double The structure contains these fields Order type Event identifier Order identifier Contract data 4 255 A Functions Alphabetical List e Order data e Order status When using an event handler function 0 is an empty double More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors e Executing orders multiple times using t
52. connection specified as a connection object created using emsx More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal processEvent Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat deleteOrder deleteRoute emsx modifyOrder orders routeOrder routes Introduced in R2013a 4 95 A Functions Alphabetical List 4 96 routeOrder Route Bloomberg EMSX order Syntax events routeOrder c route events routeOrder c route timeOut timeout routeOrder useDefaultEventHandler false routeOrder c route options Description events routeOrder c route routes a Bloomberg EMSX order using the Bloomberg EMSX connection c and route request route routeOrder returns a status message using the default event handler events routeOrder c route timeOut timeout specifies a timeout value timeout for the execution of the default event handler routeOrder __ useDefaultEventHandler false routes a Bloomberg EMSX order using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with routing orders This syntax does not have an output a
53. contains a logical zero status has an entry for each FIX message in fixtable 4 279 A Functions Alphabetical List 4 280 The MATLAB Workspace variable fixResponseStruct contains the returned FIX messages from the FIX Flyer Engine Close the FIX Flyer Engine connection close c Create an Order Using FIX Flyer on page 1 19 Input Arguments c FIX Flyer Engine connection connection object FIX Flyer Engine connection specified as a connection object created using fixf lyer fixmsg FIX message table structure FIX message specified as a table or structure Example fixtable table FIX 4 4 FIX 4 4 338 339 2 2 datestr now datestr now D D ABC ABC fe A ed LOO AOOT Pim ere VariableNames BeginString CLOrdId Side TransactTime OrdType Symbol HandlInst OrderQty Data Types table struct Output Arguments status Send message status logical Send message status returned as an array of logical zeroes or ones The array contains an entry for each FIX message in fixmsg If a FIX message is sent successfully status contains a zero Otherwise Status contains a one sendMessage More About Workflow for FIX Flyer on page 2 10 FIX Trading Community See Also addListener close fixflyer Introduced in R2015b 4 281 A functions Alphabetical List 4 282 close Close FIX Flyer con
54. contents of the columns Event type Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 Input Arguments ib IB Trader Workstation connection connection object 4 243 1988 7 A Functions Alphabetical List 4 244 IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws ibContract IB Trader Workstation contract IContract object IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide depth IB Trader Workstation market depth ESZES Es IB Trader Workstation market depth specified as a scalar from one through 10 This number denotes the depth of the active book Data Types double eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types fu
55. create the Bloomberg EMSX connection c using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure ordernum that contains the order sequence number EMSX_SEQUENCE for the order to delete ordernum EMSX_SEQUENCE 335877 Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Delete the order using the Bloomberg EMSX connection c and ordernum Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with deleting an order deleteOrder deleteOrder c ordernum useDefaultEventHandler false Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes orders creates Subs Stop the timer to stop data updates using stop c Session unsubscribe subs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Delete an Order U
56. fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Delete an Order Using a Timeout To delete a Bloomberg EMSX order create the connection c using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure ordernum that contains the order sequence number EMSX_SEQUENCE for the order to delete ordernum EMSX_SEQUENCE 335877 Delete the order using the Bloomberg EMSX connection c and ordernum Set the timeout value to 200 milliseconds events deleteOrder c ordernum timeOut 200 events 4 35 A functions Alphabetical List 4 36 STATUS 0 MESSAGE Order deleted The default event handler processes the events associated with deleting the order deleteOrder returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Delete an Order Using a Custom Event Handler To delete a Bloomberg EMSX order
57. for instrument XYZ XYZ for the last 2 days instrument XYZ XYZ startdate now 2 enddate now timeseries c instrument startdate enddate MATLAB writes the structure variable cqgTickData to the Workspace browser Display cqgTickData cqgTickData cqgTickData Timestamp 2x1 cell Price 2x1 double Volume 2x1 double PriceType 2x1 cell CorrectionType 2x1 cell SalesConditionLabel 2x1 cell SalesConditionCode 2x1 double ContributorId 2x1 cell ContributorIdCode 2x1 double MarketState 2x1 cell cqgTickData returns intraday tick data for the specified instrument Display the data in the Timestamp property of cqgTickData cqgTickData Timestamp ans 4 17 2013 2 14 00 PM 4 18 2013 2 14 00 PM Close the CQG connection close c Request CQG Intraday Tick Data with Additional Properties To request intraday tick data for an instrument with an additional property create the connection C using cqg and startUp Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output 4 181 A functions Alphabetical List data structure For an example demonstrating these activities see Request CQG Intraday Tick Data on page 3 53 See CQG API Reference Guide to learn more about event handlers and the API configuration properties
58. from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs 4 59 A Functions Alphabetical List 4 60 c Session unsubscribe subs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx modorder Modify order request structure Modify order request specified as a structure that contains these fields Use getAllFieldMetaData to view all available fields for modorder Convert the numbers to 32 bit signed integers using int32 Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number EMSX_TICKER Bloomberg EMSX ticker symbol EMSX_AMOUNT Bloomberg EMSX number of shares Example modorder EMSX_SEQUENCE int32 728905 modorder EMSX_TICKER XYZ modorder EMSX AMOUNT int32 100 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer modifyOrder Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler c
59. handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure 4 21 A Functions Alphabetical List 4 22 Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx modifyOrder orders routeOrder routes start stop Introduced in R2013a createOrderAndRouteWithStrat createOrderAndRouteWithStrat Create and route Bloomberg EMSX order wit
60. ibFutures expiry 201312 5 Dec 2013 ibFutures exchange GLOBEX ibFutures currency USD Close the connection After retrieving data and sending orders close the IB Trader Workstation connection ib close ib See Also close createOrder getdata history ibtws Related Examples Create Interactive Brokers Combination Order on page 3 39 1 Getting Started Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 More About Workflow for Interactive Brokers on page 2 6 External Websites s http www interactivebrokers com en software api api htm 1 10 Create an Order Using CQG Create an Order Using CQG This example shows how to connect to CQG and create a market order Connect to CQG c cqg Establish event handlers Start the CQG session Set up event handlers for instrument subscription orders and associated events startUp c streamEventNames InstrumentSubscribed InstrumentChanged IncorrectSymbol for i 1 length streamEventNames registerevent c Handle streamEventNames i varargin cqgrealtimeeventhandler varargin end orderEventNames AccountChanged OrderChanged AllOrdersCanceled for i 1 length orderEventNames registerevent c Handle orderEventNames i varargin cqgordere
61. object ibContract IB Trader Workstation IOrder object ibOrder Unique order identifier id d createOrder ib ibContract ibOrder id Retrieve order information 0 o orders ib 0 1x2 struct array with fields Type EventID 4 249 A functions Alphabetical List 4 250 orderld contract order orderState o contains a structure array The array contains a structure with data for each open order The structure fields are Order type Event identifier Order identifier Contract data Order data Order status Retrieve the current status of the order o orderState ans status Submitted initMargin 1 7976931348623157E308 maintMargin 1 7976931348623157E308 orderState is a structure with fields corresponding to the status of the order The fields are order status initial margin and maintenance margin For details on these fields and the additional fields in orderState see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Request Open Order Data From All Clients Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values orders Google symbol Stock security type Aggregate exchange USD currency ibContract ib Handle createC
62. options specified by one or more Name Value pair arguments to specify a custom event handler or timeout value for the event handler events subs orders c fields options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The options structure fields and values correspond to names and values of name value pair arguments respectively Examples Subscribe to Order Events Using the Default Event Handler Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Subscribe to events for Bloomberg EMSX orders using the Bloomberg EMSX connection c and Bloomberg EMSxX field list fields orders fields EMSX_BROKER EMSX_AMOUNT EMSX_FILLED events subs orders c fields events MSG_TYPE E MSG_SUB_TYPE 0O EVENT_STATUS 4 subs com bloomberglp blpapi SubscriptionList 4bc3dc78 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Unsubscribe from order events using the Bloomberg EMSX subscription list object subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Subscribe to Order Events Using the Custom Event Handler Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Write a custom event handler function named eventhandler Run the custom event handler using timer Start the timer to run eventha
63. order using the Bloomberg EMSX connection c and route Set the timeout value to 200 milliseconds events routeOrder c route timeOut 200 events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed The default event handler processes the events associated with routing the order routeOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs routeOrder c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Route an Order Using a Custom Event Handler To route a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER
64. pause causes MATLAB to wait 2 seconds before continuing to give time for CQG to subscribe to the instrument Create the CQG instrument object To use the instrument in createOrder import the name of the instrument cqgInstrumentName into the current MATLAB workspace Then create the CQGInstrument object cqgInst cqgInstrumentName evalin base cqgInstrument cqgInst c Handle Instruments Item cqgInstrumentName Set Up Account Credentials Set the CQG flags to enable account information retrieval Create CQG Orders set c Handle AccountSubscriptionLevel aslNone set c Handle AccountSubscriptionLevel aslAccountUpdatesAndOrders pause 2 ans AccountChanged The CQG API shows that account information changed Set up the CQG account credentials Retrieve the CQGAccount object into accountHand1e to use your account information in createOrder For details about creating a CQGAccount object see CQG API Reference Guide accountHandle c Handle Accounts ItemByIndex 0 Create CQG Market Limit Stop and Stop Limit Orders Create a market order that buys one share of the subscribed security cqgInst using the account credentials accountHandle quantity 1 oMarket createOrder c cqgInst 1 accountHandle quantity oMarket Place ans OrderChanged The CQGOrder object oMarket contains the order The CQG API executes the market order using the CQG API function Place After execution the order sta
65. real time data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Set the Interactive Brokers field f to 233 to denote the tick type for RTVolume RTVolume contains these fields e Last trade price e Last trade size 4 265 A functions Alphabetical List Last trade time Total volume Volume weighted average price VWAP Single trade flag For details about RTVolume see Interactive Brokers API Reference Guide Request real time data using ib ibContract and f f 233 tickerid realtime ib ibContract fF tickerid 1 tickerid returns a number for tracking the real time data request The real time data is returned in the MATLAB workspace variable ibBuiltInRealtimeData Display this real time data ibBuiltInRealtimeData ibBuiltInRealtimeData id 1 BID_PRICE 584 65 BID_SIZE 1 ASK_PRICE 585 80 ASK_SIZE 1 LAST_PRICE 585 LAST_SIZE 1 VOLUME 11611 The structure ibBuiltInRealtimeData contains these fields Real time request identifier Bid price Bid size 4 266 realtime Ask price Ask size e Last price e Last size Vo
66. save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when the flag useDefaultEventHand1er is set to true and omit this output argument when useDefaultEventHand1ler is set to false modifyRouteWithStrat Examples Modify a Route with Strategies Using the Default Event Handler To modify a route for a Bloomberg EMSX order with strategies Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_F
67. the Bloomberg Desktop software license for the host on which Trading Toolbox and MATLAB software are running CQG 1 5 1 Getting Started FIX Flyer Interactive Brokers IB Trader Workstation Trading Technologies X_TRADER You must have a valid license for required client software on your machine For more information about how to obtain required software contact your trading system sales representative Create an Order Using IB Trader Workstation Create an Order Using IB Trader Workstation This example shows how to connect to the IB Trader Workstation retrieve historical data create a market order and specify a different instrument Run the IB Trader Workstation application Ensure the IB Trader Workstation application is running and that API connections are enabled You can do this from within IB Trader Workstation 1 Select File gt Global Configuration to open the Trader Workstation Configuration Simulated Trading dialog box 2 Select API gt Settings 3 Ensure that the Enable ActiveX and Socket Clients check box is selected Connect to the IB Trader Workstation Connect to the IB Trader Workstation and create connection ib using the local host and default port number 7496 ib ibtws 7496 When the Accept incoming connection attempt message appears in the IB Trader Workstation click Yes Retrieve historical and current data Create the IB Trader Workstation IContract object ib
68. the CQG API function Place After execution the order status changes Close the CQG connection shutDown c Create and Place a Market Order Using a CQG Instrument String To create and place a market order for shares of an instrument with the CQG Trader Com API using a string to specify the instrument create the connection C using Cqg and startUp Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register event handlers for tracking events associated with instrument subscription order and account Subscribe to the instrument Then set up the account credentials accountHand1Le For an example demonstrating these activities see Create CQG Orders on page 3 45 See CQG API Reference Guide to learn more about the event handlers and the API configuration properties Create a market order that buys one share of the previously subscribed security EZC using the defined account credentials accountHandle cqgInstrumentName EZC quantity 1 oMarket createOrder c cqgInstrumentName 1 accountHandle createOrder quantity oMarket Place ans OrderChanged The CQGOrder object oMarket contains the order The CQG API executes the market order using the CQG API function Place After execution the order status changes Close the CQG connection shutDown c Create and Place a Limit Order To create and place a limit order for shares of an i
69. ved ed eae ee ae es ee EP ee EE es 1 3 Interactive Brokers 0 0 0 0 cece ee eee 1 3 Trading Technologies 0 0 0 cee eee eee eens 1 4 Trading System Providers 0 0 00 cc eee ees 1 5 Supported Providers 0 00 eee ees 1 5 Connection Requirements 0 0 00 eee eee eee 1 5 Create an Order Using IB Trader Workstation 1 7 Create an Order Using CQG 00 00 00 cen 1 11 Create an Order Using Bloomberg EMSX 1 13 Create an Order Using X TRADER 1 16 Create an Order Using FIX Flyer 1 19 Writing and Running Custom Event Handler Functions with Bloomberg EMSX 0 0 0 0 0c cece eee 1 23 Write a Custom Event Handler Function 1 23 Run a Custom Event Handler Function 1 23 Workflow for Custom Event Handler Function 1 24 iii iv Contents Writing and Running Custom Event Handler Functions with Interactive Brokers 0 0 00 ccc eens 1 26 Write a Custom Event Handler Function 1 26 Run a Custom Event Handler Function 1 26 Workflow for Custom Event Handler Function 1 27 Workflow Models 2 Workflow for Bloomberg EMSX 2 2 Workflows for Trading Technologies X_TRADER 2 4 Workflow for Interactive Brokers 4 2 6 Request Interactive Brokers Market Data 2 6 Crea
70. where events EMSX_ SUCCESS ROUTES EMSX_SEQUENCE 335877 4 107 A Functions Alphabetical List 4 108 EMSX_ROUTE_ID 1 and events EMSX_FAILED ROUTES EMSX_SEQUENCE 335878 ERROR_CODE 0 ERROR_MESSAGE Order 335878 View only orders can not be routed The default event handler processes the events associated with routing the order groupRouteOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX success routing structure which contains the order number and route identifier for the orders that successfully routed Bloomberg EMSX failed routing structure which contains the order number error code and error message for the orders that failed to route Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Route Orders Using a Custom Event Handler To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers t
71. 0 tickerID realtime ib contracts f varargin ibExampleRealtimeEventHandler varargin MATLAB displays the figure populated with real time data for stock symbols AAA BBB and DDDD Trade Bid BidSize Ask AskSize Total Volume 787 3300 787 787 8000 1 306 28 3100 28 3100 28 3100 737 23 2300 23 1700 23 3500 Close the Connection Close the IB Trader Workstation connection ib close ib See Also close createOrder getdata history ibtws timeseries Related Examples x Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 3 37 3 Sample Code for Workflows Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 More About Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 External Websites Interactive Brokers API Reference Guide 3 38 Create Interactive Brokers Combination Order Create Interactive Brokers Combination Order This example shows how to connect to the IB Trader Workstation create IB Trader Workstation IContract and IComboLegList objects and create a combination order for a calendar spread A calendar spread is one of many combination order strategies This strategy takes advantage of different stock op
72. 0 routenum EMSX_ROUTE_ID 0 Il Delete the route using the Bloomberg EMSX connection c and delete route number structure routenum events deleteRoute c routenum events STATUS 1 Manage a Bloomberg EMSX Order and Route MESSAGE Route cancellation request sent to broker The default event handler processes the events associated with deleting a route deleteRoute returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Stop the Order and Route Subscription Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX Connection close c See Also close createOrderAndRoute deleteRoute emsx modifyRoute orders routes Related Examples Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 More About Workflow for Bloomberg EMSX on page 2 2 3 25 3 Sample Code for Workflows Create and Manage an Interactive Brokers Order 3 26 This example shows how to connect to the IB Trader Workstation request open order data create an IB Trader Workstation IContract object create an IB Trader Workstation IOrde
73. 0 1991 75 1763 1991 5 2117 The first column contains the bid price and the second column contains the bid size Close the IB Trader Workstation connection close ib Request Market Depth Data Using an Event Handler To request Interactive Brokers market depth data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request market depth data using ib and ibContract Specify five price levels for the bid and offer sides for depth This code assumes ibContract is an E mini S amp P 500 futures contract with an expiry of December 2014 that trades on the CME Globex exchange Use the sample event handler function ipbExampleEventHandler or write a custom event handler function depth 5 marketdepth marketdepth ib ibContract depth ibExampleEventHandler 8147 1x1 COM TWS_TwsCtr1_1 16 00 8147 00 0 0 1 00 d is the request identifier After d ibExampleEventHandler streams market depth data to the Command Window The columns are Interactive Brokers ActiveX object Event identifier Request identifier Position Operation Side Price Size Structure that repeats the
74. 1 cell IsValid 15x1 cell Instrument 15x1 cell HasVolume 15x1 cell cqgDataEZC returns the current quotes for the security Display data in the Price property of cqgDataEZC cqgDataEZC 1 1 Price ans 2 1475e 09 2 1475e 09 Request CQG Real Time Data 2 1475e 09 660 5000 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 660 5000 2 1475e 09 gn a A MPNMNNMNNND PP Close the CQG Connection close c See Also close cqg createOrder history realtime shutDown startuUp timeseries Related Examples Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 More About Workflow for CQG on page 2 8 External Websites CQG API Reference Guide 3 59 Functions Alphabetical List A functions Alphabetical List 4 2 emsx Create Bloomberg EMSX connection Syntax c emsx servicename Description c emsx servicename creates a connection to the local Bloomberg EMSX communications server using the service servicename Examples Connect to the Bloomberg EMSX Test Service Create a connection Cc to the Bloomberg EMSxX test service You can place test calls using this service c emsx blp emapisvc_beta C emsx with properties Session 1x1 com bloomberglp blpapi
75. 100 shares of IBM to the broker BMTB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_ STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler routeOrderWithStrat immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Route the order using the Bloomberg EMSX connection c route and strat Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with routing an order routeOrderWithStrat c route strat useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs S
76. 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx 4 5 A functions Alphabetical List More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 See Also createOrder createOrderAndRoute emsx routeOrder Introduced in R2013a 4 6 createOrder createOrder Create Bloomberg EMSX order Syntax events createOrder c order events createOrder c order timeOut timeout createOrder useDefaultEventHandler false createOrder c order options Description events createOrder c order creates a Bloomberg EMSX order using the Bloomberg EMSX connection c and order request order that contains the required fields for creating an order createOrder returns the order sequence number and status message using the default event handler events createOrder c order timeOut timeout specifies a timeout value timeout for the execution of the default event handler createOrder _ useDefaultEventHandler false creates a Bloomberg EMSX order using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with creating orders This syntax does not have an outp
77. 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP 4 25 A functions Alphabetical List 4 26 strat EMSX_STRATEGY_FIELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create and route the order with strategies using the Bloomberg EMSX connection C order and strat Set the timeout value to 200 milliseconds events createOrderAndRouteWithStrat c order strat timeOut 200 events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRouteWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create
78. 32 728918 route EMSX_TICKER XYZ groupRouteOrderWithStrat route EMSX_ AMOUNT int32 100 route EMSX BROKER BB route EMSX HAND INSTRUCTION ANY route EMSX TIF DAY route EMSX ORDER TYPE MKT Data Types struct strat Order strategies structure Order strategies specified as a structure that contains the fields EMSX_STRATEGY_NAME EMSX_STRATEGY_FIELD_ INDICATORS and EMSX_STRATEGY_FIELDS The structure field values must align with the strategy fields specified by EMSX_STRATEGY_NAME For details about strategy fields and ordering see getBrokerInfo Convert EMSX_STRATEGY_FIELD_ INDICATORS to a 32 bit signed integer using int32 Set EMSX_STRATEGY_FIELD_ INDICATORS equal to 0 for each field to use the field data setting in EMSX_FIELD_ DATA Or set EMSX_STRATEGY_ FIELD INDICATORS equal to 1 to ignore the data in EMSX_FIELD_DATA Example strat EMSX_STRATEGY NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value
79. 4 63 A functions Alphabetical List 4 64 Examples Modify a Route Using the Default Event Handler To modify a route for a Bloomberg EMSX order Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code instructs Bloomberg EMSX to route 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 Modify the route using the Bloomberg EMSX connection c and modroute events modifyRoute c modroute events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRoute returns events as a structure that contains these fields modifyRoute Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from o
80. 5 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 22222 DONEN MORNY DONNY DONEN robe nde arr fo 19 Ro 19 D DUNS cqgTimedBarData returns timed bar data for the specified instrument The columns of cqgTimedBarData display data corresponding to the timestamp open price high price low price close price mid price HLC3 average price and tick volume timeseries Close the CQG connection close c Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 Input Arguments c CQG connection connection object CQG connection specified as a CQG connection object created using cqg s CQG instrument name string CQG instrument name specified as a string identifying the instrument or security Data Types char startdate Start date date string date scalar Start date specified as a starting date string or scalar Data Types double char enddate End date date string date scalar End date specified as an ending date string or scalar Data Types double char intraday Aggregated bar value scalar Aggregated bar value specified as a scalar from 1 0 to 1440 0 If you want to call timeseries to return intraday tick data with additional
81. 500 Data Types struct Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example useDefaultEventHandler false useDefaultEventHandler Flag for event handler preference true default false Flag for event handler preference indicating whether to use the default or custom event handler to process order events specified as the comma separated pair consisting of useDefaultEventHandler and the logical values true or false To specify the default event handler set this flag to true Otherwise set this flag to false to specify a custom event handler Data Types logical timeOut Timeout value for event handler 500 milliseconds default nonnegative integer Timeout value for event handler for the Bloomberg EMSX service specified as the comma separated pair consisting of timeOut and a nonnegative integer in units of milliseconds Example timeOut 200 4 87 A Functions Alphabetical List 4 88 Data Types double Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the even
82. 6113 BID_PRICE 34 92 BID_SIZE 157 ASK_PRICE 34 93 ASK_SIZE 129 Create a trade market order The IB Trader Workstation supports a variety of order types including basic types such as limit orders stop orders and market orders For this example set up a stock contract for Microsoft stock After setting the order type as MKT then specify the action in this case BUY and the total quantity to trade ibMktOrder ib Handle createOrder ibMktOrder action BUY ibMktOrder totalQuantity 100 ibMktOrder orderType MKT Set a unique order identifier and send the orders to Interactive Brokers Create an Order Using IB Trader Workstation id orderid ib result createOrder ib ibContract ibMktOrder id result STATUS Filled FILLED 100 REMAINING O0 AVG_FILL_PRICE 34 93 PERM_ID 456471585 PARENT_ID O LAST_FILL_PRICE 34 93 CLIENT ID 0 WHY_HELD Specify a different instrument You can trade a variety of instruments using the IB Trader Workstation API including equities futures options futures options and foreign currencies Here use the E mini Standard and Poor s 500 futures contract on the CME Globex with a December 2013 expiry Specify the symbol as ES the security type to be a futures contract FUT the expiry in a YYYYMM date format the exchange as GLOBEX and the currency as USD ibFutures ib Handle createContract ibFutures symbol ES ibFutures secType FUT
83. Bloomberg EMSX order order and timer object t 1 Run timer to execute eventhandler The name value pair argument TimerFcn specifies the event handler function The name value pair argument Period specifies a 1 second delay between executions of the event handler function When the name value pair argument ExecutionMode is set to fixedRate the event 1 23 1 Getting Started 1 24 handler function executes immediately after it is added to the MATLAB execution queue t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate Start the timer to initiate and execute eventhandler immediately start t Run createOrderAndRoute using the custom event handler by setting useDefaultEventHandler to false createOrderAndRoute c order useDefaultEventHandler false Stop the timer to stop data updates stop t If you want to resume data updates run start Delete the timer once you are done with processing data updates for the Bloomberg EMSX connection delete t Workflow for Custom Event Handler Function This workflow summarizes the tasks to work with a custom event handler function using Bloomberg EMSX 1 2 3 Write a custom event handler function and save it to a file Create a connection using emsx Subscribe to Bloomberg EMSxX fields using orders and routes You can also write custom event handler functions to process subscription events Run the custom event handler function usin
84. C using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure modorder that contains the order sequence number EMSX_SEQUENCE the security EMSX_TICKER and the number of shares EMSX_AMOUNT This code modifies the order number 728905 for 200 shares of IBM Convert the numbers to 32 bit signed integers using int32 modorder EMSX_SEQUENCE int32 728905 modorder EMSX_TICKER IBM modorder EMSX_AMOUNT int32 200 Modify the order using the Bloomberg EMSX connection c and modorder Set the timeout value to 200 milliseconds events modifyOrder c modorder timeOut 200 events EMSX_SEQUENCE 728905 MESSAGE Order Modified The default event handler processes the events associated with modifying the order modifyOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection 4 57 A functions Alphabetical List 4 58 close c Modify an Order Using a Custom Event Handler To modify a Bloomberg EMSX order create the Bloomberg EMSX connection c using emsx set up the order subscription using order
85. CQG using startUp hon Create the CQG account credentials object 2 8 Workflow for CQG 5 Subscribe to a CQG instrument to request real time data using realtime 6 Create and submit the order using createOrder 7 Close the CQG connection using close or shutDown Related Examples Create an Order Using CQQ on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 2 9 2 Workflow Models Workflow for FIX Flyer 2 10 In this section Create a FIX Message on page 2 10 Request Data and Create Orders Using FIX Messages on page 2 10 Receive a FIX Message on page 2 11 Send FIX messages using the FIX Flyer Engine to e Request market data Create and manage orders Request news information Request other available information using the FIX protocol Create a FIX Message Create a FIX message using a structure array or table To convert between structure arrays or tables and FIX message strings use these functions 1 Convert a structure array that contains FIX tags as fields to a cell array of FIX message strings using struct2Ffix 2 Convert a table that contains FIX tags as variables to a cell array of FIX message strings using table2Ffix Request Data and Create Orders Using FIX Messages To request market data submit orders
86. Contract This object denotes the security For this example get data for Microsoft MSFT stock Specifying SMART as the exchange lets Interactive Brokers determine which venues to get data from Setting the currency type to USD clarifies that you want dollar denominated stock This is useful when stocks are dual listed or multi listed across different jurisdictions ibContract ib Handle createContract ibContract symbol MSFT ibContract secType STK ibContract exchange SMART ibContract currency USD Define the period for which you need data for example the last 20 business days excluding today bizDayConvention 13 i e BUS 252 1 7 1 Getting Started startDate endDate daysadd today 20 bizDayConvention daysadd today 1 bizDayConvention This code uses the daysadd function from Financial Toolbox to compute the appropriate start and end dates Retrieve historical data for the last 20 business days histTradeData history ib ibContract startDate endDate Note The history function accepts additional parameters that let you obtain other historical data such as option implied volatility historical volatility bid prices ask prices or midpoints If you do not specify anything the default data returned are last traded prices Retrieve current price data from the contract currentData getdata ib ibContract currentData LAST_PRICE 34 93 LAST_SIZE 1 VOLUME 6
87. Create CQG Orders on page 3 45 Request CQG Real Time Data on page 3 57 Request CQG Intraday Tick Data on page 3 53 More About Workflow for CQG on page 2 8 External Websites CQG API Reference Guide Request CQG Intraday Tick Data Request CQG Intraday Tick Data This example shows how to connect to CQG define event handlers and request intraday and timed bar data Connect to CQG and Define Event Handlers Create the CQG connection object using cqg c cqg Register the sample event handler cqgconnectioneventhandler to track events associated with the connection status eventNames CELStarted DataError IsReady DataConnectionStatusChanged for i 1 length eventNames registerevent c Handle eventNames i varargin cqgconnectioneventhandler varargin end cqgconnectioneventhandler is assigned to the events in eventNames Set the API configuration properties For example to set the time zone to Eastern Time enter the following c APIConfig TimeZoneCode tzEastern c APIConfig is a CQG configuration object For details about setting API configuration properties see CQG API Reference Guide Create the CQG connection startUp c CELStarted DataConnectionStatusChanged The connection event handler displays event names for a successful CQG connection Register an event handler to build and initialize the output data structure cqgTickData used for st
88. D INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Route the orders using the Bloomberg EMSX connection c route and strat events groupRouteOrderWithStrat c route strat events 4 105 A Functions Alphabetical List 4 106 EMSX_SUCCESS_ ROUTES 1x1 struct EMSX_FAILED_ ROUTES 1x1 struct MESSAGE 1 of 1 Order s Routed where events EMSX_ SUCCESS ROUTES EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 and events EMSX_FAILED ROUTES EMSX_SEQUENCE 335878 ERROR_CODE 0 ERROR_MESSAGE Order 335878 View only orders can not be routed The default event handler processes the events associated with routing the order groupRouteOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX success routing structure which contains the order number and route identifier for the orders that successfully routed Bloomberg EMSX failed routing structure which contains the order number error code and error message for the orders that failed to route Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Route Orders Using a Timeout To route a Bloomberg EMSX order with strategies create the connect
89. E 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Modify the Route Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 50 shares of IBM for order sequence number 335877 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 335877 modroute EMSX_TICKER IBM modroute EMSX_AMOUNT int32 50 modroute EMSX_ROUTE_ID int32 1 Modify the route using the Bloomberg EMSX connection c and modify route request modroute events modifyRoute c modroute events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRoute returns events as a structure that contains these fields Create and Manage a Bloomberg EMSX Route Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Delete the Modified Route Define the structure routenum t
90. EMSX connection c and structure brokerstrat brokerstrat EMSX_TICKER ABCD US Equity r getBrokerInfo c brokerstrat r EMSX_BROKERS 2x1 cell The EMSX_BROKERS field lists the Bloomberg EMSX brokers Close the Bloomberg EMSX connection 4 51 A functions Alphabetical List 4 52 close c Obtain Strategy Information Create a connection C to the Bloomberg EMSX c emsx blp emapisvc_beta Define the broker and strategy information structure brokerstrat Obtain strategy information using the Bloomberg EMSX connection c and structure brokerstrat brokerstrat EMSX_TICKER brokerstrat EMSX_BROKER ABCD US Equity BMTB r getBrokerInfo c brokerstrat r EMSX_STRATEGIES 16x1 cell The EMSX_STRATEGIES field lists the Bloomberg EMSX strategies Close the Bloomberg EMSX connection close c Obtain Field Information Create a connection C to the Bloomberg EMSX c emsx blp emapisvc_beta Define the broker and strategy information structure brokerstrat Obtain field information using the Bloomberg EMSX connection c and structure brokerstrat brokerstrat EMSX_TICKER ABCD US Equity brokerstrat EMSX_BROKER BMTB brokerstrat EMSX_STRATEGY SSP r getBrokerInfo c brokerstrat r FieldName 3x1 cell getBrokerInfo Disable 3x1 cell StringValue 3x1 cell The structure field FieldName lists the Bloomberg EMSX fields The structure fields Disable and StringVa
91. EMSX subscription list object Unsubscribe from order events using the Bloomberg EMSX subscription list object subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx fields Bloomberg EMSX field information cell array Bloomberg EMSX field information specified using a cell array Use getAllFieldMetaData to view available field information for the Bloomberg EMSX service Example EMSX_TICKER EMSX_AMOUNT EMSX_ORDER_TYPE Data Types cell options Options for custom event handler or timeout value structure orders Options for custom event handler or timeout value specified as a structure Use the options structure instead of name value pair arguments to reuse the optional name value pair arguments to specify a custom event handler or timeout value for the event handler The options structure field and values correspond to names and values of the name value pair arguments respectively Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut
92. ER API See Also createInstrument xtrdr Introduced in R2013a 4 156 cag cqg Create CQG connection object Syntax c cqg Description c cqg creates a CQG connection object C Examples Create the CQG Connection Object Create the CQG connection object using cqg c cqg c cqg with properties Handle 1x1 COM CQG_CQGCEL_4 APIConfig 1x1 Interface CQG_4 0_Type_Library_ _Revised_API ICQGAPIConfig CQG connection object properties reflect the CQG ActiveX object Handle and the API configuration type library specification APIConfig Display the Handle property of c c Handle ans COM CQG_CQGCEL_4 Close the CQG connection 4 157 A Functions Alphabetical List 4 158 close c Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 Output Arguments c CQG connection connection object CQG connection returned as a CQG connection object The properties of this object are as follows Property Description Handle CQG ActiveX object APIConfig API configuration type library specification These properties are determined by the CQG API More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also close startUp Introduced in R2013b close close Close CQG
93. FIX sessions and set up the FIX Flyer Application Manager Register with the FIX Flyer session Connect the FIX Flyer Application Manager to the FIX Flyer Engine and start the internal receiving thread c SessionID flyer core session SessionID Alpha Beta FIX 4 4 c FlyerApplicationManager registerFIXSession flyer apps FixSessionSubscription c SessionID true 0 c FlyerApplicationManager connect c FlyerApplicationManager start Create a FIX message using a table fixtable This table contains two FIX messages The first row in the table represents a sell side transaction for 100 shares of symbol ABC The order type is a previously quoted order The order handling instruction is a private automated execution The order transaction time is the current moment The second row in the table has the same order field variables except that the order identifier is unique across orders The FIX protocol version is 4 4 fixtable table FIX 4 4 FIX 4 4 338 339 2 2 datestr now datestr now D D ABC ABC a ey OOF BOOP hse amp VariableNames BeginString CLOrdId Side TransactTime OrdType Symbol HandlInst OrderQty Send the FIX message using the FIX message fixtable status sendMessage c fixtable status 0 0 status contains the FIX Flyer Engine message status for each FIX message sent If the FIX message is sent successfully status
94. IELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Modify the route using the Bloomberg EMSX connection c modroute and strat events modifyRouteWithStrat c modroute strat events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 4 73 A Functions Alphabetical List 4 74 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRouteWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Modify a Route with Strategies Using a Timeout To modify a route for a Bloomberg EMSX order with strategies Create the connection C using emsx Set up the order and route subscription using orders and routes e Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares E
95. List 4 180 timeseries Request CQG intraday tick data Syntax timeseries c s startdate enddate timeseries c s startdate enddate x timeseries c s startdate enddate intraday timeseries c s startdate enddate intraday x Description timeseries c s startdate enddate requests CQG raw intraday tick data asynchronously between startdate and enddate for CQG instrument name s with CQG connection C timeseries c s startdate enddate x requests CQG raw intraday tick data asynchronously without timed bar data using additional request properties X timeseries c s startdate enddate intraday requests CQG timed bar data asynchronously with the aggregated bar value intraday timeseries c s startdate enddate intraday x requests CQG timed bar data asynchronously with additional request properties x Examples Request CQG Intraday Tick Data To request intraday tick data for an instrument create the connection C using cqg and startUp Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output data structure For an example demonstrating these activities see Request CQG Intraday Tick Data on page 3 53 See CQG API Reference Guide to learn more about event handlers and the API configuration properties timeseries Request intraday tick data
96. MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_INSTRUCTION ANY order EMSX_SIDE BUY Create and route the order using the Bloomberg EMSX connection c and the order request structure order Use the custom event handler processEventToBlotter by setting the name value pair argument useDefaultEventHandler to false events createOrderAndRoute c order useDefaultEventHandler false emsxOrderBlotter events CreateOrderAndRoute EMSX_SEQUENCE 381499 1 EMSX_ROUTE_ID MESSAGE Order created and routed createOrderAndRoute creates the order routes the order and returns a structure events that contains an empty double processEventToBlotter displays output from createOrderAndRoute with the order number EMSX_SEQUENCE route number EMSX_ROUTE_ID and message Order created and routed File Edit View Insert Tools Desktop Window Help a SEQUENCE TICKER SIDE TYPE WORKING FILLED TIF BROKER STATUS HANDLING AVGPRC LMTPRC TRADER GTD STOPPRC 381417 GOOG BUY MKT 0 0 DAY BB 0 0 CGARVIN 0 381490 IBM BUY MKT 0 250 DAY BB 189 79 0 CGARVIN o 381491 BM BUY MKT 200 200 DAY BB 189 38 0 CGARVIN 0 381492 IBM BUY MKT 0 DAY BB o 0 CGARVIN o 381494 IBM BUY MKT 0 0 DAY BB 0 CGARVIN 0 381495 IBM BUY MKT 0 0 DAY BB 0 0 CGARVIN 0 381496 IBM BUY MKT 0 0 DAY BB o 0 CGARVIN o 381499 IBM US Equity BUY 0 0 DAY BB NEW ANY o 0 CGARVIN 0 0 cose The order blotter updates us
97. MSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modifyRouteWithStrat modroute EMSX_TICKER IBM modroute EMSX_AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_FIELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Modify the route using the Bloomberg EMSX connection c modroute and strat Set the timeout value to 200 milliseconds events modifyRouteWithStrat c modroute strat timeOut 200 events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRouteWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX con
98. Object Create the IB Trader Workstation IComboLegList object comboLegs to define the legs of the combination order comboLegs ib Handle createComboLegList Here this combination order has two legs Add the first leg to comboLegs The first leg contains these property values IB Trader Workstation IContract object ibContract1 One to one leg ratio Sell the call option Aggregate exchange Identify an open or close order based on the parent security IB Trader Workstation routes the order without a designated broker e Blank designated broker ibLegi comboLegs Add ibLeg1 conId ibContractID1 ibLegi ratio 1 ibLeg1 action SELL ibLegi exchange SMART ibLeg1 openClose 0 ibLeg1 shortSaleSlot 0 ibLeg1 designatedLocation Add the second leg to comboLegs The second leg contains these property values IB Trader Workstation IContract object ibContract2 One to one leg ratio Buy the call option 3 41 3 Sample Code for Workflows 3 42 Aggregate exchange Identify an open or close order based on the parent security IB Trader Workstation routes the order without a designated broker e Blank designated broker ibLeg2 comboLegs Add ibLeg2 conId ibContractID2 ibLeg2 ratio 1 ibLeg2 action BUY ibLeg2 exchange SMART ibLeg2 openClose 0 ibLeg2 shortSaleSlot 0 ibLeg2 designatedLocation Create the Interactive Brokers Combina
99. Order routes start stop Introduced in R2013a 4 123 A functions Alphabetical List 4 124 routes Obtain Bloomberg EMSX route subscription Syntax events subs routes c fields events subs routes c fields Name Value events subs routes c fields options Description events subs routes c fields subscribes to Bloomberg EMSX fields fields using the Bloomberg EMSX connection c routes returns existing event data events from the event queue and the Bloomberg EMSX subscription list subs events subs routes c fields Name Value uses additional options specified by one or more Name Value pair arguments to specify a custom event handler or timeout value for the event handler events subs routes c fields options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The options structure fields and values correspond to names and values of name value pair arguments respectively Examples Set Up Route Subscription Using the Default Event Handler Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Set up the route subscription for Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c routes fields EMSX_BROKER EMSX_WORKING events subs routes c fields events MSG_TYPE 5x1 cell MSG_SUB_ TYPE 5x1 cell EVENT_STATUS 5x1 int32 subs
100. P address ipaddress e Port number port username user password pwd ipaddress 127 0 0 1 port 7002 c fixflyer username password ipaddress port Add the FIX Flyer event listener to the FIX Flyer Engine connection c To listen for and display the FIX Flyer Engine event data in the Workspace browser use the sample event handling listener fixExampleListener Use fixExampleListener or write a custom event handling listener function 4 275 A Functions Alphabetical List 4 276 fixExampleListener handles the FIX Flyer Engine events e denotes these events You can specify e as any letter lh addListener c e fixExampleListener e fixExampleListener returns a handle to the listener 1h When events occur fixExampleListener returns event data to objects in the MATLAB Workspace To view event data double click the object The Variables dialog box displays the data in the object Close the FIX Flyer Engine connection close c 7 Create an Order Using FIX Flyer on page 1 19 Input Arguments c FIX Flyer Engine connection connection object FIX Flyer Engine connection specified as a connection object created using fixf lyer listener Listener event handler function Listener event handler specified as a function handle to listen for FIX Flyer Engine event data You can modify the existing listener function or define your own You can find the code for the existing listener functi
101. R Orders Listen for X_TRADER Price Market Depth Updates on page 3 4 More About 7 Workflows for Trading Technologies X TRADER on page 2 4 3 11 3 Sample Code for Workflows Create and Manage a Bloomberg EMSX Order This example shows how to connect to Bloomberg EMSX create an order and interact with the order For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Connect to Bloomberg EMSX Connect to the Bloomberg EMSxX test service Display the current event queue contents using processEvent c emsx blp emapisvc_beta processEvent c G emsx with properties Session 1x1 com bloomberglp blpapi Session Service 1x1 com bloomberglp blpapi impl aQ Ipaddress localhost Port 8194 SessionConnectionUp server localhost 127 0 0 1 8194 SessionStarted ServiceOpened serviceName blp emapisvc_beta MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSX test service Port number of the machine running the Bloomberg EMSX test service Create and Manage a Bloomberg EMSX Order processEvent displays events associated with connecting to Bloomberg EMSX Set Up the Order Subscription Subscribe to order events using the Blo
102. SX HAND INSTRUCTION ANY order EMSX_SIDE BUY Data Types struct strat Order strategies structure Order strategies specified as a structure that contains the fields EMSX_STRATEGY_NAME EMSX_ STRATEGY FIELD INDICATORS and EMSX_STRATEGY_FIELDS The structure field values must align with the strategy fields specified by EMSX_STRATEGY_NAME For details about strategy fields and ordering see getBrokerInfo Convert EMSX_STRATEGY_FIELD_ INDICATORS to a 32 bit signed integer using int32 Set EMSX_STRATEGY_FIELD_ INDICATORS equal to 0 for each field to use the field data setting in EMSX_FIELD_ DATA Or set EMSX_STRATEGY_ FIELD INDICATORS equal to 1 to ignore the data in EMSX_FIELD_DATA Example strat EMSX_STRATEGY NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer createOrderAndRouteWithStrat Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom even
103. Session Service 1x1 com bloomberglp blpapi impl aQ Ipaddress localhost Port 8194 MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSxX test service Port number of the machine running the Bloomberg EMSX test service emsx Close the Bloomberg EMSX connection close c Connect to the Bloomberg EMSX Production Service Create a connection to the Bloomberg EMSX production service You can place live calls using this service c emsx bmp emapisvc C emsx with properties Session 1x1 com bloomberglp blpapi Session Service 1x1 com bloomberglp blpapi impl aQ Ipaddress localhost Port 8194 MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSX production service Port number of the machine running the Bloomberg EMSX production service Close the Bloomberg EMSX connection close c Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments servicename Bloomberg EMSX service name st
104. TICKER Bloomberg EMSX number of shares EMSX_AMOUNT This code modifies order number 354646 for 200 shares of IBM Convert the numbers to 32 bit signed integers using int32 modorder EMSX_SEQUENCE int32 354646 modorder EMSX_TICKER IBM modorder EMSX_AMOUNT int32 200 Modify the order using the Bloomberg EMSX connection c and modify order structure modorder events modifyOrder c modorder events EMSX_SEQUENCE 354646 MESSAGE Order Modified The default event handler processes the events associated with modifying an order modifyOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Delete the Order Define the structure ordernum that contains the order sequence number 354646 for the order to delete Delete the order using the Bloomberg EMSX connection c and the delete order number structure ordernum Create and Manage a Bloomberg EMSX Order ordernum EMSX_SEQUENCE 354646 events deleteOrder c ordernum events STATUS 0 MESSAGE Order deleted The default event handler processes the events associated with deleting an order deleteOrder returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Stop the Order Subscription Unsubscribe from order events using the Bloomberg EMSX subscription list object subs c Session unsubscribe subs Close the Bloomberg EMSX Connection
105. TK ibContract exchange SMART ibContract currency USD For details about the IContract object see Interactive Brokers API Reference Guide Request contract details data using ib ibContract and sample event handler function ibExampleEventHandler Use ibExampleEventHandler or write a custom event handler function d reqid contractdetails ib ibContract ibExampleEventHandler d 1269 reqid 1269 Columns 1 through 4 1x1 COM TWS_TwsCtrl_1 100 1269 1x1 Interface Tws_ActivexX_Control_m Columns 5 through 6 1x1 struct contractDetailsEx d and reqid return a number that Interactive Brokers uses to track this contract details data request After these variables ipbExampleEventHand1ler returns contract details data to the Command Window The columns are Interactive Brokers ActiveX object Event identifier 4 233 A Functions Alphabetical List 4 234 Request identifier Contract details ActiveX object Structure that repeats the contents of the columns Request type For details about this data see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws ibContract IB Trader Wor
106. T_ID O LAST_FILL_PRICE 787 5600 CLIENT_ID 0 WHY_HELD d contains these fields Status gt Filled e Remaining Average fill price Permanent identifier e Parent identifier Last fill price Client identifier Why held Display the data in the STATUS property of d d 1 1 STATUS ans 4 194 createOrder Filled Close the IB Trader Workstation connection close ib Create an Order Using an Event Handler To create an order set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract An IContract object is an Interactive Brokers object for containing the data about a security to process transactions Then create an IB Trader Workstation IOrder object ibOrder An IOrder object is an Interactive Brokers object that contains the order conditions to place an order For an example showing how to create these objects see Create and Manage an Interactive Brokers Order on page 3 26 For details about creating these objects see Interactive Brokers API Reference Guide Obtain the next valid order identification number id using ib id orderid ib id 768409 00 Execute the order using ib ibContract ibOrder and id This code assumes a buy market order for two shares Use the sample event handler function ibExampleEventHandler or write a custom event handler function d createOrder ib ibContract ibOrder id ibExampleEventHandler
107. Trader Workstation on page 1 7 e Create an Order Using CQG on page 1 11 Create an Order Using Bloomberg EMSX on page 1 13 e Create an Order Using X_TRADER on page 1 16 Create an Order Using FIX Flyer on page 1 19 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 1 Getting Started Trading Toolbox Product Description Access prices and send orders to trading systems Trading Toolbox provides functions for accessing trade and quote pricing data defining order types and sending orders to financial trading markets The toolbox lets you integrate streaming and event based data into MATLAB enabling you to develop financial trading strategies and algorithms that analyze and react to the market in real time You can build algorithmic or automated trading strategies that work across multiple asset classes instrument types and trading markets while integrating with industry standard trade execution platforms With Trading Toolbox you can subscribe to streams of tradable instrument data including quotes volumes trades market depth and instrument metadata You also can define order types and instructions for how to route and fill orders Trading Toolbox supports Bloomberg EMSX CQG Integrated Client Interactive Brokers TWS FIX Flyer and Trading Technolo
108. Trading Toolbox User s Guide R2015b How to Contact MathWorks Latest news www mathworks com Sales and services www mathworks com sales_and_ services User community www mathworks com matlabcentral Technical support www mathworks com support contact_us Phone 508 647 7000 The MathWorks Inc 3 Apple Hill Drive Natick MA 01760 2098 Trading Toolbox User s Guide COPYRIGHT 2013 2015 by The MathWorks Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks Inc FEDERAL ACQUISITION This provision applies to all acquisitions of the Program and Documentation by for or through the federal government of the United States By accepting delivery of the Program or Documentation the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12 212 DFARS Part 227 72 and DFARS 252 227 7014 Accordingly the terms and conditions of this Agreement and only those rights specified in this Agreement shall pertain to and govern the use modification reproduction release performance display and disclosure of the Program and Documentation by the federal government or other en
109. Types Function_handle char Output Arguments d Interactive Brokers historical data matrix double Interactive Brokers historical data returned as a matrix with these columns Numeric representation of a date history Open price High price Low price Close price Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar When using an event handler function d is a double denoting the request identifier More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors i Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder getdata ibtws realtime timeseries Introduced in R2013b 4 215 A Functions Alphabetical List 4 216 timeseries Request Interactive Brokers aggregated intraday data Syntax d timeseries ib ibContract startdate enddate barsize d timeseries ib ibContract startdate enddate barsize ticktype d timeseries ib ibContract startdate enddate barsize ticktype tradehours d timeseries ib ibContract startdate enddate barsize tickty
110. Updates 0 Data Types char Property2 Valid X_TRADER API options string Valid X_TRADER API options specified using the details described in Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example createNotifier X Instrument UpdateFilter EnablePriceUpdates 1 EnableDepthUpdates 0 DebugLogL DeliverAllPriceUpdates 0 Data Types char More About Workflows for Trading Technologies X TRADER on page 2 4 X_TRADER API See Also createInstrument createOrderProfile createOrderSet xtrdr Introduced in R2013a 4 145 A functions Alphabetical List 4 146 createOrderProfile Create order profile for X_TRADER Syntax P createOrderProfile X S P createOrderProfile X Name Value Description P createOrderProfile X S creates an order profile defined by the structure S with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference P createOrderProfile X Name Value creates an order profile using X_TRADER API options specified by one or more Name Value pair arguments with names and values corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Examples Create an Order Profile Using an Input Structure Start X_TRADER
111. X tags to cell array of FIX message strings Syntax fixstr table2fix fixtable Description fixstr table2fix fixtable converts the FIX messages in the table fixtable to raw FIX message strings in the cell array fixstr Examples Convert FIX Message from Table to String Create a FIX message using a table fixtable This table contains two FIX messages The first row in the table represents a sell side transaction for 100 shares of symbol ABC The order type is a previously quoted order The order handling instruction is a private automated execution The order transaction time is the current moment The second row in the table has the same order field variables except that the order identifier is unique across orders The FIX protocol version is 4 4 fixtable table FIX 4 4 FIX 4 4 388 339 2 2 datestr now datestr now D D ABC ABC Cee ETO ROO ieee VariableNames BeginString CLOrdId Side TransactTime OrdType Symbol HandlInst OrderQty Convert the FIX messages in the table fixtable to a cell array of the raw FIX message strings fixstr 4 292 table2fix fixstr table2fix fixtable fixstr 8 FIX 4 4 11 338 54 2 60 22 May 2015 14 14 21 40 D 55 ABC 21 1 38 100 8 FIX 4 4 11 339 54 2 60 22 May 2015 14 14 21 40 D 55 ABC 21 1 38 100 Each string is a raw FIX message string that contains FIX tags and values The space in bet
112. _ID int32 1 Suppose you create a custom event handler function called eventhandler with input argument C Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Modify the route using the Bloomberg EMSX connection c and modroute Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with modifying a route modifyRoute c modroute useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection 4 67 A functions Alphabetical List close c Modify a Route Using an Options Structure To modify a route for a Bloomberg EMSX order Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example show
113. achine running the Bloomberg EMSX test service Create and Manage a Bloomberg EMSX Route processEvent displays events associated with connecting to Bloomberg EMSX Set Up the Route Subscription Set up the route subscription for Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c Return the status for existing routes fields EMSX_BROKER EMSX_WORKING events subs routes c fields events MSG_TYPE 5x1 cell MSG_SUB_TYPE 5x1 cell EVENT_STATUS 5x1 int32 subs com bloomberglp blpapi SubscriptionList 463b9287 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Create and Route the Order Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_INSTRUCTION ANY order EMSX_SIDE BUY Create and route the order using the Bloomberg EMSX connection c and the order request structure order events createOrderAndRoute c order 3 17 3 Sample Code for Workflows 3 18 events EMSX_SEQUENC
114. ails about creating this object see Interactive Brokers API Reference Guide Request intraday data aggregated every 10 minutes using ib ibContract and BID tick type startdate floor now enddate now barsize 10 mins ticktype BID d timeseries ib ibContract startdate enddate barsize ticktype d 735329 17 6 38 6 38 6 38 6 38 1 00 1 00 1 00 735329 17 6 38 6 38 6 38 6 38 1 00 1 00 1 00 735329 18 6 38 6 38 6 38 6 38 1 00 1 00 1 00 d returns the aggregated 10 minute data for BID tick type Each row in matrix d represents a 10 minute interval The columns in matrix d are Numeric representation of a date Open price 4 218 timeseries High price Low price Close price Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Display the high price for the most recent bar in matrix d d 1 3 Close the IB Trader Workstation connection close ib Request Interactive Brokers Intraday Data Within Regular Trading Hours To request intraday data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide
115. ais 768409 00 Columns 1 through 5 1x1 COM TWS_TwsCtrl_1 13 00 768409 00 Submitted 0 Columns 6 through 12 2 00 0 1679681704 00 0 0 0 i Columns 13 through 14 4 195 A Functions Alphabetical List 1x1 struct orderStatus d contains the unique order identifier id ibExampleEventHandler displays order status data in the Command Window The columns are Interactive Brokers ActiveX object Event identifier Unique order identifier Order status Filled e Remaining Average fill price Permanent identifier e Parent identifier Last fill price Client identifier Why held Structure that repeats the contents of the columns Event type For details about this data see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 4 196 createOrder Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws ibContract IB Trader Workstation contract IContract object
116. al List 4 16 Examples Create and Route an Order Using the Default Event Handler To create and route a Bloomberg EMSX order create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create and route the order using the Bloomberg EMSX connection c and order events createOrderAndRoute c order events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders create
117. alse 4 55 A functions Alphabetical List 4 56 Examples Modify an Order Using the Default Event Handler To modify a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure modorder that contains the order sequence number EMSX_SEQUENCE the security EMSX_TICKER and the number of shares EMSX_AMOUNT This code modifies the order number 728905 for 200 shares of IBM Convert the numbers to 32 bit signed integers using int32 modorder EMSX_SEQUENCE int32 728905 modorder EMSX_TICKER IBM modorder EMSX_AMOUNT int32 200 Modify the order using the Bloomberg EMSX connection c and modorder events modifyOrder c modorder events EMSX_SEQUENCE 728905 MESSAGE Order Modified The default event handler processes the events associated with modifying the order modifyOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection modifyOrder close c Modify an Order Using a Timeout To modify a Bloomberg EMSX order create the connection
118. ampleEventHandler Use ibExampleEventHandler or write a custom event handler function acctno DU111111 p portfolio ib acctno ibExampleEventHandler p Columns 1 through 5 portfolio 1x1 COM TWS_TwsCtr1_1 103 1x1 Interface Tws ActiveX_Control_module ICon Columns 6 through 12 515 10 8 22 21 68 0 DU111111 1x1 struct updatePortf p is an empty double because ibExampleEventHandler displays the current Interactive Brokers portfolio data for each security in the Command Window The columns are Interactive Brokers ActiveX object Event identifier IB Trader Workstation IContract object Number of shares Price of the shares Number of shares multiplied by the price of the shares Average price when the shares are purchased Unrealized profit and loss Actual profit and loss Account number Structure that repeats the contents of the columns Event type For details about this data see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 Input Arguments ib IB Trader Workstation connection connection object 4 261 A Functions Alphabetical List 4 262 IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws acctno Account number string Account number specified as a string t
119. an be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal 3 Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 4 61 A Functions Alphabetical List See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx orders routeOrder routes start stop Introduced in R2013a 4 62 modifyRoute modifyRoute Modify Bloomberg EMSX route Syntax events modifyRoute c modroute events
120. an order with a strategy using routeOrderWithStrat e Route multiple orders with a strategy using groupRouteOrderWithStrat Create an order and route using createOrderAndRoute Create an order and route with a strategy using createOrderAndRouteWithStrat Modify an order or route using these functions Modify an order using modifyOrder Modify a route using modifyRoute Modify a route with a strategy using modif yRouteWithStrat Delete an order or route using these functions Delete an order using deleteOrder e Delete a route using deleteRoute Obtain information from Bloomberg EMSX using these functions Obtain broker information using getBrokerInfo Obtain Bloomberg EMSX field information using getAllFieldMetaData Explore information about existing orders and routes using these functions e View order transactions with a sample order blotter using emsxOrderBlotter Process the current contents of the event queue using processEvent Close the Bloomberg EMSX connection using close Workflow for Bloomberg EMSX Related Examples Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 2 3 2 Workflow Models Workflows for Trading Technologies X_TRADER 2 4 You can use X_TRADER to monitor market price information and s
121. and Route an Order Using a Custom Event Handler To create and route a Bloomberg EMSX order with strategies create the Bloomberg EMSX connection c using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 createOrderAndRouteWithStrat order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_FIELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFc
122. and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double modifyRouteWithStrat More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 i Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 238 See Also timer createOrder createOrderAndRouteWithStrat delete deleteOrder getBrokerInfo modifyRoute orders routeOrder routes start stop Introduced in R2013a 4 81 A functions Alphabetical List 4 82 orders Obtain Bloomberg EMSX order subscription Syntax events subs orders c fields events subs orders c fields Name Value events subs orders c fields options Description events subs orders c fields subscribes to Bloomberg EMSX fields fields using the Bloomberg EMSX connection c orders returns existing event data events from the event queue and the Bloomberg EMSX subscription list subs events subs orders c fields Name Value uses additional
123. argument when the flag useDefaultEventHand1ler is set to true and omit this output argument when useDefaultEventHandler is set to false 4 115 A functions Alphabetical List 4 116 Examples Route an Order Using the Default Event Handler To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BMTB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_FIELD_ INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Route the order using the Bloomberg EMSX connection c route and strat events routeOrderWithStrat c route strat events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed The default
124. arket price information and submit orders orderid accounts getdata createOrder timeseries contractdetails orders portfolio history realtime executions marketdepth Request Interactive Brokers Market Data To request current intraday real time historical or market depth data Connect to the IB Trader Workstation using ibtws Create the IB Trader Workstation IContract object Request current data for a security using getdata Request intraday data for a security using timeseries Request real time data for a security using realtime Request historical data for a security using history Request market depth data for a security using marketdepth NO Oh WN Workflow for Interactive Brokers 8 Close the IB Trader Workstation connection using close Create Interactive Brokers Orders To submit orders to the IB Trader Workstation ONO Oa hWND Connect to the IB Trader Workstation using ibtws Create the IB Trader Workstation IContract object Create the IB Trader Workstation IOrder object Request a unique order identifier using orderid Create and submit the order using createOrder Request open order data using orders Request executed order data using executions Close the IB Trader Workstation connection using close Request Interactive Brokers Informational Data To request information from the IB Trader Workstation aOooaht wn
125. assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx modroute Modify route request structure Modify route request specified as a structure with these fields Use getAllFieldMetaData to view all available fields for modroute Convert the numbers to 32 bit signed integers using int32 Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number 4 69 A Functions Alphabetical List 4 70 Field Description EMSX_TICKER Bloomberg EMSxX ticker symbol EMSX_AMOUNT Bloomberg EMSX number of shares EMSX_ROUTE_ID Bloomberg EMSX route identifier Example modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER XYZ modroute EMSX AMOUNT int32 100 modroute EMSX ROUTE_ID int32 1 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the qu
126. ata Types char port Port number scalar Port number specified as a scalar to denote the port number on the computer where the FIX Flyer Engine is running Data Types double Output Arguments c FIX Flyer connection connection object FIX Flyer connection returned as a FIX Flyer connection object with these properties Property Description User FIX Flyer user name 4 273 A Functions Alphabetical List 4 274 Property Description Ipaddress IP address of the computer where the FIX Flyer Engine is running Port Port number of the computer where the FIX Flyer Engine is running FlyerApplicationManager FIX Flyer application manager instance SessionID FIX Flyer session identifier More About Workflow for FIX Flyer on page 2 10 2 FIX Flyer Download Portal 7 FIX Trading Community See Also close sendMessage Introduced in R2015b addListener addListener Add event handling listener to FIX Flyer connection Syntax lh addListener c listener Description lh addListener c listener adds the event handling listener listener to the FIX Flyer Engine connection c Use the sample event handling listener fixExampleListener or write a custom event handling listener function Examples Listen for FIX Flyer Event Data Create the FIX Flyer Engine connection C using these arguments User name username e Password password I
127. ate is a structure with fields corresponding to the status of the order The fields are order status initial margin and maintenance margin For details on these fields and the additional fields in orderState see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Request Open Order Data Using an Event Handler Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 orders Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values Google symbol Stock security type Aggregate exchange USD currency ibContract ib Handle createContract ibContract symbol GOOG ibContract secType STK ibContract exchange SMART ibContract currency USD Create the IB Trader Workstation IOrder object ibOrder Here this object describes a limit order to sell two shares with a limit price of 590 ibOrder ib Handle createOrder ibOrder action SELL ibOrder totalQuantity 2 ibOrder orderType LMT ibOrder 1lmtPrice 590 For details about the IContract and IOrder objects see Interactive Brokers API Reference Guide Create a unique order identifier id id orderid ib Execute the order using IB Trader Workstation connection ib IB Trader Workstation IContract object ibContract IB Trader Workstation IOrder object ibOrd
128. bject created using emsx routenum Route to delete structure Route to delete specified as a structure containing fields EMSX_SEQUENCE and EMSX_ROUTE_ID Example routenum EMSX_SEQUENCE 728918 routenum EMSX_ROUTE_ID 1 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer 4 45 A Functions Alphabetical List 4 46 Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer
129. connection Syntax close c Description close c closes CQG connection C Examples Close the CQG Connection Create the CQG connection object c using cqg c cqg Create the CQG connection using startUp startUp c Close the connection using the CQG connection object c close c Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 Input Arguments c CQG connection connection object 4 159 A Functions Alphabetical List CQG connection specified as a CQG connection object created using cqg More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also cqg shutDown Introduced in R2013b 4 160 createOrder createOrder Create CQG order Syntax o createOrder c s 1 account quantity o createOrder c s 2 account quantity limitprice o createOrder c s 3 account quantity stopprice o createOrder c s 4 account quantity limitprice stopprice Description o createOrder c s 1 account quantity creates a CQGOrder object o for a market order of quantity shares of CQG instrument s using the CQGAccount credentials object account over the CQG connection C o createOrder c s 2 account quantity limitprice creates a limit order using a CQG limit price Limitprice o createOrder c
130. connection specified as a connection object created using emsx order Order request structure Order request specified as a structure using Bloomberg EMSX field properties Use getAllFieldMetaData to view all available field property options for order Convert the number of shares to a 32 bit signed integer using int32 order contains these fields Field Description EMSX_TICKER Bloomberg EMSX ticker symbol EMSX_AMOUNT Bloomberg EMSX amount of shares EMSX_ORDER_TYPE Bloomberg EMSX order type EMSX_BROKER Bloomberg EMSX broker name EMSX_TIF Bloomberg EMSX time in force EMSX_HAND_INSTRUCTION Bloomberg EMSX hand instruction createOrder Field Description EMSX_SIDE Bloomberg EMSX buy or sell specification Example order EMSX_TICKER XYZ order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_ HAND INSTRUCTION ANY order EMSX_SIDE BUY Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or ti
131. d 15x1 cell Instrument 15x1 cell HasVolume 15x1 cell cqgDataEZC returns the current quotes for the security Display data in the Price property of cqgDataEZC cqgDataEZC 1 1 Price ans 2 1475e 09 2 1475e 09 2 1475e 09 660 5000 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 1475e 09 660 5000 2 1475e 09 mman nann D eae a e MONMNMNNNDND PP Close the CQG connection close c Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 4 174 realtime Input Arguments c CQG connection connection object CQG connection specified as a CQG connection object created using cqg s CQG instrument name string CQG instrument name specified as a string identifying the instrument or security Data Types char More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also cqg createOrder history timeseries Introduced in R2013b 4 175 A Functions Alphabetical List 4 176 shutDown Close CQG connection Syntax shutDown c Description shutDown c closes the CQG connection c Examples Close the CQG Connection Create the CQG connection object using cqg c cqg Create the CQG connection using startUp startUp c
132. d Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object createOrderAndRoute Bloomberg EMSX service connection specified as a connection object created using emsx order Order request structure Order request specified as a structure using Bloomberg EMSX field properties Use getAllFieldMetaData to view all available field property options for order Convert the number of shares to a 32 bit signed integer using int32 order contains these fields Field Description EMSX_TICKER Bloomberg EMSxX ticker symbol EMSX_AMOUNT Bloomberg EMSX amount of shares EMSX_ORDER_TYPE Bloomberg EMSX order type EMSX_BROKER Bloomberg EMSX broker name EMSX_TIF Bloomberg EMSX time in force EMSX_HAND_INSTRUCTION Bloomberg EMSX hand instruction EMSX_SIDE Bloomberg EMSX buy or sell specification Example order EMSX_TICKER XYZ order EMSX AMOUNT int32 100 order EMSX ORDER TYPE MKT order EMSX_ BROKER BB order EMSX_TIF DAY order EMSX_HAND INSTRUCTION ANY order EMSX SIDE BUY Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event
133. d as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types Function_handle char Output Arguments d IB Trader Workstation execution filter data structure double 4 239 A Functions Alphabetical List 4 240 IB Trader Workstation execution filter data returned as a structure When using an event handler function d is an empty double More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder getdata history ibtws timeseries Introduced in R2015a marketdepth marketdepth Request Interactive Brokers market depth data Syntax d marketdepth ib ibContract depth d marketdepth ib ibContract depth eventhandler Description d marketdepth ib ibContract depth requests Interactiv
134. d with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output data structure For an example demonstrating these activities see Request CQG Historical Data on page 3 50 See CQG API Reference Guide to learn more about event handlers and the API configuration properties Pass an additional optional request property by creating the structure x and setting the optional property x UpdatesEnabled false For additional optional properties you can set see CQG API Reference Guide Request historical daily data for instrument XYZ XYZ for the last 10 days using the additional optional request property x 4 169 A functions Alphabetical List 4 170 instrument XYZ XYZ startdate floor now 10 enddate floor now period hpDaily history c instrument startdate enddate period x MATLAB writes the variable cqgHistoryData to the Workspace browser Display cqgHistoryData cqgHistoryData cqgHistoryData 1 0e 05 7 3533 0 0063 0 0063 7 3533 0 0064 0 0064 7 3533 0 0065 0 0065 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0066 0 0066 7 3534 0 0064 0 0064 Each row in cqgHistoryData represents data for 1 day The columns in cqgHistoryData show the numerical representation of the timestamp the close price and the open price for the instrument dur
135. data to the Command Window The columns are Interactive Brokers ActiveX object Event identifier Request identifier e Date Open price High price Low price Close price Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Structure that repeats the contents of the columns Event type history Close the IB Trader Workstation connection close ib Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws ibContract IB Trader Workstation contract IContract object IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide startdate Start date date string date scalar Start date specified as a start
136. difyOrder c modorder timeOut timeout modifyOrder _ useDefaultEventHandler false ___ modifyOrder c modorder options Description events modifyOrder c modorder modifies a Bloomberg EMSX order using the Bloomberg EMSX connection c and modify order request structure modorder modifyOrder returns a status message using the default event handler events modifyOrder c modorder timeOut timeout specifies a timeout value timeout for the execution of the default event handler modifyOrder _ useDefaultEventHandler false modifies a Bloomberg EMSX order using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with modifying orders This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true ___ modifyOrder c modorder options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when the flag useDefaultEventHand1ler is set to true and omit this output argument when useDefaultEventHandler is set to f
137. ds Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 modifyRouteWithStrat Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx modroute Modify route request structure Modify route request specified as a structure with these fields Use getAl1FieldMetaData to view all available fields for modroute Convert the numbers to 32 bit signed integers using int32 Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number EMSX_TICKER Bloomberg EMSX ticker symbol EMSX_AMOUNT Bloomberg EMSX number of shares EMSX_ROUTE_ID Bloomberg EMSX route identifier Example modroute EMSX_SEQUENCE int32 731128 modroute EMSX TICKER XYZ modroute EMSX AMOUNT int32 100 modroute EMSX ROUTE_ID int32 1 Data Types struct strat Order strategies structure Order strategie
138. e Open price High price e Low price Close price e Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar When using an event handler function d is a double denoting the request identifier More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder getdata history ibtws realtime Introduced in R2013b 4 225 A functions Alphabetical List 4 226 accounts Retrieve Interactive Brokers account information Syntax d accounts ib acctno d accounts ib acctno eventhandler Description d accounts ib acctno retrieves account information using Interactive Brokers connection ib and account number acctno d accounts ib acctno eventhandler retrieves account information using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Retrieve Account Information Create the IB Trader Workstation connection ib on the local mac
139. e an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true ___ deleteRoute c routenum options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when useDefaultEventHand1er is set to true and omit this output argument when useDefaultEventHandler is set to false deleteRoute Examples Delete Active Shares To delete the active shares that are routed but not filled for a Bloomberg EMSX order 1 Create the connection c using emsx 2 Set up an order and route subscription using orders and routes 3 Create and route an order using createOrderAndRoute For an example showing these activities see Create and Manage a Bloomberg EMSX Route on page 3 16 Define the structure routenum that contains the order sequence number EMSX_SEQUENCE for the routed order and route number EMSX_ROUTE_ID routenum EMSX_SEQUENCE routenum EMSX_ROUTE_ID 335877 1 Delete the active shares that are routed but not filled using the Bloomberg EMSX connection C and routenum events deleteRoute c routenum events STATUS 1
140. e 2 8 4 171 A Functions Alphabetical List 4 172 CQG API Reference Guide See Also cqg createOrder realtime timeseries Introduced in R2013b realtime realtime Subscribe to CQG instrument Syntax realtime c s Description realtime c s subscribes to a CQG instrument s using CQG connection C Examples Subscribe to the CQG Instrument To subscribe to the CQG instrument and get current data create the connection C using Cqg and startup Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with instrument subscription For an example demonstrating these activities see Request CQG Real Time Data on page 3 57 See CQG API Reference Guide to learn more about event handlers and the API configuration properties With the connection established subscribe to the instrument The instrument name must be formatted in the CQG long symbol view For example to subscribe to a security tied to corn type the following instrument F US EZC realtime c instrument MATLAB writes the structure variable cqgDataEZC to the Workspace browser Display cqgDataEZC cqgDataEZC 1 1 4 173 A Functions Alphabetical List ans Price 15x1 cell Volume 15x1 cell ServerTimestamp 15x1 cell Timestamp 15x1 cell Type 15x1 cell Name 15x1 cell IsVali
141. e Brokers market depth data using the IB Trader Workstation connection ib IB Trader Workstation IContract object ibContract and price level depth d marketdepth ib ibContract depth eventhandler requests Interactive Brokers market depth data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Request Market Depth Data To request Interactive Brokers market depth data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request market depth data using ib and ibContract Specify five price levels for the bid and offer sides for depth This code assumes ibContract is an E mini S amp P 500 futures contract with an expiry of December 2014 that trades on the CME Globex exchange depth 5 4 241 A Functions Alphabetical List 4 242 d marketdepth ib ibContract depth bid 5x2 double offer 5x2 double d is a structure that contains the fields for bid and offer price levels Display the bid prices for five levels of market depth d bid ans 1992 5 495 1992 25 1479 1992 195
142. e data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request the last 50 days of historical data using ib ipbContract and these arguments Start date is 50 days ago End date is the current moment The empty string denotes the default tick type TRADES e Bar sizeis 1M startdate floor now 50 history enddate floor now ticktype period 1M d history ib ibContract startdate enddate ticktype period d 1 0e 05 7 3529 0 0079 0 0081 0 0078 0 0080 1 9128 1 3384 0 0080 0 7 3532 0 0080 0 0084 0 0079 0 0079 4 0250 2 6757 0 0082 0 7 3534 0 0079 0 0081 0 0076 0 0080 3 6047 2 4843 0 0079 0 d returns the historical data for 50 days Each row of d contains historical data for 1 month The columns in matrix d are Numeric representation of a date Open price High price Low price Close price e Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Display the low price for the most recent record in matrix d d 1 4 ans 780 Close the IB Trader Workstation connection close ib Request Interactive Brokers Historical Data Within Regular Trading Hours To request historical data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object iobContract as shown in Request 4 209 A functions Alphabet
143. eOut 200 events STATUS 1 MESSAGE Route cancellation request sent to broker The default event handler processes the events associated with deleting the active shares deleteRoute returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs deleteRoute c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Delete Active Shares Using a Custom Event Handler To delete the active shares that are routed but not filled for a Bloomberg EMSX order 1 Create the Bloomberg EMSX connection c using emsx 2 Set up an order and route subscription using orders and routes 3 Create and route an order using createOrderAndRoute For an example showing these activities see Create and Manage a Bloomberg EMSX Route on page 3 16 Define the structure routenum that contains the order sequence number EMSX_SEQUENCE for the routed order and route number EMSX_ROUTE_ID routenum EMSX_SEQUENCE 335877 routenum EMSX_ROUTE_ID 1 Il Suppose you create a custom event handler function called eventhandler with input argument C Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Cu
144. eateExecutionFilter executions filter side BUY filter secType STK filter exchange SMART filter symbol GOOG For details about the IExecutionFilter object see Interactive Brokers API Reference Guide Request IB Trader Workstation execution filter data using ib and filter Il d executions ib filter d enddetails 1x1 struct d is a structure containing the execution filter data in the structure enddetails Display the execution filter data d enddetails ans Type execDetailsEnd Source 1x1 COM TWS_TwsCtr1_1 EventID 38 reqId 1 The structure enddetails contains these fields e Data request type Interactive Brokers ActiveX object Event identifier Execution filter data request identifier Close the IB Trader Workstation connection close ib Request Execution Filter Data Using an Event Handler Create the IB Trader Workstation connection ib on the local machine using port number 7496 4 237 A functions Alphabetical List 4 238 ib ibtws 7496 Create the IB Trader Workstation execution filter IExecutionFilter object filter Here this object specifies these property values Buy side Stock security type Aggregate exchange Google symbol filter ib Handle createExecutionFilter filter side BUY filter secType STK filter exchange SMART filter symbol GOOG For details about the IExecutionFilter object s
145. ect failure events so you can assign callbacks to handle these conditions createOrderSet X X OrderSet 1 EnableOrderRejectData X OrderSet 1 EnableOrderUpdateData 1 1 X OrderSet 1 OrderStatusNotifyMode ORD_NOTIFY_NORMAL Set Position Limit Checks Set whether the order set checks self imposed position limits when submitting an order X OrderSet 1 Set NetLimits false Submit X_TRADER Orders Set a Callback Function Set a callback to handle the OnOrderFilled events Each time an order is filled or partially filled this callback is invoked registerevent X OrderSet 1 OnOrderFilled varargin ttorderevent varargin X Enable Order Submission You must first enable order submission before you can submit orders to X_TRADER X OrderSet 1 Open 1 Build an Order Profile Build an order profile using an existing instrument The order profile contains the settings that define a submitted order The valid Set parameters are shown orderProfile createOrderProfile X orderProfile Instrument X Instrument 1 orderProfile Customer lt Default gt Sample Create a Market Order Create a market order to buy 100 shares orderProfile Set BuySell Buy orderProfile Set Qty 100 orderProfile Set OrderType M Sample Create a Limit Order Create a limit order by setting the OrderType and limit order price orderProfile Set OrderType L orderProfile Set Limit 127000
146. ect to the Bloomberg EMSX test service Cc Cc emsx blp emapisvc_beta emsx with properties Session 1x1 com bloomberglp blpapi Session Service 1x1 com bloomberglp blpapi impl aQ 1 Getting Started 1 14 Ipaddress localhost Port 8194 MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSxX test service Port number of the machine running the Bloomberg EMSX test service Create the market order request Create an order request structure order for a buy market order of 400 shares of IBM Specify the broker as EFIX use any hand instruction and set the time in force to DAY order order order order order order order EMSX_ORDER_TYPE MKT EMSX_SIDE BUY EMSX_TICKER IBM EMSX_AMOUNT int32 400 EMSX_BROKER EFIX EMSX_HAND_INSTRUCTION ANY EMSX_TIF DAY Create and route the market order Create and route the market order using the Bloomberg EMSX connection c and order request structure order events events EM EM createOrderAndRoute c order SX_SEQUENCE 335877 SX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields
147. ee Interactive Brokers API Reference Guide Request IB Trader Workstation execution filter data using ib and filter Use the sample event handler ibExampleEventHandler to display the IB Trader Workstation execution filter data in the Command Window Use ibExampleEventHandler or write a custom event handler function d executions ib filter ibExampleEventHandler d 1x1 COM TWS_TwsCtrl_1 38 1 1x1 struct execDetailsEnd d is an empty double ibExampleEventHandler displays the data in the Command Window The columns are Interactive Brokers ActiveX object Event identifier Execution filter data request identifier Structure that repeats the contents of the columns e Data request type executions For details see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws filter IB Trader Workstation execution filter IExecutionFilter object IB Trader Workstation execution filter specified as a IExecutionFilter object For details about this object see Interactive Brokers API Reference Guide Example Data Types struct eventhandler Event handler function handle string Event handler specifie
148. egisterevent c Handle histEventNames i varargin cqgexpressioneventhandler varargin end Pass an Additional Optional Request Property Pass an additional optional request property by creating the structure x and setting the optional property x UpdatesEnabled false For additional optional properties you can set see CQG API Reference Guide Request CQG Historical Data Request daily data for instrument XYZ XYZ for the last 10 days using the additional optional request property X instrument XYZ XYZ startdate floor now 10 enddate floor now period hpDaily history c instrument startdate enddate period x MATLAB writes the variable cqgHistoryData to the Workspace browser Display cqgHistoryData cqgHistoryData cqgHistoryData 1 0e 05 7 3533 0 0063 0 0063 7 3533 0 0064 0 0064 733533 0 0065 0 0065 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0066 0 0066 7 3534 0 0064 0 0064 3 51 3 Sample Code for Workflows 3 52 Each row in cqgHistoryData represents data for 1 day The columns in cqgHistoryData show the numerical representation of the timestamp the close price and the open price for the instrument during the day Close the CQG Connection close c See Also close cqg createOrder history realtime shutDown startuUp timeseries Related Examples t Create an Order Using CQG on page 1 11
149. empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute delete deleteRoute emsx modifyOrder orders routeOrder routes start stop Introduced in R2013a 4 39 A Functions Alphabetical List 4 40 deleteRoute Delete Bloomberg EMSX active shares Syntax events deleteRoute c routenum events deleteRoute c routenum timeOut timeout deleteRoute useDefaultEventHandler false deleteRoute c routenum options Description events deleteRoute c routenum deletes the active shares that are routed but not filled using the Bloomberg EMSX connection c and route number routenum deleteRoute returns a status message using the default event handler events deleteRoute c routenum timeOut timeout specifies a timeout value timeout for the execution of the default event handler deleteRoute _ useDefaultEventHandler false deletes the active shares that are routed but not filled using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with deleting the active shares This syntax does not hav
150. ents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder history ibtws timeseries Introduced in R2015a 4 270 fixflyer fixflyer FIX Flyer connection Syntax c fixflyer username password ipaddress port Description c fixflyer username password ipaddress port creates a connection to the FIX Flyer Engine with user name username password password IP address ipaddress and port number port Examples Connect to the FIX Flyer Engine To create a connection to FIX Flyer for the first time add these JAR files to the static Java class path by editing the javaclasspath txt file These files are located in the folder where FIX Flyer is installed This list assumes an installation of FIX Flyer version 5 0 1 FIXFlyer fix flyer 5 0 1 devkit lib fix flyer jar FIXFlyer fix flyer 5 0 1 devkit lib flyer apps jar FIXFlyer fix flyer 5 0 1 devkit lib flyer tools jar FIXFlyer fix flyer 5 0 1 devkit lib mod flyer jar FIXFlyer fix flyer 5 0 1 devkit lib quickfix jar FIXFlyer fix flyer 5 0 1 lib core trove 2 0 4 jar 0 FIXFlyer fix flyer 5 0 1 lib core mg4j 0 8 1 jar If you are running
151. equence number EMSX_SEQUENCE for the routed order and route number EMSX_ROUTE_ID routenum EMSX_SEQUENCE routenum EMSX_ROUTE_ID 335877 i Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Delete the active shares that are routed but not filled using the Bloomberg EMSX connection C routenum and options structure options options useDefaultEventHandler true options timeOut 200 events deleteRoute c routenum options events STATUS 1 MESSAGE Route cancellation request sent to broker deleteRoute The default event handler processes the events associated with deleting the active shares deleteRoute returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects osubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection o
152. er Unique order identifier id d createOrder ib ibContract ibOrder id Retrieve order information from all clients by setting client to false and using the sample event handler function ibExampleEventHandler Use ibExampleEventHandler or write a custom event handler function 4 253 4 Functions Alphabetical List orders ib false ibExampleEventHandler Columns 1 through 4 1x1 COM TWS_TwsCtrl_1 101 56947638 1x1 Interface Tws_ActiveX_Contri Columns 5 through 6 1x1 Interface Tws_ActiveX_Control_module IOrder 1x1 Interface Tws_ ActiveX_Col Columns 7 through 8 1x1 struct openOrdereEx o contains an empty double because the event handler ibExampleEventHandler processes the output data ibExampleEventHandler displays the output data in the Command Window Here IB Trader Workstation returns Interactive Brokers ActiveX object Event identifier Unique order identifier IB Trader Workstation IContract object IB Trader Workstation IOrder object IB Trader Workstation IOrderState object Structure that repeats the contents of the columns Request type For details about this data see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib 4 254 Create and Manage an Interactive Brokers Order on page 3 26 orders Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified
153. er options Description events createOrderAndRoute c order creates and routes a Bloomberg EMSX order using Bloomberg EMSX connection c and order request order createOrderAndRoute returns the order sequence number route number and status message using the default event handler events createOrderAndRoute c order timeOut timeout specifies a timeout value timeout for the execution of the default event handler createOrderAndRoute _ useDefaultEventHandler false creates and routes a Bloomberg EMSX order using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with creating and routing orders This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true ____ _ createOrderAndRoute c order options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when useDefaultEventHand1ler is set to true and omit this output argument when useDefaultEventHandler is set to false 4 15 A functions Alphabetic
154. erg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Connect to Bloomberg EMSX Connect to the Bloomberg EMSxX test service Display the current event queue contents using processEvent c emsx blp emapisvc_beta processEvent c G emsx with properties Session 1x1 com bloomberglp blpapi Session Service 1x1 com bloomberglp blpapi imp1l aQ Ipaddress localhost Port 8194 SessionConnectionUp server localhost 127 0 0 1 8194 SessionStarted ServiceOpened serviceName blp emapisvc_beta MATLAB returns c as the connection to the Bloomberg EMSX test service with the following Bloomberg EMSX session object Bloomberg EMSX service object IP address of the machine running the Bloomberg EMSX test service 3 21 3 Sample Code for Workflows 3 22 Port number of the machine running the Bloomberg EMSX test service processEvent displays events associated with connecting to Bloomberg EMSX Set Up the Order and Route Subscription Subscribe to order events using the Bloomberg EMSX connection c associated with these Bloomberg EMSxX fields fields EMSX_TICKER EMSX_AMOUNT EMSX_FILL events osubs orders c fields events MSG_TYPE E MSG_SUB_TYPE 0O EVENT_STATUS 4 osubs com bloomberglp blpapi SubscriptionList 4bc3dc78 events contains fields for the events associated with the existin
155. erid 1 1x1 COM TWS_TwsCtrl_1 1 1 1 585 50 1 1x1 struct 1x1 COM TWS_TwsCtr1_1 2 1 0 1 1x1 struct tickSize tickerid returns a number for tracking the real time data request After the tickerid ibExampleEventHandler streams real time data to the Command Window Each line is a type of tick Here there is a price tick and size tick For a price tick the IB Trader Workstation returns Interactive Brokers ActiveX object Event identifier Request identifier Tick type e Price Automatic execution flag Structure that repeats the contents of the columns Event type For details about this data see Interactive Brokers API Reference Guide Cancel the real time market data request using tickerid ib Handle cancelMktData tickerid Close the IB Trader Workstation connection 4 268 realtime close ib Request Interactive Brokers Real Time Data on page 3 35 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws ibContract IB Trader Workstation contract IContract object cell array IB Trader Workstation contract specified as an IB Trader Workstation IContract object or a cell array for multiple IB Trader Workstation IContract objects This object is the instrument or security used in the order transaction Create this object by calli
156. es a security with these property values Google symbol Stock security type Aggregate exchange 4 231 A functions Alphabetical List 4 232 USD currency ibContract ib Handle createContract ibContract symbol GOOG ibContract secType STK ibContract exchange SMART ibContract currency USD ll For details about the IContract object see Interactive Brokers API Reference Guide Request contract details data using ib and ibContract d reqid contractdetails ib ibContract d marketName NMS tradingClass NMS minTick 0 01 reqid 1269 d is a structure containing the contract details data including the market name trading class name and minimum tick For details about this data see Interactive Brokers API Reference Guide reqid is a number that Interactive Brokers uses to track this contract details data request Close the IB Trader Workstation connection close ib Request Interactive Brokers Contract Details Using an Event Handler Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values contractdetails Google symbol Stock security type Aggregate exchange USD currency ibContract ib Handle createContract ibContract symbol GOOG ibContract secType S
157. ese fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 4 77 A functions Alphabetical List 4 78 Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Modify the route using the Bloomberg EMSX connection c modroute strat and options structure options options useDefaultEventHandler true options timeOut 200 events modifyRouteWithStrat c modroute strat options events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRouteWithStrat returns events as a structure that contains these fiel
158. essages in a structure array fixstruct to raw FIX message strings in the cell array fixstr Examples Convert FIX Message from Structure Array to String Create a FIX message using a structure array fixstruct This structure array contains two FIX messages The first structure in the structure array represents a sell side transaction for 100 shares of symbol ABC The order type is a previously quoted order The order handling instruction is a private automated execution The order transaction time is the current moment The FIX protocol version is 4 4 The second structure in the structure array has the same order field values except that the order identifier is unique across orders fixstruct BeginString 1 1 FIX 4 4 fixstruct CLOrdId 1 1 338 fixstruct Side 1 1 2 fixstruct TransactTime 1 1 datestr now fixstruct OrdType 1 1 D fixstruct Symbol 1 1 ABC fixstruct HandlInst 1 1 1 fixstruct OrderQty 1 1 100 fixstruct BeginString 2 1 FIX 4 4 fixstruct CLOrdId 2 1 339 4 289 A functions Alphabetical List 4 290 fixstruct Side 2 1 2 fixstruct TransactTime 2 1 datestr now fixstruct OrdType 2 1 D fixstruct Symbol 2 1 ABC fixstruct HandlInst 2 1 1 fixstruct OrderQty 2 1 100 Convert the FIX messages in the structure array fixstruct to a cell array of the raw FIX message strings fixstr fixstr struct2fix fixstruct fixstr
159. eue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure modifyRoute If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal i Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer createOrder createOrderAndRoute delete deleteOrder modifyRouteWithStrat orders routes start stop Introduced in R2013a 4 71 A Functions Alphabetical List 4 72 modifyRouteWithStrat Modify route with strategies for Bloomberg EMSX
160. event handler processes the events associated with routing the order routeOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message routeOrderWithStrat Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Route an Order Using a Timeout To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BMTB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP
161. events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output data structure For an example demonstrating these activities see Request CQG Historical Data on page 3 50 See CQG API Reference Guide to learn more about event handlers and the API configuration properties Request historical daily data for instrument XYZ XYZ for the last 10 days instrument XYZ XYZ startdate floor now 10 enddate floor now period hpDaily history c instrument startdate enddate period history MATLAB writes variable cqgHistoryData to the Workspace browser Display cqgHistoryData cqgHistoryData cqgHistoryData 1 0e 05 7 3533 0 0063 0 0063 7 3533 0 0064 0 0064 7 3533 0 0065 0 0065 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0065 0 0065 7 3534 0 0066 0 0066 7 3534 0 0066 0 0066 7 3534 0 0064 0 0064 Each row in cqgHistoryData represents data for 1 day The columns in cqgHistoryData show the numerical representation of the timestamp the close price and the open price for the instrument during the day Close the CQG connection close c Request CQG Historical Data with Additional Request Properties To request daily historical data for an instrument with an additional property create the connection c using cqg and startUp Register an event handler for tracking events associate
162. events associated with routing an order groupRouteOrderWithStrat c route strat useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs To stop data updates stop the timer using stop c Session unsubscribe osubs c Session unsubscribe rsubs 4 109 A functions Alphabetical List 4 110 stop t If you are done processing data updates delete the timer using delete delete t Close the Bloomberg EMSX connection close c Route Orders Using an Options Structure To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies these route request fields Order numbers 335877 and 335878 Stock symbol IBM 100 percent of shares shown on the order to be routed Broker BMTB Any hand instruction Time in force set to DAY e Market order type route EMSX_SEQUENCE int32 335877 int32 335878 route EMSX_TICKER IBM route EMSX_AMOUNT_PERCENT int32 100 route EMSX_BROKER BMTB
163. fier 4 17 A functions Alphabetical List 4 18 Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Route an Order Using a Custom Event Handler To create and route a Bloomberg EMSX order create the Bloomberg EMSX connection c using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Blo
164. g Bloomberg EMSX orders oSubs contains the Bloomberg EMSX subscription list object Subscribe to route events for the Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c Return the status for existing routes fields EMSX_BROKER EMSX_WORKING events rsubs routes c fields events MSG_TYPE 5x1 cell MSG_SUB_TYPE 5x1 cell EVENT_STATUS 5x1 int32 rsubs com bloomberglp blpapi SubscriptionList 463b9287 Manage a Bloomberg EMSX Order and Route events contains fields for the events currently in the event queue rsubs contains the Bloomberg EMSX subscription list object Create and Route the Order Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_INSTRUCTION ANY order EMSX_SIDE BUY Create and route the order using the Bloomberg EMSX connection c and the order request structure order events createOrderAndRoute c order events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associa
165. g these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure ordernum that contains the order sequence number EMSX_SEQUENCE for the order to delete ordernum EMSX_SEQUENCE 335877 Delete the order using the Bloomberg EMSX connection c and ordernum events deleteOrder c ordernum events STATUS 0 MESSAGE Order deleted The default event handler processes the events associated with deleting the order deleteOrder returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Delete an Order Using the Order Number Integer To delete a Bloomberg EMSX order create the connection c using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 deleteOrder Delete the order using the Bloomberg EMSX connection c and the order sequence number 335877 for the order to delete events deleteOrder c 335877 events STATUS 0 MESSAGE Order deleted The default event handler processes the events associated with deleting the order deleteOrder returns events as a structure that contains these
166. g timer Use a function handle to specify the custom event handler function name to run timer Start the timer to execute the custom event handler function immediately using start Stop data updates using stop Unsubscribe from Bloomberg EMSxX fields by using the API syntax Delete the timer using delete Writing and Running Custom Event Handler Functions with Bloomberg EMSX 9 Close the connection using close See Also timer close createOrderAndRoute delete emsx orders routes start stop Related Examples e Create Functions in Files More About Create Function Handle 1 25 1 Getting Started Writing and Running Custom Event Handler Functions with Interactive Brokers 1 26 In this section Write a Custom Event Handler Function on page 1 26 Run a Custom Event Handler Function on page 1 26 Workflow for Custom Event Handler Function on page 1 27 Write a Custom Event Handler Function You can process events related to any Interactive Brokers data updates by writing a custom event handler function to use with Trading Toolbox For example you can request data about all open orders or retrieve account information Follow these tasks to write a custom event handler Choose the events that you want to process monitor or evaluate Decide how the custom event handler function processes these events Determine the input and output arguments for the cu
167. gies X_TRADER Key Features e Access to current intraday event based and real time tradable instrument data Data filtering by instrument and exchange Definable order types and execution instructions Bloomberg EMSX order execution Trading Technologies X_TRADER instrument pricing and order execution CQG Integrated Client instrument pricing order execution and historical price retrieval Interactive Brokers TWS instrument pricing order execution and historical price retrieval Installation Installation In this section Bloomberg on page 1 3 CQG on page 1 3 FIX Flyer on page 1 3 Interactive Brokers on page 1 3 Trading Technologies on page 1 4 Bloomberg Find the latest installation files at http www bloomberg com to install Bloomberg EMSX from Bloomberg L P You need a Bloomberg license to install and run Bloomberg EMSX CQG Find the latest installation files at http www cqg com to install CQG You need a CQG license to install and run CQG FIX Flyer Find the latest installation files at the FIX Flyer Download Portal to install FIX Flyer You need a FIX Flyer license to install and run FIX Flyer Interactive Brokers 1 Download and install the IB Trader Workstation Desktop Trading Client Find the latest installation files at https www interactivebrokers com en index php f 552 2 Download and install the Interactive Brokers API softwa
168. h strategies Syntax events createOrderAndRouteWithStrat c order strat events createOrderAndRouteWithStrat c order strat timeOut timeout createOrderAndRouteWithStrat useDefaultEventHandler false createOrderAndRouteWithStrat c order strat options Description events createOrderAndRouteWithStrat c order strat creates and routes a Bloomberg EMSX order with strategies using Bloomberg EMSX connection c order request order and order strategy strat createOrderAndRouteWithStrat returns the order sequence number route number and status message using the default event handler events createOrderAndRouteWithStrat c order strat timeOut timeout specifies a timeout value timeout for the execution of the default event handler createOrderAndRouteWithStrat _ useDefaultEventHandler false creates and routes a Bloomberg EMSX order with strategies using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with creating and routing orders This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true createOrderAndRouteWithStrat c order strat options uses the option
169. hStrat c route strat events groupRouteOrderWithStrat c route strat timeOut timeout groupRouteOrderWithStrat _ s useDefaultEventHandler false groupRouteOrderWithStrat c route strat options Description events groupRouteOrderWithStrat c route strat routes multiple Bloomberg EMSX orders with strategies using the Bloomberg EMSX connection C route request route and strategy strat routeOrderWithStrat returns the order sequence number route number and status message using the default event handler events groupRouteOrderWithStrat c route strat timeOut timeout specifies a timeout value timeout for the execution of the default event handler groupRouteOrderWithStrat _ useDefaultEventHandler false routes multiple Bloomberg EMSX orders with strategies using any of the input arguments in the previous syntaxes and a custom event handler To process the events associated with routing orders write a custom event handler This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true _____ _ groupRouteOrderwWithStrat c route strat options uses the options structure to customize the output which is useful to preconfigure and save your option
170. handler or timeout value structure routes Options for custom event handler or timeout value specified as a structure Use the options structure instead of name value pair arguments to reuse the optional name value pair arguments to specify a custom event handler or timeout value for the event handler The options structure field and values correspond to names and values of the name value pair arguments respectively Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example useDefaultEventHandler false useDefaultEventHandler Flag for event handler preference true default false Flag for event handler preference indicating whether to use the default or custom event handler to process order events specified as the comma separated pair consisting of useDefaultEventHandler and the logical values true or false To specify the default event handler set this flag to true Otherwise set this flag to false to specify a custom event handler Data Types logical timeOut Timeout value for e
171. hat contains the order sequence number EMSX_SEQUENCE and the route number EMSX_ROUTE_ID associated with the modified route routenum EMSX_SEQUENCE routenum EMSX_ROUTE_ID 0 0 Delete the route using the Bloomberg EMSX connection c and delete route number structure routenum events deleteRoute c routenum events STATUS 1 MESSAGE Route cancellation request sent to broker The default event handler processes the events associated with deleting a route deleteRoute returns events as a structure that contains these fields Bloomberg EMSX status Bloomberg EMSX message Stop the Route Subscription Unsubscribe from route events using the Bloomberg EMSX subscription list object subs c Session unsubscribe subs Close the Bloomberg EMSX Connection close c See Also close createOrderAndRoute deleteRoute emsx modifyRoute routeOrder routes 3 19 3 Sample Code for Workflows Related Examples Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 6 Manage a Bloomberg EMSX Order and Route on page 3 21 More About 7 Workflow for Bloomberg EMSX on page 2 2 3 20 Manage a Bloomberg EMSX Order and Route Manage a Bloomberg EMSX Order and Route This example shows how to connect to Bloomberg EMSxX set up an order and route subscription create and route an order and interact with the route For details about Bloomb
172. hat identifies the Interactive Brokers account number Example Data Types char eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types function handle char Output Arguments p Interactive Brokers portfolio data structure double Interactive Brokers portfolio data returned as a structure The structure contains these fields When using an event handler function p is an empty double Field Description Type Interactive Brokers event type name Source Interactive Brokers ActiveX object EventID Number that identifies the event type contract Structure that contains details for each contract in the portfolio portfolio Field Description position Number of shares for each contract in the portfolio marketPrice Price of the shares for each contract in the portfolio marketValue Number of shares multiplied by the price of the shares for each contract in the portfolio averageCost Average price when the shares are purchased for each contract in the portfolio unrealizedPNL Unrealized profit and loss for each contract in the portf
173. he Bloomberg EMSX connection c and route events routeOrder c route events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed The default event handler processes the events associated with routing the order routeOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs 4 97 A functions Alphabetical List 4 98 Close the Bloomberg EMSX connection close c Route an Order Using a Timeout To route a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BB route EMSX_HAND_INSTRUCTION ANY Route the
174. he same IB Trader Workstation connection can cause this kind of warning message Warning Cannot unregister openOrderEx Invalid event name handler combination To fix this warning close the IB Trader Workstation connection and create a new connection using ibtws Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder executions getdata history ibtws orderid timeseries Introduced in R2015a 4 256 portfolio portfolio Retrieve current Interactive Brokers portfolio data Syntax p portfolio ib p portfolio ib acctno p portfolio ib acctno eventhandler Description p portfolio ib retrieves current Interactive Brokers portfolio data for the active account number using the IB Trader Workstation connection ib p portfolio ib acctno retrieves current Interactive Brokers portfolio data using the account number acctno p portfolio ib acctno eventhandler retrieves current Interactive Brokers portfolio data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Retrieve Current Portfolio Data Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Retrieve current Interact
175. hine using port number 7496 ib ibtws 7496 Retrieve account information for account number acctno using ib acctno AB123456 d Il accounts ib acctno d AccountCode AB123456 AccountReady true accounts AccountType LLC d is a structure with the fields containing the account information Here the fields are Account code IB Trader Workstation internal use only Account type For details about this data and the other fields see Interactive Brokers API Reference Guide Close the IB Trader Workstation connection close ib Retrieve Account Information Using an Event Handler Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Retrieve account information for account number acctno using ib Use the sample event handler ibExampleEventHandler to display the IB Trader Workstation account information in the Command Window Use ibExampleEventHand1ler or write a custom event handler function acctno AB123456 Il d accounts ib acctno ibExampleEventHandler d Columns 1 through 7 1x1 COM TWS_TwsCtr1_1 7 AccountCode AB123456 d AB123456 Column 8 updateAccountValue 4 227 A Functions Alphabetical List 4 228 dis an empty double The sample event handler ibExampleEventHandler displays the account information in the Command Window The columns are Interactive Brokers ActiveX object
176. iable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder history ibtws realtime timeseries Introduced in R2013b 4 204 history history Request Interactive Brokers historical data Syntax d history ib ibContract startdate enddate d history ib ibContract startdate enddate ticktype period d history ib ibContract startdate enddate ticktype period tradehours d history ib ibContract startdate enddate ticktype period tradehours eventhandler Description d history ib ibContract startdate enddate requests Interactive Brokers historical data using the IB Trader Workstation connection ib and IB Trader Workstation IContract object ibContract to signify the instrument history requests data from startdate through enddate The default tick type is TRADES and default periodis 1 day d history ib ibContract startdate enddate ticktype period requests Interactive Brokers historical data for a specific type of market data tick ticktype and bar size period d history ib ibContract startdate enddate ticktype period tradehours requests Interactive Brokers historical data using the flag tradehours t
177. ical List 4 210 Interactive Brokers Historical Data on page 3 32 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request the last 50 days of historical data using ib ioContract and these arguments Start date is 50 days ago End date is the current moment The empty string denotes the default tick type TRADES e Bar sizeis 1M e Within regular trading hours startdate floor now 50 enddate floor now ticktype period 1M tradehours true d history ib ibContract startdate enddate ticktype period tradehours d Columns 1 through 5 735805 00 591 25 599 55 585 21 588 85 735812 00 587 50 592 45 562 80 565 90 735819 00 568 85 575 32 560 00 568 45 Columns 6 through 9 1 00 1 00 1 00 0 1 00 1 00 1 00 0 1 00 1 00 1 00 0 d returns the historical data for 50 days Each row of d contains historical data for 1 month The columns in matrix d are Numeric representation of a date Open price High price history Low price Close price Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Display the low price for the most recent record in matrix d d 1 4 ans 585 21 Close the IB Trader Workstation connection close ib Request Interactive Br
178. ing date string or scalar Data Types double char enddate End date date string date scalar End date specified as an ending date string or scalar Data Types double char 4 213 A Functions Alphabetical List 4 214 ticktype Types of market data ticks TRADES default MIDPOINT BID ASK BID_ASK HISTORICAL VOLATILITY OPTION IMPLIED VOLATILITY Types of market data ticks specified as one of the preceding enumerated strings The Interactive Brokers API predetermines these strings to denote tick values to collect period Bar size 1 day default 1W 1M Bar size specified as one of the preceding enumerated strings predetermined by the Interactive Brokers API that denote the periodicity for collecting data tradehours Trading hours false default true Trading hours specified as the logical true or false When this flag is set to true this function returns data only within regular trading hours Otherwise this function returns all data Data Types logical eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data
179. ing the day Close the CQG connection close c Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 7 Request CQG Real Time Data on page 3 57 Input Arguments c CQG connection connection object history CQG connection specified as a CQG connection object created using cqg s CQG instrument name string CQG instrument name specified as a string identifying the instrument or security Data Types char startdate Start date date string date scalar Start date specified as a starting date string or scalar Data Types double char enddate End date date string date scalar End date specified as an ending date string or scalar Data Types double char period Bar size hpDaily default hpWeekly hpMonthly hpQuarterly hpSemiannual hpYearly Bar size specified as one of the above enumerated strings predetermined by the CQG API that denotes the length of time to collect data x CQG request properties request properties structure CQG request properties specified as a CQG request properties structure Create this structure by writing MATLAB code to set additional optional request properties For additional optional properties you can set see CQG API Reference Guide Example x UpdatesEnabled false Data Types struct More About Workflow for CQG on pag
180. ing the information for the created and routed order where order number EMSX_SEQUENCE is 381499 using the event handler function processEventToBlotter The order blotter updates as orders are created and managed Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 4 91 A Functions Alphabetical List 4 92 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx Output Arguments t MATLAB timer object MATLAB timer returned as a MATLAB object For details see timer subs Bloomberg EMSX subscription list subscription list object Bloomberg EMSX subscription list returned as a Bloomberg EMSX subscription list object More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 See Also timer close createOrder createOrder createOrderAndRoute createOrderAndRouteWithStrat deleteOrder deleteRoute emsx modifyOrder orders routeOrder routes Introduced in R2013a processEvent processEvent Sample Bloomberg EMSX event handler Syntax processEvent c
181. ing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Modify the route using the Bloomberg EMSX connection c modroute and options structure options options useDefaultEventHandler true options timeOut 200 events modifyRoute c modroute options events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified 4 68 modifyRoute The default event handler processes the events associated with modifying a route modifyRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code
182. ion C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes groupRouteOrderWithStrat Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies these route request fields Order numbers 335877 and 335878 Stock symbol IBM 100 percent of shares shown on the order to be routed Broker BMTB Any hand instruction Time in force set to DAY e Market order type route EMSX_SEQUENCE int32 335877 int32 335878 route EMSX_TICKER IBM route EMSX_AMOUNT_PERCENT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY route EMSX_TIF DAY route EMSX_ORDER_TYPE MKT Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_FIELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Route the orders using the Bloomberg EMSX connection c route and strat Set the timeout value to 200 milliseconds events groupRouteOrderWithStrat c route strat timeOut 200 events EMSX_SUCCESS ROUTES 1x1 struct EMSX_FAILED_ROUTES 1x1 struct MESSAGE 1 of 1 Order s Routed
183. istory ib ibContract startdate enddate ticktype period d 1 0e 05 7 3529 0 0080 0 0081 0 0078 0 0081 0 0000 0 0000 0 0000 0 7 3530 0 0080 0 0084 0 0080 0 0083 0 0000 0 0000 0 0000 0 7 3531 0 0082 0 0084 0 0081 0 0081 0 0000 0 0000 0 0000 0 7 3532 0 0080 0 0083 0 0079 0 0081 0 0000 0 0000 0 0000 0 7 3532 0 0081 0 0082 0 0079 0 0079 0 0000 0 0000 0 0000 0 7 3533 0 0079 0 0081 0 0078 0 0078 0 0000 0 0000 0 0000 0 7 3534 0 0078 0 0079 0 0077 0 0079 0 0000 0 0000 0 0000 0 7 3534 0 0079 0 0080 0 0076 0 0080 0 0000 0 0000 0 0000 0 d returns the historical data for 50 days Each row of d contains historical data for 1 week 4 207 A Functions Alphabetical List 4 208 The columns in matrix d are Numeric representation of a date Open price High price Low price Close price e Volume e Bar count e Weighted average price Flag indicating if there are gaps in the bar Display the high price for the most recent record in matrix d d 1 3 ans 810 Close the IB Trader Workstation connection close ib Request Interactive Brokers Historical Data with TRADES Default Tick Type and 1 Month Period To request historical data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Historical Data on page 3 32 An IContract object is an Interactive Brokers object for containing th
184. ith input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Create the order using the Bloomberg EMSX connection c and order Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with creating an order createOrder c order useDefaultEventHandler false Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates Subs Stop the timer to stop data updates using stop c Session unsubscribe subs stop t createOrder Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Create an Order Using an Options Structure To create a Bloomberg EMSX order create the connection C using emsx and set up the order subscription using orders For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any ha
185. ith names and values corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Examples Create an X_TRADER Instrument Notifier Using an Input Structure Start X_TRADER X xtrdr Define an input structure S with fields corresponding to valid X_TRADER API options S S Instrument S UpdateFilter S EnablePriceUpdates 1 createNotifier S EnableDepthUpdates 0 S DebugLogLevel 3 EnableOrderSetUpdates 1 S PriceList DeliverAllPriceUpdates 0 S S Instrument UpdateFilter EnablePriceUpdates EnableDepthUpdates DebugLogLevel EnableOrderSetUpdates PriceList DeliverAllPriceUpdates om WUO Create an xtrdr instrument notifier createNotifier X S Close the connection close X Create an X_TRADER Instrument Notifier Using Name Value Pairs Start X_TRADER X xtrdr Create an xtrdr instrument using name value pairs corresponding to valid X_TRADER API options createNotifier X Instrument UpdateFilter EnablePriceUpdates 1 EnableDepthUpdates 0O DebugLogLevel 3 EnableOrderSetUpdates 1 PriceList DeliverAllPriceUpdates 0 Close the connection close X Listen for X_TRADER Price Updates on page 3 2 4 143 A Functions Alphabetical List Listen for X_TRADER Price Market Depth Updates
186. itive number denotes a buy and a negative number denotes a sell Data Types double limitprice CQG limit price double createOrder CQG limit price specified as a double denoting the limit order price Data Types double stopprice CQG stop price double CQG stop price specified as a double denoting the stop order price Data Types double Output Arguments o CQG order CaGOrder object CQG order returned as a CQGOrder object This object encapsulates all data necessary to execute a CQG order For more information about creating a CQGOrder object see CQG API Reference Guide More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also cqg history realtime timeseries Introduced in R2013b 4 167 A functions Alphabetical List 4 168 history Request CQG historical data Syntax history c s startdate enddate period history c s startdate enddate period x Description history c s startdate enddate period requests CQG historical data asynchronously with bar size period between startdate and enddate for CQG instrument name s with CQG connection C history c s startdate enddate period x requests CQG historical data asynchronously with additional request properties x Examples Request CQG Historical Data To request daily historical data for an instrument create the connection C using cqg and startUp Register an event handler for tracking
187. ive Brokers portfolio data using ib p portfolio ib p 4 257 A Functions Alphabetical List 4 258 Type 5x1 cell Source 5x1 cell EventID 5x1 cell contract 5x1 cell position 5x1 cell marketPrice 5x1 cell marketValue 5x1 cell averageCost 5x1 cell unrealizedPNL 5x1 cell realizedPNL 5x1 cell accountName 5x1 cell p is a structure that contains these fields Event type Interactive Brokers ActiveX object Event identifier Contract details Number of shares for each contract Price of the shares for each contract Number of shares multiplied by the price of the shares for each contract Average price when the shares are purchased for each contract Unrealized profit and loss for each contract Actual profit and loss for each contract e Account number 5x1 means there are five contracts in this portfolio For details about this data see Interactive Brokers API Reference Guide Display the market price for each contract in the portfolio p marketPrice ans 8 60 582 95 591 79 188 44 42 24 portfolio Close the IB Trader Workstation connection close ib Retrieve Current Portfolio Data Using the Account Number Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Retrieve current Interactive Brokers portfolio data using ib and account number string acctno acctno
188. jects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx order Order request structure Order request specified as a structure using Bloomberg EMSX field properties Use getAllFieldMetaData to view all available field property options for order Convert the number of shares to a 32 bit signed integer using int32 order contains these fields Field Description EMSX_TICKER Bloomberg EMSX ticker symbol 4 29 A Functions Alphabetical List 4 30 Field Description EMSX_AMOUNT Bloomberg EMSX amount of shares EMSX_ORDER_TYPE Bloomberg EMSX order type EMSX_BROKER Bloomberg EMSX broker name EMSX_TIF Bloomberg EMSX time in force EMSX_HAND_INSTRUCTION Bloomberg EMSX hand instruction EMSX_SIDE Bloomberg EMSX buy or sell specification Example order EMSX_TICKER XYZ order EMSX_AMOUNT int32 100 order EMSX_ORDER_ TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EM
189. kstation contract IContract object IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types function_handle char contractdetails Output Arguments d Interactive Brokers contract details data structure scalar Interactive Brokers contract details data returned as a structure When using an event handler function d is a scalar that denotes the contract detail data request identifier reqid Contract detail data request identifier scalar Contract detail data request identifier returned as a scalar Interactive Brokers uses this number to match responses to the correct data request when multiple data requests are present More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection
190. ld timeOut to 200 milliseconds Route the order using the Bloomberg EMSX connection c route strat and options structure options options useDefaultEventHandler true options timeOut 200 events routeOrderWithStrat c route strat options events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order Routed The default event handler processes the events associated with routing the order routeOrderWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 routeOrderWithStrat Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx route Route request structure Route request specified as a structure containing these fields Convert the numbers to 32 bit signed integers using int32 EMSX_SEQUENCE must denote an existing order sequence nu
191. ler Data Types Function _handle char Output Arguments d Interactive Brokers order data structure double Interactive Brokers order data returned as a structure containing these fields Status Filled Remaining Average fill price Permanent identifier Parent identifier Last fill price Client identifier Why held When using an event handler function d is a double containing the unique order identifier More About Tips ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 createOrder Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 i Interactive Brokers API Reference Guide See Also close getdata history ibtws orderid realtime timeseries Introduced in R2013b 4 199 A Functions Alphabetical List 4 200 getdata Request current Interactive Brokers data Syntax d getdata ib ibContract d getdata ib ibContract eventhandler Description d getdata ib ibContract requests Interactive Brokers current data over the IB Trader Workstation connection ib using the IB Trader Workstation IContract object ibContract to signify the instrument d getdata ib ibCo
192. lose X closes the X_TRADER connection X Examples Close X_TRADER Connection close X Create an Order Using X_TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 Input Arguments X X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr More About Workflows for Trading Technologies X TRADER on page 2 4 close X_TRADER API See Also xtrdr Introduced in R2013a 4 135 A functions Alphabetical List 4 136 createlnstrument Create instrument for X_TRADER Syntax createInstrument c s createInstrument c Name Value Description createInstrument c s creates the X_TRADER instrument defined by the structure s with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference createInstrument c Name Value creates the instrument using one or more Name Value pair arguments with names and values corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Examples Create an X_TRADER Instrument Using an Input Structure The instruments used in these examples continually expire To ensure you use a current inst
193. lue contain information about the Bloomberg EMSX fields Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx brokerstrat Broker and strategy request structure Broker and strategy request specified as a structure that contains Bloomberg EMSX fields Use getAl1FieldMetaData to view all available fields for brokerStrategyStruct Example brokerstrat EMSX_ TICKER ABCD US Equity Data Types struct Output Arguments r Broker and strategy information structure Broker and strategy information returned as a structure 4 53 A Functions Alphabetical List 4 54 More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 See Also close createOrder createOrderAndRoute createOrderAndRouteWithStrat deleteOrder deleteRoute emsx modifyOrder orders routeOrder routes Introduced in R2013a modifyOrder modifyOrder Modify Bloomberg EMSX order Syntax events modifyOrder c modorder events mo
194. lume The id field is a number that tracks the real time data request for IB Trader Workstation IContract object ipbContract When you create multiple contracts each real time data display has a different value for the id field that corresponds to a specific contract Cancel the real time market data request using tickerid ib Handle cancelMktData tickerid Close the IB Trader Workstation connection close ib Request Real Time Data Using an Event Handler To request real time data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Set the field f to the tick type for RTVolume 233 RTVolume contains e Last trade price e Last trade size e Last trade time Total volume Volume weighted average price VWAP Single trade flag For details about RTVolume see Interactive Brokers API Reference Guide 4 267 A functions Alphabetical List f 233 Request real time data using ib ibContract and f Use the sample event handler ibExampleEventHandler to display the real time data in the Command Window tickerid realtime ib ibContract f ibExampleEventHandler tick
195. mber Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number EMSX_TICKER Bloomberg EMSX ticker symbol EMSX_AMOUNT Bloomberg EMSX number of shares EMSX_BROKER Bloomberg EMSX broker name EMSX_HAND_ INSTRUCTION Bloomberg EMSX hand instruction Example route EMSX_SEQUENCE int32 728918 route EMSX_ TICKER XYZ route EMSX AMOUNT int32 100 route EMSX BROKER BB route EMSX HAND INSTRUCTION ANY Data Types struct strat Order strategies structure Order strategies specified as a structure that contains the fields EMSX_STRATEGY_NAME EMSX_STRATEGY_FIELD_ INDICATORS and 4 121 A Functions Alphabetical List 4 122 EMSX_STRATEGY_FIELDS The structure field values must align with the strategy fields specified by EMSX_STRATEGY_NAME For details about strategy fields and ordering see getBrokerInfo Convert EMSX_STRATEGY_FIELD_ INDICATORS to a 32 bit signed integer using int32 Set EMSX_STRATEGY_FIELD INDICATORS equal to 0 for each field to use the field data setting in EMSX_FIELD_ DATA Or set EMSX_STRATEGY_ FIELD INDICATORS equal to 1 to ignore the data in EMSX_FIELD_DATA Example strat EMSX_STRATEGY_ NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a non
196. meout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure 4 13 A Functions Alphabetical List If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal i Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx modifyOrder orders routeOrder routes start stop Introduced in R2013a createOrderAndRoute createOrderAndRoute Create and route Bloomberg EMSX order Syntax events createOrderAndRoute c order events createOrderAndRoute c order timeOut timeout createOrderAndRoute useDefaultEventHandler false createOrderAndRoute c ord
197. mer if you are done processing data updates using delete delete t modifyOrder Close the Bloomberg EMSX connection close c Modify an Order Using an Options Structure To modify a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure modorder that contains the order sequence number EMSX_SEQUENCE the security EMSX_TICKER and the number of shares EMSX_AMOUNT This code modifies the order number 728905 for 200 shares of IBM Convert the numbers to 32 bit signed integers using int32 modorder EMSX_SEQUENCE int32 728905 modorder EMSX_TICKER IBM modorder EMSX_AMOUNT int32 200 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Modify the order using the Bloomberg EMSX connection c modorder and options structure options options useDefaultEventHandler true options timeOut 200 events modifyOrder c modorder options events EMSX_SEQUENCE 728905 MESSAGE Order Modified The default event handler processes the events associated with modifying the order modifyOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe
198. n c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Create and route the order with strategies using the Bloomberg EMSX connection c order and strat Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with creating and routing an order createOrderAndRouteWithStrat c order strat useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t 4 27 A functions Alphabetical List Close the Bloomberg EMSX connection close c Create and Route an Order Using an Options Structure To create and route a Bloomberg EMSX order with strategies create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand inst
199. nal Websites https developer tradingtechnologies com x_trader api Create an Order Using FIX Flyer Create an Order Using FIX Flyer This example shows how to connect to the FIX Flyer Engine process event data for sending FIX messages and interact with a counterparty using FIX messages FIX is a financial industry protocol that facilitates low latency trading For details about the FIX protocol see FIX Trading Community Connect to FIX Flyer Import the FIX Flyer Java libraries import flyer apps import flyer apps FlyerApplicationManagerFactory import flyer core session Create the FIX Flyer Engine connection c using these arguments User name username e Password password IP address ipaddress e Port number port username user password pwd ipaddress 127 0 0 1 port 7002 c fixflyer username password ipaddress port Add a Listener and Subscribe to FIX Sessions Add the FIX Flyer event listener to the FIX Flyer Engine connection c To listen for and display the FIX Flyer Engine event data in the Workspace browser use the sample event handling listener FixExampleListener Use FixExampleListener or write a custom event handling listener function fixExampleListener handles the FIX Flyer Engine events e denotes these events You can specify e as any letter lh addListener c e fixExampleListener e fixExampleListener returns a handle to the listener Lh 1 Getting S
200. nction_handle char Output Arguments d IB Trader Workstation market depth data structure double IB Trader Workstation market depth data returned as a structure containing the price level data for the bid and offer prices Price level data consists of the price and size When using an event handler function d is a double denoting the request identifier marketdepth More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions e Errors Workflow for Interactive Brokers on page 2 6 7 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder history ibtws realtime timeseries Introduced in R2015a 4 245 A functions Alphabetical List 4 246 orderid Obtain next valid order identification number Syntax id orderid ib Description id orderid ib obtains the next valid order identification number for Interactive Brokers connection ib Examples Obtain Next Valid Order Identification Number Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Obtain the next valid order identification number u
201. nd cqgconnectioneventhandler is assigned to the events in eventNames Set the API configuration properties For example to set the time zone to Eastern Time enter the following c APIConfig TimeZoneCode tzEastern c APIConfig is a CQG configuration object For details about setting the API configuration properties see CQG API Reference Guide Establish the connection to CQG startUp c CELStarted DataConnectionStatusChanged GWConnectionStatusChanged The connection event handler displays event names for a successful CQG connection 3 57 3 Sample Code for Workflows 3 58 Register an event handler to track events associated with the CQG instrument subscription streamEventNames InstrumentSubscribed InstrumentChanged IncorrectSymbol for i 1 length streamEventNames registerevent c Handle streamEventNames i varargin cqgrealtimeeventhandler varargin end Request CQG Real Time Data With the connection established subscribe to the instrument The instrument name must be formatted in the CQG long symbol view For example to subscribe to a security tied to corn enter the following instrument F US EZC realtime c instrument MATLAB writes the structure variable cqgDataEZC to the Workspace browser Display cqgDataEZC cqgDataEZC 1 1 ans Price 15x1 cell Volume 15x1 cell ServerTimestamp 15x1 cell Timestamp 15x1 cell Type 15x1 cell Name 15x
202. nd instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Create the order using the Bloomberg EMSX connection c order and options structure options options useDefaultEventHandler true options timeOut 200 events createOrder c order options events EMSX_SEQUENCE 354646 MESSAGE Order created The default event handler processes the events associated with creating the order createOrder returns events as a structure that contains these fields 4 11 A Functions Alphabetical List Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service
203. ndler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t t is the timer object Subscribe to events for Bloomberg EMSX orders using the Bloomberg EMSX connection c and Bloomberg EMSxX field list fields Use the custom event handler by setting the name value pair argument useDefaultEventHandler to false 4 83 A functions Alphabetical List 4 84 fields EMSX_BROKER EMSX_AMOUNT EMSX_FILLED events subs orders c fields useDefaultEventHandler false events subs com bloomberglp blpapi SubscriptionList 2c5b1c7e events contains an empty double The custom event handler processes the event queue subs contains the Bloomberg EMSX subscription list object Unsubscribe from order events using the Bloomberg EMSX subscription list object subs Stop the timer to stop data updates using stop c Session unsubscribe subs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Subscribe to Order Events Using a Timeout Create the Bloomberg EMSX connection C c emsx blp emapisvc_beta Subscribe to events for Bloomberg EMSX orders using the Bloomberg EMSX connection c and Bloomberg EMSX field list fields Specify the name value pair arg
204. ne with port number 7496 ib ibtws 7496 ibtws creates the IB Trader Workstation connection object ib Close the IB Trader Workstation connection using the IB Trader Workstation connection object ib close ib d Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 Input Arguments ib IB Trader Workstation connection connection object 4 191 A Functions Alphabetical List IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws More About Workflow for Interactive Brokers on page 2 6 Interactive Brokers API Reference Guide See Also ibtws Introduced in R2013b 4 192 createOrder createOrder Create IB Trader Workstation order Syntax d createOrder ib ibContract ibOrder id d createOrder ib ibContract ibOrder id eventhandler Description d createOrder ib ibContract ibOrder id creates an IB Trader Workstation order over the IB Trader Workstation connection ib using the IB Trader Workstation IOrder object ibOrder with a unique order identifier id to denote the order information createOrder uses the IB Trader Workstation IContract object ibContract
205. nection Syntax close c Description close c closes the FIX Flyer Engine connection Cc Examples Close the FIX Flyer Connection Create the FIX Flyer Engine connection C using these arguments User name username e Password password IP address ipaddress e Port number port username user password pwd ipaddress 127 0 0 1 port 7002 c fixflyer username password ipaddress port Close the FIX Flyer Engine connection close c Create an Order Using FIX Flyer on page 1 19 close Input Arguments c FIX Flyer Engine connection connection object FIX Flyer Engine connection specified as a connection object created using fixf lyer More About Workflow for FIX Flyer on page 2 10 See Also fixflyer Introduced in R2015b 4 283 A Functions Alphabetical List fix2struct Convert FIX message string to structure array Syntax fixstruct fix2struct fixstr Description fixstruct fix2struct fixstr converts raw FIX message strings in the cell array fixstr toa structure array fixstruct Examples Convert FIX String to Structure Array For this example assume that a counterparty sends you raw FIX messages in fixstr The FIX protocol version is 4 4 Convert the raw FIX messages in fixstr to a structure array fixstruct There are two raw FIX messages in fixstr fixstruct fix2struct fixstr fixstruct BeginString 2x1 cell ClOrdID 2x1 cell
206. nection close c Modify a Route with Strategies Using a Custom Event Handler To modify a route for a Bloomberg EMSX order with strategies Create the connection C using emsx 4 75 A functions Alphabetical List 4 76 Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_ STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to
207. nection close X i Create an Order Using X TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 Input Arguments X X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr S X_TRADER API properties structure X_TRADER API properties specified as a structure where the field names match the X_TRADER API properties For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example S S Exchange Eurex S Product OGBM S ProdType Option S Contract Jani2 P12300 S Alias TestiInstrument3 Data Types struct createOrderSet Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example createOrderSet X Count 0O Alias ReadProperties b WriteProperties DebugLogLevel 3 QuoteWithCancelReplace 0 EnableOrderUpdateData O Enabl Property1 X_TRADER API options string X_TRADER API options specified using the details described in Trading Technologies X_TRADER API P
208. negative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure routeOrderWithStrat Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx getBrokerInfo modifyOrder orders route
209. ng events associated with connection status Set up the API configuration properties Then register an event handler for tracking events associated with building and initializing the output data structure For an example demonstrating these activities see Request CQG Intraday Tick Data on page 3 53 See CQG API Reference Guide to learn more about event handlers and the API configuration properties Request timed bar data for instrument XYZ XYZ for the last fraction of a day instrument XYZ XYZ startdate now 1 enddate now intraday 1 timeseries c instrument startdate enddate intraday MATLAB writes variable cqgTimedBarData to the Workspace browser Display cqgTimedBarData cqgTimedBarData cqgTimedBarData 1 0e 09 0 0007 0 0007 0 0007 0 0007 0 0007 1475 2 1475 1475 2 1475 2 1475 2 1475 2 1475 2 2 1475 1475 1475 1475 1475 1475 1475 1475 1475 1475 2 1475 1475 2 1475 2 1475 2 1475 2 1475 2 1475 2 2 2 1475 2 1475 1475 2 1475 2 1475 2 1475 2 1475 2 1475 1475 2 1475 1475 2 1475 1475 2 1475 1475 2 1475 ymnwnmn yrywwnr yywnwn yprywmwnr ymywmnwnr cqgTimedBarData returns timed bar data for the specified instrument The columns of cqgTimedBarData display data corresponding to the timestamp open price high price low price close price mid price HLC3 average price and tick volume Close the CQG connection 4 183
210. ng the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide Data Types cell f Interactive Brokers fields string cell array Interactive Brokers fields specified as a string or a cell array of strings These fields correspond to numeric identifiers that specify the Interactive Brokers generic market data tick types For details see Interactive Brokers API Reference Guide Data Types char cell eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler 4 269 A Functions Alphabetical List Data Types function handle char Output Arguments tickerid Interactive Brokers market request identifier double Interactive Brokers market request identifier specified as a double for tracking and canceling the market data request tickerid is a scalar for one Interactive Brokers contract and a vector of scalars for multiple contracts More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the cont
211. ns 3 mins 5 mins e 10 mins e 15 mins 20 mins 4 223 A Functions Alphabetical List 4 224 e 30 mins e 1 hour e 2 hours 3 hours e 4 hours 8 hours ticktype Types of market data ticks TRADES default MIDPOINT BID ASK BID_ASK HISTORICAL VOLATILITY OPTION IMPLIED VOLATILITY Types of market data ticks specified as one of the preceding enumerated strings The Interactive Brokers API predetermines these strings to denote tick values to collect tradehours Trading hours false default true Trading hours specified as the logical true or false When this flag is set to true this function returns data only within regular trading hours Otherwise this function returns all data Data Types logical eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types Function_handle char Output Arguments d Interactive Brokers aggregated intraday data matrix double timeseries Interactive Brokers aggregated intraday data returned as a matrix with these columns Numeric representation of a dat
212. nstrument with the CQG Trader Com API using a COQGInstrument object to specify the instrument create the connection c using cqg and startup Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register event handlers for tracking events associated with instrument subscription order and account Subscribe to the instrument and create the CQGInstrument object cqgInst Then set up the account credentials accountHand1le For an example demonstrating these activities see Create CQG Orders on page 3 45 See CQG API Reference Guide to learn more about the event handlers the API configuration properties and the CQGInstrument object To create a limit order you can use the bid price Extract the CQG bid object qtBid from the previously defined CQGInstrument object cqgInst qtBid cqgInst get Bid Create a limit order that buys one share of the previously subscribed security cqgInst using the previously defined account credentials accountHand1le and qtBid for the limit price quantity 1 limitprice qtBid get Price oLimit createOrder c cqgInst 2 accountHandle quantity limitprice oLimit Place ans 4 163 A functions Alphabetical List 4 164 OrderChanged The CQGOrder object oLimit contains the order The CQG API executes the limit order using the CQG API function Place After execution the order status changes Close
213. nt handling listener FixExampleListener returns the raw FIX message in the structure fixResponseStruct Display the contents of fixResponseStruct fixResponseStruct fixResponseStruct Create an Order Using FIX Flyer BeginString BodyLength MsgType SenderCompID TargetCompID MsgSeqNum SendingTime PossDupFlag PossResend AvgPx Cl0rdID CumQty ExecID LastMkt LastPx LastQty Order ID OrderQty OrdStatus Side Symbol Text TransactTime TradeDate ExecType LeavesQty CheckSum close c See Also addListener fixflyer sendMessage More About FIX 4 4 255 8 Beta Alpha 16 20150602 19 31 56 068 N N 85 47 338 100 exec 454053004605080 FL 85 47 100 order 454053004596042 100 ee 2 ABC Done For Day Execution 20150602 19 31 56 066 20150602 DSa 0 007 The fields of the structure fixResponseStruct contain FIX tag names from the returned raw FIX message The values of the structure contain the values of the returned raw FIX message Close the FIX Flyer Connection Close the FIX Flyer Engine connection Workflow for FIX Flyer on page 2 10 1 21 1 Getting Started External Websites FIX Trading Community 1 22 Writing and Running Custom Event Handler Functions with Bloomberg EMSX Writing and Running Custom Event Handler Functions
214. nt object cqgInst qtTrade cqgInst get Trade Create a stop order that buys one share of the previously subscribed security cqgInst using the previously defined account credentials accountHandle and qtTrade for the stop price quantity 1 stopprice qtTrade get Price oStop createOrder c cqgInst 3 accountHandle quantity stopprice oStop Place ans OrderChanged Create CQG Orders The CQGOrder object oStop contains the order The CQG API executes the stop order using the CQG API function Place After execution the order status changes To create a stop limit order use both the bid and trade prices defined above Create a stop limit order that buys one share of the subscribed security cqgInst using the defined account credentials accountHand1le quantity 1 oStopLimit createOrder c cqgInst 4 accountHandle quantity limitprice stopprice oStopLimit Place ans OrderChanged The CQGOrder object oStopLimit contains the order The CQG API executes the stop limit order using the CQG API function Place After execution the order status changes Close the CQG Connection shutDown c See Also close cqg createOrder history realtime shutDown startuUp timeseries Related Examples 7 Create an Order Using CQG on page 1 11 Request CQG Historical Data on page 3 50 Request CQG Real Time Data on page 3 57 7 Request CQG Intraday Tick Data on page 3 53 Mo
215. ntract eventhandler requests Interactive Brokers current data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Request Current Data To request Interactive Brokers current data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request current data using ib and ibContract d getdata ib ibContract d getdata LAST_PRICE 6 85 LAST_SIZE 1 00 VOLUME 187 00 BID_PRICE 6 84 BID_SIZE 14 00 ASK_PRICE 6 86 ASK_SIZE 13 00 d contains these fields e Last price e Last size Volume e Bid price Bid size Ask price Ask size Display the data in the BID PRICE field of d d BID_ PRICE ans 6 84 Close the IB Trader Workstation connection close ib Request Current Data Using an Event Handler To request Interactive Brokers current data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Broke
216. o include all data or only data within regular trading hours d history ib ibContract startdate enddate ticktype period tradehours eventhandler requests Interactive Brokers historical data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function 4 205 A Functions Alphabetical List 4 206 Examples Request Interactive Brokers Historical Data with TRADES Default Tick Type and 1 Day Default Period To request historical data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Historical Data on page 3 32 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request the last 5 days of historical data using ib and ibContract startdate floor now 5 enddate floor now d history ib ibContract startdate enddate d 1 0e 05 3534 0079 3534 0078 0 0080 0078 0 3534 0 0079 0 0 0080 0078 QO 0078 2386 0 0079 0 0078 0 0 0079 1669 0 1727 0079 0 0078 0 1982 0 0 0 1075 0 0079 1420 0 0078 3534 0079 0 3534 0078 0 0080 0076 0080 0077 0078 3188 0080 5568 2239 0077 3723 0079 NNNNN ooo0oo0oo0 ooo0oo0oo0
217. o 32 bit signed integers using int32 This code specifies these route request fields Order numbers 335877 and 335878 Stock symbol IBM 100 percent of shares shown on the order to be routed groupRouteOrderWithStrat Broker BMTB Any hand instruction Time in force set to DAY e Market order type route EMSX_SEQUENCE int32 335877 int32 335878 route EMSX_TICKER IBM route EMSX_AMOUNT_PERCENT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY route EMSX_TIF DAY route EMSX_ORDER_TYPE MKT Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Suppose that you create a custom event handler function called eventhandler with input argument c Run eventhandler using timer To run eventhandler immediately start the timer using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Route the orders using the Bloomberg EMSX connection c route and strat Set the flag useDefaultEventHandler to false so that eventhandler processes the
218. odified The default event handler processes the events associated with modifying a route modifyRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Modify a Route Using a Custom Event Handler To modify a route for a Bloomberg EMSX order Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE modifyRoute Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_ TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE
219. okers Historical Data Using an Event Handler To request historical data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ipbContract as shown in Request Interactive Brokers Historical Data on page 3 32 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request the last 50 days of historical data using ib ibContract and these arguments Start date is 50 days ago e End date is the current moment The empty string denotes the default tick type TRADES e Bar sizeis 1M e Within regular trading hours Sample event handler function ibExampleEventHandler Use ibExampleEventHand1er or write a custom event handler function startdate floor now 50 enddate floor now ticktype 4 211 A functions Alphabetical List 4 212 period 1M tradehours true eventhandler ibExampleEventHandler d history ib ibContract startdate enddate ticktype period tradehours eventhandler 1576 00 Columns 1 through 4 1x1 COM TWS_TwsCtr1_1 22 00 1576 00 20140718 Columns 5 through 10 582 50 596 76 568 51 594 94 1 00 1 00 Columns 11 through 14 1 00 0 1x1 struct historicalData d is the request identifier After d ibExampleEventHandler streams historical
220. ol Style pushbutton String Close Callback evalin base close ib close findobj Tag IBOrderBlotter Position 607 5 80 20 end MATLAB displays the IB Order Blotter Create and Manage an Interactive Brokers Order 4 IB Order Blotter i baee Status Filled Remaining Avg Fill Price Id ParentId Last Fill Price Client Id Why Held cose _ Request Open Order Data Request information for all open orders using only this client and the sample event handler ibExampleOrderEventHandler o orders ib true ibExampleOrderEventHandler O is an empty double because ibExampleOrderEventHandler displays the data for all open orders in the IB Order Blotter 3 27 3 Sample Code for Workflows 3 28 a Amiz Status Filled Remaining Avg Fill Price Id Parent Id Last Fill Price ClientId Why Held Submitted 380774589 0 0 cose Create the IB Trader Workstation IContract and IOrder Objects Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values XYZ symbol Stock security type Aggregate exchange USD currency ibContract ib Handle createContract ibContract symbol XYZ ibContract secType STK ibContract exchange SMART ibContract currency USD ibContract Interface Tws_ActiveX_Control_module ICon
221. olio realizedPNL Actual profit and loss for each contract in the portfolio accountName Account number More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions e Errors i Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Interactive Brokers API Reference Guide See Also close createOrder executions getdata history ibtws marketdepth timeseries 4 263 A Functions Alphabetical List Introduced in R2015a 4 264 realtime realtime Request Interactive Brokers real time data Syntax tickerid realtime ib ibContract fF tickerid realtime ib ibContract f eventhandler Description tickerid realtime ib ibContract f requests Interactive Brokers real time data using IB Trader Workstation connection ib IB Trader Workstation IContract object ibContract and Interactive Brokers fields f tickerid realtime ib ibContract f eventhandler requests Interactive Brokers real time data using an event handler function eventhandler Use the sample event handler ipbExampleEventHandler or write a custom event handler function Examples Request Real Time Data To request
222. omberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer createOrderAndRoute Create and route the order using the Bloomberg EMSX connection c and order Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with creating and routing an order createOrderAndRoute c order useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Create and Route an Order Using an Options Structure To create and route a Bloomberg EMSX order create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of share
223. omberg EMSX connection c associated with these Bloomberg EMSxX fields fields EMSX_TICKER EMSX_AMOUNT EMSX_FILL events subs orders c fields events MSG_TYPE E MSG_SUB_ TYPE 0 EVENT_STATUS 4 subs com bloomberglp blpapi SubscriptionList 4bc3dc78 events contains fields for the events associated with the existing Bloomberg EMSX orders subs contains the Bloomberg EMSX subscription list object Create the Order Create an order request structure order for a buy market order of 400 shares of IBM Specify the broker as EFIX use any hand instruction and set the time in force to DAY order EMSX_ORDER_TYPE MKT order EMSX_SIDE BUY order EMSX_TICKER IBM order EMSX_AMOUNT int32 400 order EMSX_BROKER EFIX order EMSX_HAND_INSTRUCTION ANY order EMSX_TIF DAY Create the order using the Bloomberg EMSX connection c and the order request structure order events createOrder c order order_events EMSX_SEQUENCE 354646 3 13 3 Sample Code for Workflows MESSAGE Order created The default event handler processes the events associated with creating the order createOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Modify the Order Define the structure modorder that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_
224. on Place After execution the order status changes createOrder Close the CQG connection shutDown c Create and Place a Stop Limit Order To create and place a stop limit order for shares of an instrument with the CQG Trader Com API using a CQGInstrument object to specify the instrument create the connection c using cqg and startup Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register event handlers for tracking events associated with instrument subscription order and account Subscribe to the instrument and create the CQGInstrument object cqgInst Then set up the account credentials accountHand1e For an example demonstrating these activities see Create CQG Orders on page 3 45 See CQG API Reference Guide to learn more about the event handlers the API configuration properties and the CQGInstrument object To create a stop limit order you can use the bid and trade prices Extract the CQG bid object qtBid and the CQG trade object qt Trade from the previously defined CQGInstrument object cqgInst qtBid cqgInst get Bid qtTrade cqgInst get Trade Create a stop limit order that buys one share of the subscribed security cqgInst using the defined account credentials accountHand1le and qtBid for the limit price and qtTrade for the stop price quantity 1 limitprice qtBid get Price stopprice qtTrade get Price oSto
225. on in the fixExampleListener m file Data Types Function_handle Output Arguments 1h Listener handle object Listener handle returned as a handle to a FIX Flyer listener object addListener More About Workflow for FIX Flyer on page 2 10 See Also close fixflyer sendMessage Introduced in R2015b 4 277 A functions Alphabetical List 4 278 sendMessage Send FIX message to FIX Flyer Engine Syntax status sendMessage c fixmsg Description status sendMessage c fixmsg sends the FIX message fixmsg using the FIX Flyer Engine connection C Examples Send FIX Message Create the FIX Flyer Engine connection c using these arguments e User name username e Password password IP address ipaddress Port number port username user password pwd ipaddress 127 0 0 1 port 7002 c fixflyer username password ipaddress port Add the FIX Flyer event listener to the FIX Flyer Engine connection c To listen for and display the FIX Flyer Engine event data in the Workspace browser use the sample event handling listener FixExampleListener Use FixExampleListener or write a custom event handling listener function fixExampleListener handles the FIX Flyer Engine events e denotes these events You can specify e as any letter sendMessage lh addListener c e fixExampleListener e fixExampleListener returns a handle to the listener Lh Subscribe to
226. ontract ibContract symbol GOOG ibContract secType STK ibContract exchange SMART ibContract currency USD Create the IB Trader Workstation IOrder object ibOrder Here this object describes a limit order to sell two shares with a limit price of 590 ibOrder ib Handle createOrder ibOrder action SELL ibOrder totalQuantity 2 ibOrder orderType LMT ibOrder ilmtPrice 590 For details about the IContract and IOrder objects see Interactive Brokers API Reference Guide Create a unique order identifier id id orderid ib Execute the order using IB Trader Workstation connection ib IB Trader Workstation IContract object ibContract IB Trader Workstation IOrder object ibOrder Unique order identifier id d createOrder ib ibContract ibOrder id Retrieve order information 0 from all clients by setting client to false Il o orders ib false 0 1x2 struct array with fields 4 251 A functions Alphabetical List 4 252 Type EventID orderld contract order orderState o contains a structure array The array contains a structure with data for each open order The structure fields are Order type Event identifier Order identifier Contract data Order data Order status Retrieve the current status of the order o orderState ans status Submitted initMargin 1 7976931348623157E308 maintMargin 1 7976931348623157E308 orderSt
227. open Interactive Brokers orders ib Handle reqGlobalCancel This method cancels all open Interactive Brokers orders globally The order is canceled despite where it is created Close the Connection Close the IB Trader Workstation connection ib close ib See Also close createOrder getdata history ibtws orderid orders timeseries Create and Manage an Interactive Brokers Order Related Examples Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 More About Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 External Websites Interactive Brokers API Reference Guide 3 31 3 Sample Code for Workflows Request Interactive Brokers Historical Data 3 32 This example shows how to connect to the IB Trader Workstation create an IB Trader Workstation IContract object and request historical data For details about the IContract object see Interactive Brokers API Reference Guide To access the code for this example see IBHistoricalDataWorkflow m Connect to the IB Trader Workstation and Create the IContract Object Connect to the IB Trader Workstation and create connection ib using the local host and
228. oring intraday tick data rawEventNames TicksResolved TicksAdded 3 53 3 Sample Code for Workflows 3 54 for i 1 length rawEventNames registerevent c Handle rawEventNames i varargin cqgintradayeventhandler varargin end Request CQG Intraday Tick Data Pass an additional optional request property by creating the structure x and setting the optional property To see only bid tick data for example set TickFilter to tfBid x TickFilter tfBid TickFilter and SessionsFilter are the only valid additional optional properties for calling timeseries without a timed bar request For additional property values you can set see CQG API Reference Guide Request intraday tick data for instrument XYZ XYZ for the last 2 days using the additional optional request property xX instrument XYZ XYZ startdate now 2 enddate now timeseries c instrument startdate enddate x pause 1 pause causes MATLAB to wait 1 second before continuing to give time for CQG to subscribe to the instrument MATLAB writes the variable cqgTickData to the Workspace browser Display cqgTickData cqgTickData cqgTlickData Timestamp 2x1 cell Price 2x1 double Volume 2x1 double PriceType 2x1 cell CorrectionType 2x1 cell SalesConditionLabel 2x1 cell SalesConditionCode 2x1 double ContributorId 2x1 cell ContributorIdCode 2x1 double Request CQG Intraday Tick Data MarketS
229. orkstation IContract Objects Create the IB Trader Workstation IContract object for the first security Here this object describes a security with these property values AAA symbol Stock security type Aggregate exchange USD currency ibContract1 ib Handle createContract ibContract1 symbol AAA ibContract1 secType STK ibContract1 exchange SMART ibContract1 currency USD Create the IB Trader Workstation IContract object for the second security symbol BBB ibContract2 ib Handle createContract ibContract2 symbol BBB ibContract2 secType STK ibContract2 exchange SMART ibContract2 currency USD Create the IB Trader Workstation IContract object for the third security symbol DDDD ibContract3 ib Handle createContract ibContract3 symbol DDDD ibContract3 secType STK ibContract3 exchange SMART ibContract3 currency USD Display the data in the symbol property of ipbContract1 ibContract1 symbol Request Interactive Brokers Real Time Data ans AAA Request real time data for the three securities Set f to 100 to retrieve the Option Volume tick type For details about other generic market data tick types see Interactive Brokers API Reference Guide Use the sample event handler ibExampleRealtimeEventHand1ler to process the real time data events or write a custom event handler function contracts ibContract1 ibContract2 ibContract3 f 10
230. pLimit createOrder c cqgInst 4 accountHandle quantity limitprice stopprice oStopLimit Place ans OrderChanged The CQGOrder object oStopLimit contains the order The CQG API executes the stop limit order using the CQG API function Place After execution the order status changes Close the CQG connection 4 165 A Functions Alphabetical List 4 166 shutDown c Create an Order Using CQG on page 1 11 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 Input Arguments c CQG connection connection object CQG connection specified as a CQG connection object created using cqg s CQG instrument name string CQGInstrument object CQG instrument name specified as a string or a CQGInstrument object denoting the instrument or security for the order transaction For more information about creating a CQGInstrument object see CQG API Reference Guide Data Types char account CQG account credentials CQGAccount object CQG account credentials specified as a CQGACcount object This object encapsulates all data pertinent to your account For more information about creating a CQ GAccount object see CQG API Reference Guide quantity CQG order quantity scalar CQG order quantity specified as a scalar denoting the number of shares to order A pos
231. pc 3 bspc 2 bhgt bwid oe ui Product uicontrol Style text Tag Position 2 bspct bwid 3 bspc 2 bhgt bwid bhgt ui Type uicontrol Style text Tag Position 3 bspct 2 bwid 3 bspe 2 bhgt bwid bhgt ui Contract uicontrol Style text Tag Position 4 bspct 3 bwid 3 bspc 2 bhgt owid bhgt uicontrol Style text String Last Price Position bspc 2 bspotbhgt bwid bhgt uicontrol Style text String Last Qty Position 2 bspctbwid 2 bspc bhgt bwid bhgt uicontrol Style text String Change Position 3 bspc 2 bwid 2 bspct bhgt bwid bhgt ui Last uicontrol Style text Tag Position bspc bspc bwid bhgt ui Quantity uicontrol Style text Tag Position 2 bspc bwid bspc bwid eh ui Change uicontrol Style text Tag Position 3 bspc 2 bwid bspc bwid bhgt Create a Table Create a table containing order information 3 5 3 Sample Code for Workflows data data uibook data ones 10 4 uitable Data data ColumnName Bid Bid Size Ask Ask Size Position 5 105 350 205 Store Data setappdata 0 TTOrderBookHandle uibook setappdata 0 TTOrderBookUIData ui Listen for Event Data Listen for event data with depth updates enabled X Instrument 1 Open 1 BB Order Book PriceinstrumentDepthUpdate calu ie Contract 2F May13
232. pe tradehours eventhandler Description d timeseries ib ibContract startdate enddate barsize requests Interactive Brokers aggregated intraday data using the IB Trader Workstation connection ib and IB Trader Workstation IContract object ibContract to signify the instrument Request data between startdate and enddate using the tick aggregation interval barsize for default tick type TRADES d timeseries ib ibContract startdate enddate barsize ticktype requests Interactive Brokers aggregated intraday data for a specific type of market data tick ticktype d timeseries ib ibContract startdate enddate barsize ticktype tradehours requests Interactive Brokers aggregated intraday data using the flag tradehours to include all data or only data within regular trading hours d timeseries ib ibContract startdate enddate barsize ticktype tradehours eventhandler requests Interactive Brokers aggregated intraday data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function timeseries Examples Request Interactive Brokers Intraday Data Aggregated Every 5 Minutes with TRADES Default Tick Type To request intraday data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Broker
233. perties createOrderSet createOrderSet X Close the connection close X Create an Order Set Using an Input Structure Start X_TRADER X xtrdr Define an input structure S with fields corresponding to X_TRADER API options Count Alias ReadProperties b WriteProperties b EnableOrderSetUpdates 1 sEnableOrderriLIDAtA 0 EnableOrderSend 0 EnableOrderAutoDelete 0 QuotingOrderProfile DebugLogLevel 3 QuoteWithCancelReplace 0 EnableOrderUpdateData 0 EnableFillCaching 0 AvgOpenPriceMode NONE EnableOrderRejectData 0 OrderStatusNotifyMode ORD NOTIFY_NONE J ahs DANNNNNNDNNNAANAVHVNHVHHNNW Create an order set createOrderSet X S Close the connection close X Create an Order Set Using Name Value Pair Arguments Start X_TRADER X xtrdr 4 151 A functions Alphabetical List 4 152 Create an order set using name value pair arguments corresponding to X_TRADER API options createOrderSet X Count O Alias ReadProperties b WriteProperties b EnableOrderSetUpdates 1 EnableOrderFillData 0 EnableOrderSend 0 EnableOrderAutoDelete 0 QuotingOrderProfile DebugLogLevel 3 QuoteWithCancelReplace O EnableOrderUpdateData 0 EnableFillCaching O AvgOpenPriceMode NONE EnableOrderRejectData O OrderStatusNotifyMode ORD_NOTIFY_NONE Close the con
234. pes double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure routeOrder Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx modifyOrder orders routeOrderWithStrat routes start stop Introduced in R2013a 4 103 A Functions Alphabetical List 4 104 groupRouteOrderWithStrat Route multiple Bloomberg EMSX orders with strategies Syntax events groupRouteOrderWit
235. port number 7496 ib ibtws 7496 MATLAB returns ib as the connection to the IB Trader Workstation with the Interactive Brokers ActiveX object the local host and the port number that you choose Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values XYZ symbol Stock security type Aggregate exchange USD currency ibContract ib Handle createContract ibContract symbol XYZ ibContract secType STK ibContract exchange SMART ibContract currency USD ibContract Interface Tws_ ActiveX_Control_module IContract ibContract contains the stock symbol security type exchange and currency for security XYZ Request Interactive Brokers Historical Data Request the last 5 days of historical data using ibContract Request Interactive Brokers Historical Data startdate floor now 5 enddate floor now d history ib ibContract startdate enddate d 1 0e 05 7 3534 0 0079 0 0080 0 0078 0 0078 0 2386 0 1727 0 0079 0 7 3534 0 0078 0 0080 0 0078 0 0079 0 1669 0 1075 0 0079 0 7 3534 0 0079 0 0079 0 0078 0 0078 0 1982 0 1420 0 0078 0 7 3534 0 0079 0 0080 0 0076 0 0078 0 3188 0 2239 0 0077 0 7 3534 0 0078 0 0080 0 0077 0 0080 0 5568 0 3723 0 0079 0 d contains the historical data for 5 days Each row of d contains historical data for 1 day The columns in matrix d are Numeric representation of a date Open p
236. properties without timed bar data then enter for this argument 4 185 A Functions Alphabetical List 4 186 Data Types double x CQG request properties request properties structure CQG request properties specified as a CQG request properties structure Create this structure by writing MATLAB code to set additional optional request properties For additional optional properties you can set see CQG API Reference Guide Example x UpdatesEnabled false Data Types struct More About Workflow for CQG on page 2 8 CQG API Reference Guide See Also cqg createOrder history realtime Introduced in R2013b ibtws ibtws Create IB Trader Workstation connection Syntax ib ibtws host port Description ib ibtws host port creates a connection to IB Trader Workstation on a machine with IP address host and port number port ibtws returns the IB Trader Workstation connection object ib Examples Connect to the IB Trader Workstation on the Local Machine Connect to the IB Trader Workstation on the local machine using port number 7496 ib ibtws 7496 ib ibtws with properties ClientId 0 Handle 1x1 COM TWS_TwsCtr1_1 Host Port 7496 MATLAB returns ib as the connection to the IB Trader Workstation with the Interactive Brokers ActiveX object the local host and the port number that you choose Display the Handle property of ib ib Handle ans 4 187
237. r Structure that repeats the contents of the columns Event type Close the IB Trader Workstation connection close ib Request Interactive Brokers Real Time Data on page 3 35 Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws timeseries ibContract IB Trader Workstation contract IContract object IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide startdate Start date date string date scalar Start date specified as a starting date string or scalar Data Types double char enddate End date date string date scalar End date specified as an ending date string or scalar Data Types double char barsize Tick aggregation interval 10 secs 15 secs 30 secs 1 min 2 mins 3 mins Tick aggregation interval specified as one of the following enumerated strings The Interactive Brokers API predetermines these strings to denote the size of aggregated bars for collecting data e 10 secs lt 15 secs 30 secs e 1 min 2 mi
238. r object and execute the order For details about the IContract and IOrder objects see Interactive Brokers API Reference Guide This example uses the sample event handler function ibExampleOrderEventHandler to populate an order blotter figure with Interactive Brokers order information Use this event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 To access the code for this example see IBOrderWorkf low m Connect to the IB Trader Workstation Connect to the IB Trader Workstation and create connection ib using the local host and port number 7496 ib ibtws 7496 Create an Example Order Blotter Create an example order blotter that the event handler populates This MATLAB code creates a MATLAB figure to contain the Interactive Brokers order information f findobj Tag IBOrderBlotter if isempty f f figure Tag IBOrderBlotter MenuBar none NumberTitle off Name IB Order Blotter pos f Position f Position pos 1 pos 2 687 335 colnames Status Filled Remaining Avg Fill Price Id Parent Id Last Fill Price Client Id Why Held data cell 15 9 uitable f Data data RowName ColumnName colnames Position 10 30 677 300 Tag OrderDataTable uicontrol Style text Position 10 5 592 20 Tag IBOrderMessage uicontr
239. rat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create and route the order with strategies using the Bloomberg EMSX connection C order and strat events createOrderAndRouteWithStrat c order strat events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed createOrderAndRouteWithStrat The default event handler processes the events associated with creating and routing the order createOrderAndRouteWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Route an Order Using a Timeout To create and route a Bloomberg EMSX order with strategies create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a
240. rder and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Modify a Route Using a Timeout To modify a route for a Bloomberg EMSX order Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 100 shares of IBM for order sequence number 731128 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 731128 modroute EMSX_TICKER IBM modroute EMSX AMOUNT int32 100 modroute EMSX_ROUTE_ID int32 1 4 65 A functions Alphabetical List 4 66 Modify the route using the Bloomberg EMSX connection c and modroute Set the timeout value to 200 milliseconds events modifyRoute c modroute timeOut 200 events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route m
241. re Find the latest installation files at http interactivebrokers github io You need an Interactive Brokers license to install and run Interactive Brokers 1 3 1 Getting Started Trading Technologies Find the latest installation files at http www tradingtechnologies com to install Trading Technologies You need a Trading Technologies license to install and run Trading Technologies 1 4 Trading System Providers Trading System Providers In this section Supported Providers on page 1 5 Connection Requirements on page 1 5 Supported Providers This toolbox supports connections to financial trading systems provided by the following corporations Bloomberg EMSX from Bloomberg L P http www bloomberg com Note Only the Bloomberg Desktop API is supported CQG http www cqg com FIX Flyer http fixflyer com IB Trader Workstation from Interactive Brokers http www interactivebrokers com Note IB Trader Workstation versions 9 69 and 9 7 and later are supported X_TRADER from Trading Technologies http www tradingtechnologies com See the MathWorks website for the system requirements for connecting to these trading systems Connection Requirements To connect to these trading systems additional requirements apply The following data service providers require you to install proprietary software on your PC Bloomberg EMSX Note You need
242. re About Workflow for CQG on page 2 8 External Websites CQG API Reference Guide 3 49 3 Sample Code for Workflows Request CQG Historical Data 3 50 This example shows how to connect to CQG define event handlers and request historical data Connect to CQG Create the CQG connection object using cqg c cqg Define Event Handlers Register the sample event handler cqgconnectioneventhandler to track events associated with connection status eventNames CELStarted DataError IsReady DataConnectionStatusChanged for i 1 length eventNames registerevent c Handle eventNames i varargin cqgconnectioneventhandler varargin end cqgconnectioneventhandler is assigned to the events in eventNames Set the API configuration properties For example to set the time zone to Eastern Time enter the following c APIConfig TimeZoneCode tzEastern c APIConfig is a CQG configuration object For details about setting API configuration properties see CQG API Reference Guide Create the CQG connection startUp c CELStarted DataConnectionStatusChanged The connection event handler displays event names for a successful CQG connection Register an event handler to build and initialize the output data matrix cqgHistoryData Request CQG Historical Data histEventNames ExpressionResolved ExpressionAdded ExpressionUpdated for i 1 length histEventNames r
243. re ordernum deleteOrder returns a status message using the default event handler events deleteOrder c ordernum timeOut timeout specifies a timeout value timeout for the execution of the default event handler deleteOrder _ useDefaultEventHandler false deletes a Bloomberg EMSX order using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with deleting orders This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true ___ deleteOrder c ordernum options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when useDefaultEventHand1er is set to true and omit this output argument when useDefaultEventHandler is set to false 4 33 A Functions Alphabetical List 4 34 Examples Delete an Order Using the Default Event Handler To delete a Bloomberg EMSX order create the connection c using emsx set up the order subscription using orders and create an order using createOrder For an example showin
244. rgument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true _ __ routeOrder c route options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when the flag useDefaultEventHandler is set to true and omit this output argument when useDefaultEventHand1ler is set to false routeOrder Examples Route an Order Using the Default Event Handler To route a Bloomberg EMSX order create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 route EMSX_BROKER BB route EMSX_HAND_INSTRUCTION ANY Route the order using t
245. rice High price e Low price Close price e Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar Close the Connection Close the IB Trader Workstation connection ib close ib See Also close createOrder getdata history ibtws timeseries Related Examples Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 3 33 3 Sample Code for Workflows Request Interactive Brokers Real Time Data on page 3 35 More About Workflow for Interactive Brokers on page 2 6 External Websites Interactive Brokers API Reference Guide 3 34 Request Interactive Brokers Real Time Data Request Interactive Brokers Real Time Data This example shows how to connect to the IB Trader Workstation create IB Trader Workstation IContract objects and request real time data For details about the IContract object see Interactive Brokers API Reference Guide This example uses the sample event handler function ibExampleRealtimeEventHand1ler to handle events associated with requesting real time data Use this event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 To access the code for this example see IBStreamingDataWo
246. ring 4 3 A Functions Alphabetical List 4 4 Bloomberg EMSX service name specified using a test or production Bloomberg EMSX servicename Data Types char Output Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection returned as a connection object with these properties Property Description Session Bloomberg EMSX session object Service Bloomberg EMSX service object Ipaddress IP address of the machine where Bloomberg EMSX is running Port Port number of the machine where Bloomberg EMSX is running More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 See Also close createOrder createOrderAndRoute routeOrder Introduced in R2013a close close Close Bloomberg EMSX connection Syntax close c Description close c closes the Bloomberg EMSX connection c Examples Close the Bloomberg EMSX Connection Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Close the Bloomberg EMSX connection close c Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page
247. ription for Bloomberg EMSX fields EMSX_BROKER and EMSX_WORKING using the Bloomberg EMSX connection c and options structure options options useDefaultEventHandler true options timeOut 200 fields EMSX_BROKER EMSX_WORKING events subs routes c fields options events MSG_TYPE 5x1 cell MSG_SUB_ TYPE 5x1 cell EVENT STATUS 5x1 int32 4 127 A Functions Alphabetical List 4 128 subs com bloomberglp blpapi SubscriptionList 463b9287 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Unsubscribe from route events using the Bloomberg EMSX subscription list object Subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx fields Bloomberg EMSX field information cell array Bloomberg EMSX field information specified using a cell array Use getAllFieldMetaData to view available field information for the Bloomberg EMSX service Example EMSX_TICKER EMSX_AMOUNT EMSX_ORDER_TYPE Data Types cell options Options for custom event
248. rkflow m Connect to the IB Trader Workstation and Create the Real Time Data Display Figure Connect to the IB Trader Workstation and create connection ib using the local host and port number 7496 ib ibtws 7496 MATLAB returns ib as the connection to the IB Trader Workstation with the Interactive Brokers ActiveX object the local host and the port number that you choose Create an example figure to display real time data This MATLAB code creates a MATLAB figure to contain the Interactive Brokers real time data f findobj Tag IBStreamingDataWorkflow if isempty f f figure Tag IBStreamingDataWorkflow MenuBar none NumberTitle off pos f Position f Position pos 1 pos 2 pos 3 37 109 colnames Trade Size Bid BidSize Ask AskSize Total Volume rownames AAA BBB DDDD data cell 3 6 uitable f Data data RowName rownames ColumnName colnames Position 10 30 582 76 Tag SecurityDataTable uicontrol Style text Position 10 5 497 20 Tag IBMessage uicontrol Style pushbutton String Close Gallback evalin base close ib close findobj Tag IBStreamingDataWorkflow Position 512 5 80 20 end MATLAB displays the empty figure 3 35 3 Sample Code for Workflows 3 36 H S Trade i BidSize AskSize Total Volume Create IB Trader W
249. rkstation connection object created using ibtws ibContract IB Trader Workstation contract IContract object IB Trader Workstation contract specified as an IB Trader Workstation IContract object This object is the instrument or security used in the order transaction Create this object by calling the Interactive Brokers API function createContract For details about createContract and the attributes that you can set see Interactive Brokers API Reference Guide eventhandler Event handler function handle string Event handler specified as a function handle or a string to identify an event handler function that processes the returned data Use the sample event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 Example eventhandler Data Types function handle char Output Arguments d Interactive Brokers current data structure double Interactive Brokers current data returned as a structure containing these tick types Last price e Last size Volume Bid price 4 203 A Functions Alphabetical List Bid size Ask price Ask size When using an event handler function d is a double denoting the request identifier More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this var
250. rn information on the instrument that you have created 4 Define events by assigning callbacks for validating or invalidating an instrument and performing calculations based on the event Based on some predefined condition Workflows for Trading Technologies X_TRADER reached when changes in the incoming data satisfy the condition event callbacks execute the functions in steps 5 6 and 7 5 Create an order set using createOrderSet to define the level of the order status events and event handlers for orders that will be submitted to X_TRADER 6 Define the order using createOrderProfile An order profile contains the settings that define an individual order to be submitted 7 Route the order for execution using the OrderSet object created by createOrderSet in step 5 8 Close the Trading Technologies X_TRADER connection using close Related Examples Create an Order Using X_TRADER on page 1 16 Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 2 5 2 Workflow Models Workflow for Interactive Brokers In this section Request Interactive Brokers Market Data on page 2 6 Create Interactive Brokers Orders on page 2 7 Request Interactive Brokers Informational Data on page 2 7 This diagram shows the functions that you can use with the IB Trader Workstation to monitor m
251. rogramming Tutorial or X_TRADER API Class Reference Data Types char Property2 X_TRADER API options string X_TRADER API options specified using the details described in Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Data Types char More About Workflows for Trading Technologies X TRADER on page 2 4 X_TRADER API See Also createInstrument createNotifier createOrderProfile xtrdr Introduced in R2013a 4 153 A functions Alphabetical List 4 154 getData Obtain current X_TRADER data Syntax D getData X S F D getData X F Description D getData X S F returns data for the fields F for the xtrdr instrument object S with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference D getData X F returns data for the fields F for all instruments associated with the xtrdr session object X Examples Return Exchange and Last Price for an Instrument Return the exchange and last price fields for the instrument defined in x Instrument 1 D Il getData X X Instrument 1 Exchange Last Ps Exchange CME Last 45 Return Exchange and Last Price for an Alias Return the exchange and last price fields for the instrument defined by the alias PriceInstrumenti getData 0 l getData X PriceInstrumen
252. rs object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request current data using ib ioContract and sample event handler function ibExampleEventHandler Use ibExampleEventHandler or write a custom event handler function 4 201 A Functions Alphabetical List 4 202 d getdata ib ibContract ibExampleEventHandler a 1418 00 Columns 1 through 5 1x1 COM TWS_TwsCtrl_1 2 00 1418 00 0 5 00 Columns 6 through 7 1x1 struct tickSize d is the request identifier After d ibExampleEventHandler streams current data to the Command Window Each column set is a type of tick For a size tick the columns are Interactive Brokers ActiveX object Event identifier Request identifier Tick type Size Structure that repeats the contents of the columns Event type Close the IB Trader Workstation connection close ib Create an Order Using IB Trader Workstation on page 1 7 Create Interactive Brokers Combination Order on page 3 39 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 getdata Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Wo
253. ruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_ STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Create and route the order using the Bloomberg EMSX connection c order strat and options structure options options useDefaultEventHandler true options timeOut 200 events createOrderAndRouteWithStrat c order strat options events EMSX_SEQUENCE 728924 EMSX_ROUTE_ID 1 4 28 createOrderAndRouteWithStrat MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRouteWithStrat returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list ob
254. ructure specified with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example S S Exchange Eurex S Product OGBM S ProdType Option Contract Jan12 P12300 S Alias TestInstrument3 Data Types struct Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example createOrderProfile X Instrument Customer lt Default gt Alias RoundOption 2 CustomerDefaults Property1 Valid X_TRADER API options string Valid X_TRADER API options specified using the details described in Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference 4 148 createOrderProfile Example createOrderProfile X Instrument Customer lt Default gt Alias RoundOption 2 CustomerDefaults Data Types char Property2 Valid X_TRADER API options string Valid X_TRADER API options specified using the details described in Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example createOrderProfile X Instrument Customer
255. rument see the Market Explorer in X_TRADER Pro Create the X_TRADER connection c xtrdr Define an input structure s with fields corresponding to valid X_TRADER API options For example create the input structure for Euro Bobl Futures s s Exchange Eurex s Product OGBM createlnstrument s ProdType Option s Contract Jani2 P12300 s Alias TestInstrument3 S S Exchange Eurex Product OGBM ProdType Option Contract Jan1i2 P12300 Alias TestInstrument3 Requirement Restart the MATLAB session before reusing an Alias setting Create an X_TRADER instrument createInstrument c s Close the connection close c Create an X_TRADER Instrument Using Name Value Pairs Create the X_TRADER connection c xtrdr Create an X_TRADER instrument for Euro Bobl Futures using name value pair arguments corresponding to valid X_TRADER API options createInstrument c Exchange Eurex Product OGBM ProdType Option Contract vdanl2 P12300 Alias TestInstrument3 Close the connection close c Retrieve Data Using Multiple X_TRADER Instruments Create the X_TRADER connection 4 137 A functions Alphabetical List 4 138 c xtrdr Create an X_TRADER instrument for Euro Bobl Futures using name value pair arguments corresponding to valid X_TRADER API options createInstrument c Exchange Eurex Product OGBM
256. run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Modify the route using the Bloomberg EMSX connection c modroute and strat Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with modifying a route modifyRouteWithStrat modifyRouteWithStrat c modroute strat useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Modify a Route with Strategies Using an Options Structure To modify a route for a Bloomberg EMSX order with strategies Create the connection C using emsx Set up the order and route subscription using orders and routes Create and route the order using createOrderAndRoute For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Define the modroute structure that contains th
257. s on page 3 4 Submit X_TRADER Orders on page 3 8 Input Arguments c X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr s X_TRADER input structure structure X_TRADER input structure specified using fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Caution If the symbols for the exchange are entered incorrectly or the exchange server is down an error appears For example if the exchange is CME and the CME exchange server is down then this error appears The price server for the Exchange CME is down Unable to create instrument Example s s Exchange Eurex s Product OGBM s ProdType Option s Contract Jan12 P12300 s Alias TestInstruments3 4 139 A Functions Alphabetical List 4 140 Data Types struct Name Value Pair Arguments Specify optional comma separated pairs of Name Value arguments Name is the argument name and Value is the corresponding value Name must appear inside single quotes You can specify several name and value pair arguments in any order as Name1 Value1 NameN ValueN Example createInstrument X Exchange Eurex Product OGBM ProdType Option Cc P12300 Alias TestInstruments Property1 Valid X_TRADER API options
258. s and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure modorder that contains the order sequence number EMSX_SEQUENCE the security EMSX_TICKER and the number of shares EMSX_AMOUNT This code modifies the order number 728905 for 200 shares of IBM Convert the numbers to 32 bit signed integers using int32 modorder EMSX_SEQUENCE int32 728905 modorder EMSX_TICKER IBM modorder EMSX_AMOUNT int32 200 Suppose you create a custom event handler function called eventhandler with input argument cC Run eventhandler using timer Start the timer to run eventhandler immediately using start For details see Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Modify the order using the Bloomberg EMSX connection c and modorder Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with modifying an order modifyOrder c modorder useDefaultEventHandler false Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates Subs Stop the timer to stop data updates using stop c Session unsubscribe subs stop t Delete the ti
259. s specified as a structure that contains the fields EMSX_STRATEGY_NAME EMSX_ STRATEGY _FIELD_ INDICATORS and EMSX_STRATEGY_FIELDS The structure field values must align with the strategy fields specified by EMSX_STRATEGY_NAME For details about strategy fields and ordering see getBrokerInfo 4 79 A Functions Alphabetical List 4 80 Convert EMSX_STRATEGY_FIELD_ INDICATORS to a 32 bit signed integer using int32 Set EMSX_STRATEGY_FIELD INDICATORS equal to 0 for each field to use the field data setting in EMSX_FIELD_ DATA Or set EMSX_STRATEGY FIELD INDICATORS equal to 1 to ignore the data in EMSX_FIELD_DATA Example strat EMSX_STRATEGY NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Data Types struct timeout Timeout value 500 milliseconds default nonnegative integer Timeout value specified as a nonnegative integer This integer denotes the time in milliseconds the event handler listens to the queue for an event for each iteration of the code The event handler can be a default or custom event handler Data Types double options Options for custom event handler or timeout value structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure Specify using a custom event handler
260. s 3 account quantity stopprice creates a stop order using a CQG stop price stopprice o createOrder c s 4 account quantity limitprice stopprice creates a stop limit order using CQG limit and stop prices Limitprice and stopprice Examples Create and Place a Market Order Using a CQGinstrument Object To create and place a market order for shares of an instrument with the CQG Trader Com API using a CQGInstrument object to specify the instrument create the connection c using cqg and startUp Register an event handler for tracking events associated with the connection status Set up the API configuration properties Then register event handlers for tracking events associated with the instrument subscription order and 4 161 A functions Alphabetical List 4 162 account Subscribe to the instrument and create the CQGInstrument object cqgInst Then set up the account credentials accountHand1e For an example demonstrating these activities see Create CQG Orders on page 3 45 See CQG API Reference Guide to learn more about event handlers API configuration properties and CQGInstrument object Create a market order that buys one share of the subscribed security cqgInst using the account credentials accountHandl1le quantity 1 oMarket createOrder c cqgInst 1 accountHandle quantity oMarket Place ans OrderChanged The CQGOrder object oMarket contains the order The CQG API executes the market order using
261. s for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when the flag useDefaultEventHand1er is set to true and omit this output argument when useDefaultEventHandler is set to false groupRouteOrderWithStrat Examples Route Orders Using the Default Event Handler To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies these route request fields Order numbers 335877 and 335878 Stock symbol IBM 100 percent of shares shown on the order to be routed Broker BMTB Any hand instruction Time in force set to DAY Market order type route EMSX_SEQUENCE int32 335877 int32 335878 route EMSX_TICKER IBM route EMSX_AMOUNT_PERCENT int32 100 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY route EMSX_TIF DAY route EMSX_ORDER_TYPE MKT Create the order strategies structure strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_ STRATEGY FIEL
262. s oSubs and routes creates rsubs createOrderAndRoute c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Route an Order Using a Timeout To create and route a Bloomberg EMSX order create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create and route the order using the Bloomberg EMSX connection c and order Set the timeout value to 200 milliseconds events createOrderAndRoute c order timeOut 200 events EMSX_SEQUENCE 335877 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identi
263. s object for containing the data about a security to process transactions For details about creating this object see Interactive Brokers API Reference Guide Request intraday data aggregated every 5 minutes using ib and ibContract startdate floor now enddate now barsize 5 mins d timeseries ib ibContract startdate enddate barsize d 735329 40 6 91 6 91 6 85 6 85 158 00 13 00 6 87 735329 40 6 85 6 87 6 85 6 87 29 00 24 00 6 86 735329 40 6 87 6 89 6 87 6 87 13 00 13 00 6 88 d returns the aggregated 5 minute data with default tick type TRADES Each row in matrix d represents a 5 minute interval The columns in matrix d are Numeric representation of a date Open price High price Low price Close price Volume Bar count e Weighted average price Flag indicating if there are gaps in the bar 4 217 A functions Alphabetical List Display the open price for the most recent bar in matrix d d 1 2 Close the IB Trader Workstation connection close ib Request Interactive Brokers Intraday Data Aggregated Every 10 Minutes with a BID Tick Type To request intraday data set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ibContract as shown in Request Interactive Brokers Real Time Data on page 3 35 An IContract object is an Interactive Brokers object for containing the data about a security to process transactions For det
264. s structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are 4 23 A functions Alphabetical List 4 24 timeOut and useDefaultEventHandler Use the events output argument when useDefaultEventHand1er is set to true and omit this output argument when useDefaultEventHand1ler is set to false Examples Create and Route an Order Using the Default Event Handler To create and route a Bloomberg EMSX order with strategies create the connection C using emsx and set up the order and route subscription using orders and routes For an example showing these activities see Manage a Bloomberg EMSX Order and Route on page 3 21 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX STRATEGY FIELD INDICATORS int32 0 0 0 st
265. s to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Create 4 19 A Functions Alphabetical List 4 20 and route the order using the Bloomberg EMSX connection c order and options structure options options useDefaultEventHandler true options timeOut 200 events createOrderAndRoute c order options events EMSX_SEQUENCE 728924 EMSX_ROUTE_ID 1 MESSAGE Order created and routed The default event handler processes the events associated with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c i Create an Order Using Bloomberg EMSX on page 1 13 Create and Manage a Bloomberg EMSX Order on page 3 12 Create an
266. sing an Options Structure To delete a Bloomberg EMSX order create the connection c using emsx set up the order subscription using orders and create an order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Define the structure ordernum that contains the order sequence number EMSX_SEQUENCE for the order to delete ordernum EMSX_SEQUENCE 335877 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Delete the order using the Bloomberg EMSX connection c ordernum and options structure options options useDefaultEventHandler true options timeOut 200 events deleteOrder c ordernum options events STATUS 0 MESSAGE Order deleted The default event handler processes the events associated with deleting the order deleteOrder returns events as a structure that contains these fields 4 37 A Functions Alphabetical List 4 38 Bloomberg EMSX status Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 7 Manage a Bloomberg EMSX Order and
267. sing ib id orderid ib id 54110686 id contains the next valid order identification number Use this number in createOrder Close the IB Trader Workstation connection close ib Create and Manage an Interactive Brokers Order on page 3 26 orderid Input Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection specified as an IB Trader Workstation connection object created using ibtws Output Arguments id Next valid order identification number scalar Next valid order identification number returned as a scalar More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Interactive Brokers API Reference Guide See Also close createOrder getdata history ibtws timeseries Introduced in R2015a 4 247 A functions Alphabetical List 4 248 orders Request Interactive Brokers open order data Syntax o orders ib o orders ib client o orders ib client eventhandler Description o orders ib requests Interactive Brokers open order data using IB Trader Workstation connection ib for the current client only o orders ib client reques
268. stom Event Handler Functions with Bloomberg EMSX on page 1 28 t timer TimerFcn c eventhandler Period 1 ExecutionMode fixedRate start t tis the MATLAB timer object For details see timer Delete the active shares that are routed but not filled using the Bloomberg EMSX connection C and routenum Set the flag useDefaultEventHandler to false so that eventhandler processes the events associated with deleting the active shares deleteRoute c routenum useDefaultEventHandler false Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs Stop the timer to stop data updates using stop 4 43 A Functions Alphabetical List 4 44 c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Delete Active Shares Using an Options Structure To delete the active shares that are routed but not filled for a Bloomberg EMSX order 1 Create the connection cC using emsx 2 Set up an order and route subscription using orders and routes 3 Create and route an order using createOrderAndRoute For an example showing these activities see Create and Manage a Bloomberg EMSX Route on page 3 16 Define the structure routenum that contains the order s
269. stom event handler function hon Write the code for the custom event handler function For details see Create Functions in Files For a code example of an Interactive Brokers event handler function see ibExampleEventHandler m Run a Custom Event Handler Function You can run the custom event handler function by passing the function name as an input argument into an existing function Specify the custom event handler function name as a string or function handle For details about function handles see Create Function Handle For example suppose you want to retrieve real time data from Interactive Brokers using realtime with the custom event handler function named eventhandler You can use either of these syntaxes to run eventhandler This code assumes a IB Trader Workstation connection ib IB Trader Workstation IContract object ibContract and Interactive Brokers fields f Use a string Writing and Running Custom Event Handler Functions with Interactive Brokers tickerid realtime ib ibContract f eventhandler Or use a function handle tickerid realtime ib ibContract f eventhandler Workflow for Custom Event Handler Function This workflow summarizes the tasks to work with a custom event handler function using Interactive Brokers 1 Write a custom event handler function and save it to a file 2 Create a connection to the IB Trader Workstation using ibtws 3 Run an existing function to recei
270. strat timeOut timeout routeOrderWithStrat useDefaultEventHandler false routeOrderWithStrat c route strat options Description events routeOrderWithStrat c route strat routes a Bloomberg EMSX order with strategies using the Bloomberg EMSX connection C route request route and strategy strat routeOrderWithStrat returns the order sequence number route number and status message using the default event handler events routeOrderWithStrat c route strat timeOut timeout specifies a timeout value timeout for the execution of the default event handler routeOrderWithStrat _ _ useDefaultEventHandler false routes a Bloomberg EMSX order with strategies using any of the input arguments in the previous syntaxes and a custom event handler Write a custom event handler to process the events associated with routing orders This syntax does not have an output argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true __ s routeOrderWithStrat c route strat options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output
271. string to specify another machine Data Types char port IB Trader Workstation port number scalar IB Trader Workstation port number specified as a number designating the connection port of the machine Data Types double Output Arguments ib IB Trader Workstation connection connection object IB Trader Workstation connection returned as an IB Trader Workstation connection object The properties of this object are as follows Property Description Clientid Application identifier where the connection originated Handle Interactive Brokers ActiveX object Host host argument Port port argument 4 189 A Functions Alphabetical List 4 190 The Interactive Brokers API determines these properties More About Tips e ibBuiltInErrMsg appears in the MATLAB workspace Check the status of connection and function execution by displaying the contents of this variable ibBuiltInErrMsg contains messages related to Connection Information resulting from executing functions Errors Workflow for Interactive Brokers on page 2 6 Interactive Brokers API Reference Guide See Also close Introduced in R2013b close close Close IB Trader Workstation connection Syntax close ib Description close ib closes the IB Trader Workstation connection ib Examples Close the IB Trader Workstation Connection Connect to the IB Trader Workstation on the local machi
272. structure Options for custom event handler or timeout value specified as a structure To reuse the settings for specifying a custom event handler or timeout value for the event handler use the options structure 4 113 A Functions Alphabetical List 4 114 Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx getBrokerInfo modifyOrder orders routeOrder routeOrderWithStrat routes start stop Introduced in R2015b routeOrderWithStrat routeOrderWithStrat Route Bloomberg EMSX order with strategies Syntax events routeOrderWithStrat c route strat events routeOrderWithStrat c route
273. t handler or timeout value for the event handler use the options structure Specify using a custom event handler and a timeout value of 500 milliseconds Example options useDefaultEventHandler false options timeOut 500 Data Types struct Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal 3 Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 4 31 A Functions Alphabetical List See Also timer close createOrder delete deleteOrder deleteRoute emsx getBrokerInfo modifyOrder orders routeOrder routes start stop Introduced in R2013a 4 32 deleteOrder deleteOrder Delete Bloomberg EMSX order Syntax events deleteOrder c ordernum events deleteOrder c ordernum timeOut timeout deleteOrder _ useDefaultEventHandler false ___ deleteO0rder c ordernum options Description events deleteOrder c ordernum deletes a Bloomberg EMSX order using the Bloomberg EMSX connection c and order number or structu
274. t property to true 1 enables the X_TRADER API to send order rejection notifications Setting the second property to true 1 enables the X_TRADER API to add order pairs for all order updates to the order tracker list in this order set Setting the third property to ORD_NOTIFY_NORMAL sets the X_TRADER API notification mode for order status events to normal createOrderSet c c OrderSet 1 EnableOrderRejectData c OrderSet 1 EnableOrderUpdateData 1 1 c OrderSet 1 OrderStatusNotifyMode i ORD_NOTIFY_NORMAL Set position limit checks c OrderSet 1 Set NetLimits false Create an Order Using X_TRADER Register event handlers for order status Register event handlers to track events associated with the order status registerevent c OrderSet 1 OnOrderFilled varargin ttorderevent varargin c registerevent c OrderSet 1 OnOrderRejected varargin ttorderevent varargin c registerevent c OrderSet 1 OnOrderSubmitted varargin ttorderevent varargin c registerevent c OrderSet 1 OnOrderDeleted varargin ttorderevent varargin c Enable order submission Open the instrument for trading and enable the X_TRADER API to retrieve market depth information when opening the instrument c OrderSet 1 Open 1 Build an order profile with the existing instrument orderProfile createOrderProfile c Instrument c Instrument 1 Set the customer default property
275. t queue Otherwise events is an empty double When the name value pair argument useDefaultEventHandler or the same field for the structure options is set to false events is an empty double subs Bloomberg EMSX subscription list subscription list object Bloomberg EMSX subscription list returned as a Bloomberg EMSX subscription list object More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler Functions with Bloomberg EMSX on page 1 23 See Also timer close createOrder createOrderAndRoute createOrderAndRouteWithStrat delete deleteOrder deleteRoute emsx getAllFieldMetaData modifyOrder routeOrder routes start stop Introduced in R2013a emsxOrderBlotter emsxOrderBlotter Bloomberg EMSX example order blotter Syntax t subs emsxOrderBlotter c Description t subs emsxOrderBlotter c displays a trader s order information C is the Bloomberg EMSX connection t is the timer object associated with the event handler and subs is the Bloomberg EMSX subscription list Examples Display the Order in an Order Blotter Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Open Bloomberg EMSX order blotter using the Bloomberg EMSX connection c t subs emsxOrderBlotter c
276. tarted 1 20 Subscribe to FIX sessions and set up the FIX Flyer Application Manager Register with the FIX Flyer session Connect the FIX Flyer Application Manager to the FIX Flyer Engine and start the internal receiving thread c SessionID flyer core session SessionID Alpha Beta FIX 4 4 c FlyerApplicationManager registerFIXSession flyer apps FixSessionSubscription c SessionID true 0 c FlyerApplicationManager connect c FlyerApplicationManager start Create a FIX Message Create a FIX message using a structure array fixstruct The data in the structure represents one FIX message This message denotes a sell side transaction for 100 shares of symbol ABC The order type is a previously quoted order The order handling instruction is a private automated execution The order transaction time is the current moment The FIX protocol version is 4 4 fixstruct BeginString 1 1 FIX 4 4 fixstruct CLOrdId 1 1 338 fixstruct Side 1 1 2 fixstruct TransactTime 1 1 datestr now fixstruct OrdType 1 1 D fixstruct Symbol 1 1 ABC fixstruct HandlInst 1 1 1 fixstruct OrderQty 1 1 100 Send a FIX Message Send the FIX message fixstruct using the FIX Flyer Engine connection C status sendMessage c fixstruct status contains a logical zero for a successful message delivery Receive a FIX Message Receive a FIX message response from the FIX Flyer Engine The sample eve
277. tate 2x1 cell Display data in the Timestamp property of cqgTickData cqgTickData Timestamp ans 4 17 2013 2 14 00 PM 4 18 2013 2 14 00 PM Request CQG Timed Bar Data Register an event handler to build and initialize the output data matrix cqgTimedBarData used for storing timed bar data aggEventNames TimedBarsResolved TimedBarsAdded TimedBarsUpdated TimedBarsInserted TimedBarsRemoved for i 1 length aggEventNames registerevent c Handle aggEventNames i varargin cqgintradayeventhandler varargin end Pass additional optional request properties by creating the structure x and setting the optional property x UpdatesEnabled false Request timed bar data for instrument XYZ XYZ for the last fraction of a day using the additional optional request property X instrument XYZ XYZ startdate now 1 enddate now intraday 1 timeseries c instrument startdate enddate intraday x pause 1 MATLAB writes the variable cqgTimedBarData to the Workspace browser Display cqgTimedBarData cqgTimedBarData cqgTimedBarData 3 55 3 Sample Code for Workflows 3 56 1 0e 09 0007 0007 0007 0007 0007 OOO090 cqgTimedBarData returns timed bar data for the specified instrument The columns of cqgTimedBarData display data corresponding to the timestamp open price high price NNNNND 1475 1475 1475 1475 1475 NNNNND 1475 1475
278. tdetails createOrder ibtws orderid Related Examples s Create an Order Using IB Trader Workstation on page 1 7 Create and Manage an Interactive Brokers Order on page 3 26 Request Interactive Brokers Historical Data on page 3 32 Request Interactive Brokers Real Time Data on page 3 35 More About Workflow for Interactive Brokers on page 2 6 Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 3 43 3 Sample Code for Workflows External Websites Interactive Brokers API Reference Guide 3 44 Create CQG Orders Create CQG Orders This example shows how to connect to CQG define the event handlers subscribe to the security define the account handle and submit orders for execution Create the CQG Connection Create the CQG connection object using cqg c cqg Define Event Handlers Register the sample event handler cqgconnectioneventhandler to track events associated with the connection status eventNames CELStarted DataError IsReady DataConnectionStatusChanged GWConnectionStatusChanged GWEnvironmentChanged for i 1 length eventNames registerevent c Handle eventNames i varargin cqgconnectioneventhandler varargin end cqgconnectioneventhandler is assigned to the events in eventNames Set the API configuration properties For example to set the time zone to Eastern Time
279. te Interactive Brokers Orders 00005 2 7 Request Interactive Brokers Informational Data 2 7 Workflow for CQG 0 0 ene 2 8 Workflow for FIX Flyer 0 0 0 0 eae 2 10 Create a FIX Message 0 0 cece eee 2 10 Request Data and Create Orders Using FIX Messages 2 10 Receive a FIX Message 0 0 0 cece eee eee 2 11 Sample Code for Workflows 3 Listen for X_TRADER Price Updates 3 2 Listen for X_TRADER Price Market Depth Updates 3 4 Submit X_TRADER Orders 00000000005 3 8 Create and Manage a Bloomberg EMSX Order 3 12 Create and Manage a Bloomberg EMSX Route 3 16 Manage a Bloomberg EMSX Order and Route 3 21 Create and Manage an Interactive Brokers Order 3 26 Request Interactive Brokers Historical Data 3 32 Request Interactive Brokers Real Time Data 3 35 Create Interactive Brokers Combination Order 3 39 Create CQG Orders 0 0 0 0 cc ees 3 45 Request CQG Historical Data 5 3 50 Request CQG Intraday Tick Data 3 53 Request CQG Real Time Data 3 57 Functions Alphabetical List 4 Getting Started Trading Toolbox Product Description on page 1 2 Installation on page 1 3 lt Trading System Providers on page 1 5 e Create an Order Using IB
280. ted with creating and routing the order createOrderAndRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Modify the Route Define the modroute structure that contains these fields Bloomberg EMSX order sequence number EMSX_SEQUENCE Bloomberg EMSX ticker symbol EMSX_TICKER Bloomberg EMSX number of shares EMSX_AMOUNT 3 23 3 Sample Code for Workflows 3 24 Bloomberg EMSX route identifier EMSX_ROUTE_ID This code modifies the route to 50 shares of IBM for order sequence number 335877 and route identifier 1 Convert the numbers to 32 bit signed integers using int32 modroute EMSX_SEQUENCE int32 335877 modroute EMSX_TICKER IBM modroute EMSX_AMOUNT int32 50 modroute EMSX_ROUTE_ID int32 1 Modify the route using the Bloomberg EMSX connection c and modify route request modroute events modifyRoute c modroute events EMSX_SEQUENCE 0 EMSX_ROUTE_ID 0 MESSAGE Route modified The default event handler processes the events associated with modifying a route modifyRoute returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX route identifier Bloomberg EMSX message Delete the Route Define the structure routenum that contains the order sequence number EMSX_SEQUENCE for the routed order and route number EMSX_ROUTE_ID routenum EMSX_SEQUENCE
281. the CQG connection shutDown c Create and Place a Stop Order To create and place a stop order for shares of an instrument with the CQG Trader Com API using a COQGInstrument object to specify the instrument create the connection c using cqg and startup Register an event handler for tracking events associated with connection status Set up the API configuration properties Then register event handlers for tracking events associated with instrument subscription order and account Subscribe to the instrument and create the CQGInstrument object cqgInst Then set up the account credentials accountHand1le For an example demonstrating these activities see Create CQG Orders on page 3 45 See CQG API Reference Guide to learn more about the event handlers the API configuration properties and the CQGInstrument object To create a stop order you can use the trade price Extract the CQG trade object qtTrade from the previously defined CQGInstrument object cqgInst qtTrade cqgInst get Trade Create a stop order that buys one share of the previously subscribed security cqgInst using the previously defined account credentials accountHandle and qtTrade for the stop price quantity 1 stopprice qtTrade get Price oStop createOrder c cqgInst 3 accountHandle quantity stopprice oStop Place ans OrderChanged The CQGOrder object oStop contains the order The CQG API executes the stop order using the CQG API functi
282. ti Exchange Last Exchange CME Last 45 Return Exchange and Last Price for All Session Instruments Return the exchange and last price fields for all instruments associated with the xtrdr session object X D getData X Exchange Last D Exchange 2x1 cell Last 2x1 cell Listen for X_TRADER Price Updates on page 3 2 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 Input Arguments X X_TRADER connection connection object X_TRADER connection specified as a connection object created using xtrdr S Instrument object instrument Instrument object created by createInstrument or aliases with fields corresponding to valid X_TRADER API options For details see the Trading Technologies X_TRADER API Programming Tutorial or X_TRADER API Class Reference Example x Instrument 1 F Fields for the instrument object string cell array of strings 4 155 A Functions Alphabetical List Fields for the instrument object or aliases S F without a corresponding S are fields for all instruments associated with the xtrdr session object X Example Exchange Last Data Types char cell Output Arguments D X_TRADER data strings X_TRADER data returned as strings in MATLAB and missing data is returned as NaN More About Workflows for Trading Technologies X TRADER on page 2 4 X_TRAD
283. tion Order Create the IB Trader Workstation IContract object orderContract for the combination order Create an IContract object with these property values Google symbol Combination order type BAG Aggregate exchange USD currency IB Trader Workstation IComboLegList object comboLegs orderContract ib Handle createContract orderContract symbol GOOG orderContract secType BAG orderContract exchange SMART orderContract currency USD orderContract comboLegs comboLegs Il Create the IB Trader Workstation IOrder object ibOrder Here the combination order is a market order to buy one combination of the two legs ibOrder ib Handle createOrder ibOrder action BUY ibOrder totalQuantity 1 ibOrder orderType MKT Request the next valid order identification number id using orderid Create Interactive Brokers Combination Order id orderid ib Execute the combination order ibOrder using these arguments IB Trader Workstation connection ib Combination order IContract object orderContract IB Trader Workstation IOrder object ibOrder Order identifier id Sample event handler ibExampleEventHandler Q l createOrder ib orderContract ibOrder id ibExampleEventHandler 768413 00 d returns the unique order identifier for this combination order Close the Connection Close the IB Trader Workstation connection ib close ib See Also close contrac
284. tion expiration dates This example creates a buy order on a calendar spread for Google For details about IContract objects IComboLegList objects and combination orders see Interactive Brokers API Reference Guide This example uses the sample event handler function ibExampleEventHandler to handle events associated with creating a combination order Use this event handler or write a custom event handler function For details see Writing and Running Custom Event Handler Functions with Interactive Brokers on page 1 26 To access the code for this example see IBCombinationOrder m Connect to the IB Trader Workstation Connect to the IB Trader Workstation and create connection ib using the local host and port number 7496 ib ibtws 7496 MATLAB returns ib as the connection to the IB Trader Workstation with the Interactive Brokers ActiveX object the local host and the port number that you choose Create IB Trader Workstation IContract Objects Create the IB Trader Workstation IContract object ibContract1 Here this object describes the first call option in the calendar spread Create an IContract object with these property values Google symbol Stock option Expiry date is August 2014 Strike price is 535 00 Call option Number of shares is 100 3 39 3 Sample Code for Workflows Aggregate exchange USD currency ibContract1 ib Handle createContract ibContract1 symbol GOOG
285. tity acquiring for or through the federal government and shall supersede any conflicting contractual terms or conditions If this License fails to meet the government s needs or is inconsistent in any respect with federal procurement law the government agrees to return the Program and Documentation unused to The MathWorks Inc Trademarks MATLAB and Simulink are registered trademarks of The MathWorks Inc See www mathworks com trademarks for a list of additional trademarks Other product or brand names may be trademarks or registered trademarks of their respective holders Patents MathWorks products are protected by one or more U S patents Please see www mathworks com patents for more information Revision History March 2013 Online only New for Version 1 0 Release 2013a September 2013 Online only Revised for Version 2 0 Release 2013b March 2014 Online only Revised for Version 2 1 Release 2014a October 2014 Online only Revised for Version 2 1 1 Release 2014b March 2015 Online only Revised for Version 2 2 Release 2015a September 2015 Online only Revised for Version 2 2 1 Release 2015b Contents Getting Started Trading Toolbox Product Description 1 2 Key Features sera kde Sek deed 4 ba wele Mae acd Sanaa eA 1 2 Installations reee ERR r EEA ERR AEEA 1 3 BlOOmib OF 8 rieo ga eg Ste sts lata Ne a aE a ea Boke 1 3 CQ sas er AE AE aes Net Ean ny A inte ook oly Maite on E 1 3 FIX Flyet oe xs fae
286. to signify the instrument for the transaction createOrder returns the Interactive Brokers order data d containing data about the completed order d createOrder ib ibContract ibOrder id eventhandler creates an IB Trader Workstation order using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Create an Order To create an order set up the IB Trader Workstation connection ib using ibtws Create an IB Trader Workstation IContract object ipbContract An IContract object is an Interactive Brokers object for containing the data about a security to process transactions Then create an IB Trader Workstation IOrder object ibOrder An IOrder object is an Interactive Brokers object that contains the order conditions to place an order For an example showing how to create these objects see Create and Manage an Interactive Brokers Order on page 3 26 For details about creating these objects see Interactive Brokers API Reference Guide 4 193 A Functions Alphabetical List Obtain the next valid order identification number id using ib id ll orderid ib id 54110686 Execute the order using ib ibContract ibOrder and id This code assumes a buy market order for two shares d Il createOrder ib ibContract ibOrder id d STATUS Filled FILLED 2 REMAINING 0 AVG_FILL_PRICE 787 5600 PERM_ID 1979798454 PAREN
287. top the timer to stop data updates using stop c Session unsubscribe osubs c Session unsubscribe rsubs stop t Delete the timer if you are done processing data updates using delete delete t Close the Bloomberg EMSX connection close c Route an Order Using an Options Structure To route a Bloomberg EMSX order with strategies create the connection C using emsx set up the order subscription using orders and create the order using createOrder For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Set up the route subscription using routes Define the route request structure route Convert the numbers to 32 bit signed integers using int32 This code specifies to route 100 shares of IBM to the broker BMTB using any hand instruction and the order number 335877 route EMSX_SEQUENCE int32 335877 route EMSX_TICKER IBM route EMSX_AMOUNT int32 100 4 119 A functions Alphabetical List 4 120 route EMSX_BROKER BMTB route EMSX_HAND_INSTRUCTION ANY Create the order strategies structure Strat using the strategy SSP Convert the field indicators to a 32 bit signed integer using int32 strat EMSX_STRATEGY_NAME SSP strat EMSX_STRATEGY_FIELD_INDICATORS int32 0 0 0 strat EMSX_STRATEGY_FIELDS 09 30 00 14 30 00 50 Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the fie
288. tract ibContract contains the stock symbol security type exchange and currency for security XYZ Create and Manage an Interactive Brokers Order Create the IB Trader Workstation IOrder object ibOrder for a buy market order for two shares ibOrder ib Handle createOrder ibOrder action BUY ibOrder totalQuantity 2 ibOrder orderType MKT ibOrder Interface Tws_ ActiveX_Control_module I0Order ibOrder contains the action total quantity and order type Create the Interactive Brokers Order Obtain the next valid order identification number using IB Trader Workstation connection ib id orderid ib Execute the buy market order for two shares using the unique order identifier id and sample event handler ibExampleOrderEventHandler createOrder ib ibContract ibOrder id ibExampleOrderEventHandler MATLAB displays order information in the IB Order Blotter The IB Order Blotter shows the open order and the filled order 3 29 3 Sample Code for Workflows 3 30 4 IB Order Blotter tojta Status Filled Remaining Avg Fill Price Id ParentId Last Fill Price Client Id Why Held Submitted 380774589 0 0 Filled 2 0 7 6300 380774590 0 7 6300 0 Cancel the Interactive Brokers Order ib Handle cancelOrder id After canceling the existing order create a new order by modifying the IB Trader Workstation IOrder object ibOrder Then create the order by executing createOrder Cancel all
289. ts Interactive Brokers open order data using IB Trader Workstation connection ib and a client flag client denotes requesting data from the current client or all clients o orders ib client eventhandler requests Interactive Brokers open order data using an event handler function eventhandler Use the sample event handler ibExampleEventHandler or write a custom event handler function Examples Request Open Order Data Create the IB Trader Workstation connection ib on the local machine using port number 7496 ib ibtws 7496 Create the IB Trader Workstation IContract object ibContract Here this object describes a security with these property values Google symbol Stock security type orders Aggregate exchange USD currency ibContract ib Handle createContract ibContract symbol GOOG ibContract secType STK ibContract exchange SMART ibContract currency USD Create the IB Trader Workstation IOrder object ibOrder Here this object describes a limit order to sell two shares with a limit price of 590 ibOrder ib Handle createOrder ibOrder action SELL ibOrder totalQuantity 2 ibOrder orderType LMT ibOrder 1lmtPrice 590 For details about the IContract and IOrder objects see Interactive Brokers API Reference Guide Create a unique order identifier id id orderid ib Execute the order using IB Trader Workstation connection ib IB Trader Workstation IContract
290. tus changes To use a string for the security subscribe to the security EZC as shown above Then create a market order that buys one share of the security EZC using the defined account credentials accountHandl1e cqgInstrumentName EZC quantity 1 oMarket createOrder c cqgInstrumentName 1 accountHandle quantity oMarket Place ans 3 47 3 Sample Code for Workflows 3 48 OrderChanged The CQGOrder object oMarket contains the order The CQG API executes the market order using the CQG API function Place After execution the order status changes To create a limit order you can use the bid price Extract the CQG bid object qtBid from the previously defined CQGInstrument object cqgInst For details about the CQGInstrument object see CQG API Reference Guide qtBid cqgInst get Bid Create a limit order that buys one share of the previously subscribed security cqgInst using the previously defined account credentials accountHand1le and qtBid for the limit price quantity 1 limitprice qtBid get Price oLimit createOrder c cqgInst 2 accountHandle quantity limitprice oLimit Place ans OrderChanged The CQGOrder object oLimit contains the order The CQG API executes the limit order using the CQG API function Place After execution the order status changes To create a stop order you can use the trade price Extract the CQG trade object qtTrade from the previously defined CQGInstrume
291. uantity previous last quantity and a change in prices Listen for this event data X InstrNotify 1 UpdateFilter Last LastQty LastQty Change X Instrument 1 Open 0 Listen for X_TRADER Price Updates The last command tells X_TRADER to start monitoring the attached instruments using the specified event settings Close the Connection close X See Also close createInstrument createNotifier xtrdr Related Examples Create an Order Using X_ TRADER on page 1 16 Listen for X_TRADER Price Market Depth Updates on page 3 4 Submit X_TRADER Orders on page 3 8 More About Workflows for Trading Technologies X_TRADER on page 2 4 3 3 3 Sample Code for Workflows Listen for X_TRADER Price Market Depth Updates This example shows how to connect to X_TRADER and turn on event handling for level two market data for example bid and ask orders in the market for an instrument and then create a figure window to display the depth data Connect to X_TRADER X xtrdr Create an Event Notifier Create an event notifier and enable depth updates The event notifier is the X_TRADER mechanism lets you define MATLAB functions to use as callbacks for specific events createNotifier X X InstrNotify 1 EnableDepthUpdates 1 Create an Instrument createInstrument X Exchange CME Product 2F ProdType Future Contract Aug13 Alias PriceInstrumentDepthUpdate
292. ubmit orders To monitor market price information 1 Connect to Trading Technologies X_TRADER using xtrdr 2 Create an event notifier using createNotifier 3 Create an instrument and attach it to the notifier using createInstrument Optionally use getData to return information on the instrument that you have created 4 Close the Trading Technologies X_TRADER connection using close To submit orders to X_TRADER 1 Connect to Trading Technologies X_TRADER using xtrdr 2 Create an event notifier using createNotifier 3 Create an instrument and attach it to the notifier using createInstrument Optionally use getData to return information on the instrument that you have created 4 Create an order set using createOrderSet to define the level of the order status events and event handlers for orders that will be submitted to X_TRADER 5 Define the order using createOrderProfile An order profile contains the settings that define an individual order to be submitted 6 Route the order for execution using the OrderSet object created by createOrderSet in step 4 7 Close the Trading Technologies X_TRADER connection using close To monitor market price information and respond to market changes by automatically submitting orders to X_TRADER 1 Connect to Trading Technologies X_TRADER using xtrdr 2 Create an event notifier using createNotifier 3 Create an instrument and attach it to the notifier using createInstrument Use getData to retu
293. ument timeOut and set it to 200 milliseconds fields EMSX_BROKER EMSX_AMOUNT EMSX_FILLED events subs orders c fields timeOut 200 events orders MSG_TYPE E MSG_SUB_TYPE 0O EVENT_STATUS 4 subs com bloomberglp blpapi SubscriptionList 4bc3dc78 events contains fields for the events currently in the event queue Subs contains the Bloomberg EMSX subscription list object Unsubscribe from order events using the Bloomberg EMSX subscription list object subs c Session unsubscribe subs Close the Bloomberg EMSX connection close c Subscribe to Order Events Using the Options Structure Create the Bloomberg EMSX connection c c emsx blp emapisvc_beta Create a structure options To use the default event handler set the field useDefaultEventHandler to true Set the field timeOut to 200 milliseconds Subscribe to events for Bloomberg EMSX orders using the Bloomberg EMSX connection c Bloomberg EMSX field list fields and options structure options options timeOut 200 options useDefaultEventHandler true fields EMSX_BROKER EMSX_AMOUNT EMSX_FILLED events subs orders c fields options events MSG_TYPE E MSG_SUB_ TYPE 0 EVENT STATUS 4 4 85 A Functions Alphabetical List 4 86 subs com bloomberglp blpapi SubscriptionList 4bc3dc78 events contains fields for the events currently in the event queue Subs contains the Bloomberg
294. ut argument because the custom event handler processes the contents of the event queue If you want to use the default event handler instead set the flag useDefaultEventHandler to true and use the events output argument By default the flag useDefaultEventHandler is set to true createOrder c order options uses the options structure to customize the output which is useful to preconfigure and save your options for repeated use The available options structure fields are timeOut and useDefaultEventHandler Use the events output argument when useDefaultEventHand1ler is set to true and omit this output argument when useDefaultEventHandler is set to false 4 7 A functions Alphabetical List Examples Create an Order Using the Default Event Handler To create a Bloomberg EMSX order create the connection C using emsx and set up the order subscription using orders For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 3 12 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_INSTRUCTION ANY
295. uting structure which contains the order number error code and error message for the orders that failed to route Bloomberg EMSX message Unsubscribe from order and route events using the Bloomberg EMSX subscription list objects oSubs and rsubs This code assumes that orders creates oSubs and routes creates rsubs 4 111 A Functions Alphabetical List 4 112 c Session unsubscribe osubs c Session unsubscribe rsubs Close the Bloomberg EMSX connection close c Create and Manage a Bloomberg EMSX Order on page 3 12 Create and Manage a Bloomberg EMSX Route on page 3 16 Manage a Bloomberg EMSX Order and Route on page 3 21 Input Arguments c Bloomberg EMSX service connection connection object Bloomberg EMSX service connection specified as a connection object created using emsx route Route request structure Route request specified as a structure containing these fields Convert the numbers to 32 bit signed integers using int32 EMSX_SEQUENCE must denote an existing order sequence number Field Description EMSX_SEQUENCE Bloomberg EMSX order sequence number EMSX_TICKER Bloomberg EMSxX ticker symbol EMSX_AMOUNT Bloomberg EMSX number of shares EMSX_BROKER Bloomberg EMSX broker name EMSX_HAND_INSTRUCTION Bloomberg EMSX hand instruction EMSX_TIF Bloomberg EMSX time in force EMSX_ORDER_TYPE Bloomberg EMSX order type Example route EMSX_SEQUENCE int
296. value to 200 milliseconds events createOrder c order timeOut 200 events EMSX_SEQUENCE 354646 MESSAGE Order created The default event handler processes the events associated with creating the order createOrder returns events as a structure that contains these fields Bloomberg EMSX order number Bloomberg EMSX message Unsubscribe from order events using the Bloomberg EMSX subscription list object subs This code assumes that orders creates subs c Session unsubscribe subs Close the Bloomberg EMSX connection A functions Alphabetical List 4 10 close c Create an Order Using a Custom Event Handler To create a Bloomberg EMSX order create the Bloomberg EMSX connection c using emsx and set up the order subscription using orders For an example showing these activities see Create and Manage a Bloomberg EMSX Order on page 38 12 Create the order request structure order to define the order parameters This code creates a buy market order for 100 shares of IBM This code uses the broker BB with the time in force set to DAY and any hand instruction Convert the number of shares to a 32 bit signed integer using int32 order EMSX_TICKER IBM order EMSX_AMOUNT int32 100 order EMSX_ORDER_TYPE MKT order EMSX_BROKER BB order EMSX_TIF DAY order EMSX_HAND_ INSTRUCTION ANY order EMSX_SIDE BUY Suppose you create a custom event handler function called eventhandler w
297. ve Brokers Combination Order on page 3 39 Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 3 Sample Code for Workflows Listen for X_TRADER Price Updates This example shows how to connect to X_TRADER and listen for price update event data Connect to X_TRADER X xtrdr Create an Event Notifier The event notifier is the X_TRADER mechanism that lets you define MATLAB functions to use as callbacks for specific events createNotifier X Create an Instrument Create an instrument and attach it to the notifier createInstrument X Exchange CME Product 2F Prodlype Future Gontract Augl3 Alias PriceInstrumenti1 X InstrNotify 1 AttachInstrument X Instrument 1 Define Events Assign callbacks for validating or invalidating an instrument and for handling data updates for a previously validated instrument registerevent X InstrNotify 1 OnNotifyFound varargin ttinstrumentfound varargin registerevent X InstrNotify 1 OnNotifyNotFound varargin ttinstrumentnotfound varargin registerevent X InstrNotify 1 OnNotifyUpdate varargin ttinstrumentupdate varargin Monitor Events Set the update filter to monitor the desired fields In this example events are monitored for updates to last price last q
298. ve data updates Use the custom event handler function as an input argument Caution To run default event handler and sample event handler functions you must run one event handler function at a time After you run one event handler close the IB Trader Workstation connection Then create another connection to run a different event handler with the same existing function Otherwise MATLAB assigns multiple existing functions to events and errors occur 4 Close the connection to the IB Trader Workstation using close See Also close ibtws realtime More About Create Functions in Files Create Function Handle 1 27 Workflow Models Workflow for Bloomberg EMSX on page 2 2 Workflows for Trading Technologies X_TRADER on page 2 4 Workflow for Interactive Brokers on page 2 6 Workflow for CQG on page 2 8 Workflow for FIX Flyer on page 2 10 2 Workflow Models Workflow for Bloomberg EMSX The workflow for Bloomberg EMSxX is versatile with many options for alternate flows to create route and manage the status of an open order until it is filled 2 2 1 2 Connect to Bloomberg EMSX using emsx Set up a subscription for orders and routes to obtain events on subsequent requests using orders and routes Create a Bloomberg EMSX order Options in the flow of creating an order are e Create an order using createOrder Route an order using routeOrder e Route
299. vent handler 500 milliseconds default nonnegative integer Timeout value for event handler for the Bloomberg EMSX service specified as the comma separated pair consisting of timeOut and a nonnegative integer in units of milliseconds Example timeOut 200 4 129 A functions Alphabetical List 4 130 Data Types double Output Arguments events Event queue contents double structure Event queue contents returned as a double or structure If the event queue contains events events is a structure containing the current contents of the event queue Otherwise events is an empty double When the name value pair argument useDefaultEventHandler or the same field for the structure options is set to false events is an empty double subs Bloomberg EMSX subscription list subscription list object Bloomberg EMSX subscription list returned as a Bloomberg EMSX subscription list object More About Tips For details about Bloomberg EMSX see the EMSX API Programmer s Guide using the WAPI lt GO gt option from the Bloomberg terminal Suppose you create a custom event handler function called eventhandler with input argument c Run eventhandler using this code t timer TimerFecn c eventhandler Period 1 ExecutionMode fixedRate t is the MATLAB timer object For details see timer Workflow for Bloomberg EMSX on page 2 2 Writing and Running Custom Event Handler
300. venthandler varargin end Subscribe to the instrument Subscribe to a security tied to the EURIBOR realtime c F US IE pause 2 Create the CQGInstrument object To use the instrument for creating an order import the instrument name cqgInstrumentName into the current MATLAB workspace Then create the CQGInstrument object cqgInst cqgInstrumentName evalin base cqgInstrument cqgInst c Handle Instruments Item cqgInstrumentName 1 11 1 Getting Started 1 12 Set up account credentials Set the CQG flags to enable account information retrieval c Handle set AccountSubscriptionLevel aslNone c Handle set AccountSubscriptionLevel aslAccountUpdatesAndOrders pause 2 accountHandle c Handle Accounts ItemByIndex 0 Create the market order Create a market order that buys one share of the subscribed security cqgInst using the account credentials accountHandl1e orderType 1 Market order flag quantity 1 Positive quantity is Buy negative is Sell oMarket createOrder c cqgInst orderType accountHandle quantity oMarket Place Close the connection close c See Also close cqg createOrder realtime startUp Related Examples Create CQG Orders on page 3 45 Request CQG Historical Data on page 3 50 Request CQG Intraday Tick Data on page 3 53 Request CQG Real Time Data on page 3 57 More About Workflow for CQG on page
301. ween the tag and value pairs is a SOH character This character is not printable and has a hexadecimal value of 0x01 Input Arguments fixtable FIX message table FIX message specified as table The table variables correspond to FIX tag names Each row contains the values you specify for the FIX message Specify the values for each variable as a cell array of strings Example fixtable table FIX 4 4 FIX 4 4 T 338 339 p 2i 2 bigs aie datestr now datestr now D D ABC ABC fe a A 100 OO pe ai VariableNames BeginString CLOrdId Side TransactTime OrdType Symbol HandlInst OrderQty Data Types table Output Arguments fixstr FIX message cell array FIX message returned as a cell array of one or more converted raw FIX message strings The number of strings depends on the number of messages that you specify in the input argument 4 293 A Functions Alphabetical List 4 294 More About Workflow for FIX Flyer on page 2 10 FIX Trading Community See Also fix2struct fix2table fixflyer struct2fix Introduced in R2015b
302. with Bloomberg EMSX In this section Write a Custom Event Handler Function on page 1 23 Run a Custom Event Handler Function on page 1 23 Workflow for Custom Event Handler Function on page 1 24 Write a Custom Event Handler Function You can process events related to any Bloomberg EMSX orders and routes by writing a custom event handler function to use with Trading Toolbox For example you can plot the changes in the number of shares routed Follow these tasks to write a custom event handler 1 Choose the events that you want to process monitor or evaluate 2 Decide how the custom event handler function processes these events 3 Determine the input and output arguments for the custom event handler function 4 Write the code for the custom event handler function For details see Create Functions in Files For a code example of an event handler function see the function processEventToBlotter in the emsxOrderBlotter m file Run a Custom Event Handler Function You can run the custom event handler function by using timer Specify the custom event handler function name as a function handle and pass this function handle as an input argument to timer For details about function handles see Create Function Handle For example suppose you want to create an order using createOrderAndRoute with the custom event handler function named eventhandler This code assumes a Bloomberg EMSX connection c
Download Pdf Manuals
Related Search
Related Contents
Joseph Ciaglia, Barbara London, John Upton, Ken Kobre and Betsy Harman/Kardon MS 150/230 docking speaker Descargar PDF Coleman Cable L1323 Manual de puesta en marcha de atornilladores, taladros y radiales. 2-La Préhistoire Goodman Mfg . Co. LP. Furnace Multi-Position, Two-Stage/Variable-Speed Gas Furnace User's Manual Copyright © All rights reserved.
Failed to retrieve file