MATLAB Trading Toolbox™ Users Guide (The MathWorks, Inc.) (z-library.sk, 1lib.sk, z-lib.sk)
,
Matlab
No Description
7
Views
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Trading Toolbox™ User's Guide R2020a
Page
2
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. 1 Apple Hill Drive Natick, MA 01760-2098 Trading Toolbox™ User's Guide © COPYRIGHT 2013–2020 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 entity 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) March 2016 Online only Revised for Version 3.0 (Release 2016a) September 2016 Online only Revised for Version 3.1 (Release 2016b) March 2017 Online only Revised for Version 3.2 (Release 2017a) September 2017 Online only Revised for Version 3.3 (Release 2017b) March 2018 Online only Revised for Version 3.4 (Release 2018a) September 2018 Online only Revised for Version 3.5 (Release 2018b) March 2019 Online only Revised for Version 3.5.1 (Release 2019a) September 2019 Online only Revised for Version 3.6 (Release 2019b) March 2020 Online only Revised for Version 3.6.1 (Release 2020a)
Page
3
Getting Started 1 Trading Toolbox Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 Bloomberg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 CQG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 FIX Flyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 Interactive Brokers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3 Trading Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 Trading System Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Supported Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Connection Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Platform Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Create an Order Using IB Trader Workstation . . . . . . . . . . . . . . . . . . . . . . 1-7 Create an Order Using CQG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10 Create an Order Using Bloomberg EMSX . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Create an Order Using X_TRADER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14 Create an Order Using FIX Flyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17 Writing and Running Custom Event Handler Functions with Bloomberg EMSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21 Write a Custom Event Handler Function . . . . . . . . . . . . . . . . . . . . . . . . . 1-21 Run a Custom Event Handler Function . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21 Workflow for Custom Event Handler Function . . . . . . . . . . . . . . . . . . . . . 1-22 Writing and Running Custom Event Handler Functions with Interactive Brokers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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-23 iii Contents
Page
4
Workflow Models 2 Workflow for Bloomberg EMSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 Workflows for Trading Technologies X_TRADER . . . . . . . . . . . . . . . . . . . . . 2-4 Workflow for Interactive Brokers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 Request Interactive Brokers Market Data . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 Create Interactive Brokers Orders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 Request Interactive Brokers Informational Data . . . . . . . . . . . . . . . . . . . . 2-7 Workflow for CQG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 Transaction Cost Analysis 3 Analyze Trading Execution Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 Post-Trade Analysis Metrics Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Implementation Shortfall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Alpha Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Benchmark Costs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Broker Value Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Z-Score . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Kissell Research Group Data Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 Basket Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 BrokerNames Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 TradeData Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 TradeDataCurrent and TradeDataHistorical Variables . . . . . . . . . . . . . . . . 3-9 PortfolioData Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9 PostTradeData Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10 TradeDataBackTest Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12 TradeDataStressTest Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12 TradeDataPortOpt Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13 TradeDataTradeOpt Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14 CovarianceData Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15 CovarianceTradeOpt Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15 Conduct Sensitivity Analysis to Estimate Trading Costs . . . . . . . . . . . . . 3-17 Estimate Portfolio Liquidation Costs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20 Optimize Percentage of Volume Trading Strategy . . . . . . . . . . . . . . . . . . 3-23 Optimize Trade Time Trading Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26 Optimize Trade Schedule Trading Strategy . . . . . . . . . . . . . . . . . . . . . . . . 3-29 Estimate Trading Costs for Collection of Stocks . . . . . . . . . . . . . . . . . . . . 3-33 iv Contents
Page
5
Conduct Back Test on Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-35 Conduct Stress Test on Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38 Liquidate Dollar Value from Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-43 Optimize Long Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-48 Determine Buy-Sell Imbalance Using Cost Index . . . . . . . . . . . . . . . . . . . 3-51 Rank Broker Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-55 Optimize Trade Schedule Trading Strategy for Basket . . . . . . . . . . . . . . 3-60 Create Basket Summary and Efficient Trading Frontier . . . . . . . . . . . . . 3-64 Sample Code for Workflows 4 Listen for X_TRADER Price Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Listen for X_TRADER Price Market Depth Updates . . . . . . . . . . . . . . . . . . 4-4 Submit X_TRADER Orders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Create and Manage a Bloomberg EMSX Order . . . . . . . . . . . . . . . . . . . . . 4-10 Create and Manage a Bloomberg EMSX Route . . . . . . . . . . . . . . . . . . . . . 4-14 Manage a Bloomberg EMSX Order and Route . . . . . . . . . . . . . . . . . . . . . 4-18 Create and Manage an Interactive Brokers Order . . . . . . . . . . . . . . . . . . 4-22 Request Interactive Brokers Historical Data . . . . . . . . . . . . . . . . . . . . . . 4-27 Request Interactive Brokers Real-Time Data . . . . . . . . . . . . . . . . . . . . . . 4-29 Create Interactive Brokers Combination Order . . . . . . . . . . . . . . . . . . . . 4-32 Create CQG Orders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37 Request CQG Historical Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-41 Request CQG Intraday Tick Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-44 Request CQG Real-Time Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-47 v
Page
6
WDS Topics 5 Decide to Buy Shares Using Current and Historical WDS Data . . . . . . . . 5-2 Create Order Using Real-Time Snapshot WDS Data . . . . . . . . . . . . . . . . . . 5-4 Functions 6 vi Contents
Page
7
Getting Started • “Trading Toolbox Product Description” on page 1-2 • “Installation” on page 1-3 • “Trading System Providers” on page 1-5 • “Create an Order Using IB Trader Workstation” on page 1-7 • “Create an Order Using CQG” on page 1-10 • “Create an Order Using Bloomberg EMSX” on page 1-12 • “Create an Order Using X_TRADER” on page 1-14 • “Create an Order Using FIX Flyer” on page 1-17 • “Writing and Running Custom Event Handler Functions with Bloomberg EMSX” on page 1-21 • “Writing and Running Custom Event Handler Functions with Interactive Brokers” on page 1-23 1
Page
8
Trading Toolbox Product Description Access prices, analyze transaction costs, and send orders to trading systems Trading Toolbox provides functions for analyzing transaction costs, 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 or proprietary trade execution platforms. With Trading Toolbox you can analyze and estimate transaction costs before placing an order, as well as attribute costs post-trade. You can analyze transaction costs associated with market impact, timing, liquidity, and price appreciation, and use cost curves to minimize transaction costs for single assets or for a portfolio of assets. Trading Toolbox lets you access real-time streams of tradable instrument data, including quotes, volumes, trades, market depth, and instrument metadata. You can define order types and specify order routing and filling procedures. Key Features • Market impact modeling and cost curve generation using Kissell Research Group models • Trading cost, sensitivity, and post-trade execution analysis • Access to current, intraday, event-based, and real-time tradable instrument data • Data filtering by instrument and exchange • Definable order types and execution instructions • Access to FIX-compliant trading systems using FIX Flyer™ Engine • Support for Bloomberg® EMSX, Trading Technologies® X_TRADER®, CQG® Integrated Client, and Interactive Brokers® TWS 1 Getting Started 1-2
Page
9
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 To install Bloomberg EMSX from Bloomberg L.P., find the latest installation files at https:// www.bloomberg.com. You need a Bloomberg license to install and run Bloomberg EMSX. CQG To install CQG, find the latest installation files at https://www.cqg.com. You need a CQG license to install and run CQG. The Trading Toolbox no longer supports connection using a 32-bit version of MATLAB. To configure CQG to work with a 64-bit version of MATLAB, see https://www.mathworks.com/matlabcentral/ answers/223461-how-can-i-set-up-a-cqg-connection-using-the-trading-toolbox-with-64-bit-version-of- matlab. FIX Flyer 1 Install FIX Flyer. Find the latest installation files using the Files Provided by FIX Flyer. 2 Download the zip file that contains the installation JAR files. Unzip the file. 3 Search the folders for the JAR file fix-flyer.jar and the folder named core. The JAR file is located in the folder where FIX Flyer is installed. The JAR file points to the folder core that contains the other required JAR files. 4 Add the JAR file fix-flyer.jar to the static Java® class path. Edit the javaclasspath.txt file and enter the path to the file. For example, ..\FIXFlyer\fix-flyer-5.0.1\devkit\lib \fix-flyer.jar. This file path assumes an installation of FIX Flyer version 5.0.1. If you are running Linux® or Mac, the JAR file path has a different format. For example, / FIXFlyer/fix-flyer-5.0.1/devkit/lib/fix-flyer.jar. For details about modifying the static Java class path, see “Java Class Path” (MATLAB). You need a FIX Flyer license to install and run FIX Flyer. Interactive Brokers 1 Download and install the IB Trader Workstation(SM) 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 software. Find the latest installation files at https://interactivebrokers.github.io/. Installation 1-3
Page
10
3 Configure IB Trader Workstation to enable connections. Follow these steps in IB Trader Workstation: a Select File > Global Configuration under Application Settings. b Select API > Settings on the left side. c Select Enable ActiveX and Socket Clients on the right side. d Click Apply, then OK. e Restart MATLAB and connect to IB Trader Workstation. You need an Interactive Brokers license to install and run Interactive Brokers. Trading Technologies To install Trading Technologies, find the latest installation files at https:// www.tradingtechnologies.com. You need a Trading Technologies license to install and run Trading Technologies. See Also cqg | emsx | fixflyer | ibtws | xtrdr Related Examples • “Create an Order Using Bloomberg EMSX” on page 1-12 • “Create an Order Using CQG” on page 1-10 • “Create an Order Using FIX Flyer” on page 1-17 • “Create an Order Using IB Trader Workstation” on page 1-7 • “Create an Order Using X_TRADER” on page 1-14 1 Getting Started 1-4
Page
11
Trading System Providers In this section... “Supported Providers” on page 1-5 “Connection Requirements” on page 1-5 “Platform Requirements” on page 1-6 Trading Toolbox enables you to connect to various trading system providers. To create a connection, ensure that you satisfy the license, connection, and platform requirements. Supported Providers This toolbox supports connections to financial trading systems provided by the following corporations: • Bloomberg EMSX from Bloomberg L.P. (https://www.bloomberg.com) Note Only the Bloomberg Desktop API is supported. • CQG (https://www.cqg.com) • FIX Flyer (https://www.fixflyer.com/) • IB Trader Workstation from Interactive Brokers (https://www.interactivebrokers.com) Note IB Trader Workstation versions 9.69 and 9.7 and later are supported. • X_TRADER from Trading Technologies (https://www.tradingtechnologies.com) • Wind Data Feed Services (WDS) from The Wind Information Co., Ltd. (http:// www.wind.com.cn/en/product/Wind.DataFeed.html) 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 the Bloomberg Desktop software license for the host on which Trading Toolbox and MATLAB software are running. • CQG • FIX Flyer • Interactive Brokers IB Trader Workstation • Trading Technologies X_TRADER • WDS You must have a valid license for required client software on your machine. Trading System Providers 1-5
Page
12
For more information about how to obtain required software, contact your trading system sales representative. Platform Requirements The Trading Toolbox supports 64-bit Windows® only. However, transaction cost analysis from the Kissell Research Group supports all platforms. These data service providers work only with the Windows platform: • Bloomberg EMSX • CQG • Interactive Brokers • Trading Technologies X_TRADER • WDS 1 Getting Started 1-6
Page
13
Create an Order Using IB Trader Workstation Create a connection to the IB Trader Workstation℠ and create a market order based on historical and current data for a security. You can also create orders for a different instrument, such as a futures contract. Before creating the connection, you must enter your credentials and run the IB Trader Workstation℠ application. To run this example, you must have the Financial Toolbox™ installed. Run IB Trader Workstation℠ Application Ensure the IB Trader Workstation℠ application is running, and that API connections are enabled. Follow these steps in IB Trader Workstation℠. 1 To open the Trader Workstation Configuration (Simulated Trading) dialog box, select File > Global Configuration. 2 Select API > Settings. 3 Ensure that the Enable ActiveX and Socket Clients check box is selected. Connect to 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 ibContract. This object specifies the security. Retrieve data for Microsoft® stock. Specifying SMART as the exchange lets Interactive Brokers® determine which venue to use for data retrieval. To clarify any ambiguity, set the primary exchange for the destination to NASDAQ. To retrieve dollar-denominated stock, set the currency type to USD. Setting currency type 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.primaryExchange = 'NASDAQ'; ibContract.currency = 'USD'; Define the date range for the last 20 business days, excluding today. To calculate the appropriate start and end dates, this code uses the daysadd function from Financial Toolbox™. bizDayConvention = 13; % i.e. BUS/252 currentdate = today; startDate = daysadd(currentdate,-20,bizDayConvention); endDate = daysadd(currentdate,-1,bizDayConvention); Retrieve historical data for the last 20 business days. Create an Order Using IB Trader Workstation 1-7
Page
14
histTradeData = history(ib,ibContract,startDate,endDate); 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, last traded prices return by default. Retrieve current price data from the contract. currentData = getdata(ib,ibContract) currentData = struct with fields: LAST_PRICE: 62.8500 LAST_SIZE: 1 VOLUME: 41273 BID_PRICE: 62.8400 BID_SIZE: 17 ASK_PRICE: 62.8600 ASK_SIZE: 12 Create Trade Market Order The IB Trader Workstation℠ supports various order types, including basic types such as limit orders, stop orders, and market orders. Create the IB Trader Workstation℠ Iorder object ibMktOrder. This object specifies the order. To buy shares, specify the action BUY. To specify buying 100 shares, set totalQuantity to 100. To create a market order, specify the order type as MKT. ibMktOrder = ib.Handle.createOrder; ibMktOrder.action = 'BUY'; ibMktOrder.totalQuantity = 100; ibMktOrder.orderType = 'MKT'; Set a unique order identifier and send the order to Interactive Brokers®. id = orderid(ib); result = createOrder(ib,ibContract,ibMktOrder,id) result = struct with fields: STATUS: 'Submitted' FILLED: 0 REMAINING: 100 AVG_FILL_PRICE: 0 PERM_ID: '1621177315' PARENT_ID: 0 LAST_FILL_PRICE: 0 CLIENT_ID: 0 WHY_HELD: '' 1 Getting Started 1-8
Page
15
Specify Different Instrument You can trade various instruments using the IB Trader Workstation℠ API, including equities, futures, options, futures options, and foreign currencies. ibFutures is 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 as a futures contract FUT, the expiry as a YYYYMM date format, the exchange as GLOBEX, and the currency as USD. ibFutures = ib.Handle.createContract; ibFutures.symbol = 'ES'; ibFutures.secType = 'FUT'; ibFutures.expiry = '201312'; % Dec 2013 ibFutures.exchange = 'GLOBEX'; ibFutures.currency = 'USD'; Retrieve futures data and send orders using the getdata and createOrder functions. Close IB Trader Workstation℠ Connection close(ib) See Also close | createOrder | getdata | history | ibtws Related Examples • “Create Interactive Brokers Combination Order” on page 4-32 • “Create and Manage an Interactive Brokers Order” on page 4-22 • “Request Interactive Brokers Historical Data” on page 4-27 • “Request Interactive Brokers Real-Time Data” on page 4-29 More About • “Workflow for Interactive Brokers” on page 2-6 External Websites • https://www.interactivebrokers.com/en/software/api/api.htm Create an Order Using IB Trader Workstation 1-9
Page
16
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)cqgordereventhandler(varargin{:})}) end Subscribe to Instrument Subscribe to a security tied to the EURIBOR. realtime(c,'F.US.IE') pause(2) Create 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); 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 Market Order Create a market order that buys one share of the subscribed security cqgInst using the account credentials accountHandle. 1 Getting Started 1-10
Page
17
orderType = 1; % Market order flag quantity = 1; % Positive quantity is Buy, negative is Sell oMarket = createOrder(c,cqgInst,orderType,accountHandle,quantity); oMarket.Place Close CQG Connection close(c) See Also close | cqg | createOrder | realtime | startUp Related Examples • “Create CQG Orders” on page 4-37 • “Request CQG Historical Data” on page 4-41 • “Request CQG Intraday Tick Data” on page 4-44 • “Request CQG Real-Time Data” on page 4-47 More About • “Workflow for CQG” on page 2-8 External Websites • CQG API Reference Guide Create an Order Using CQG 1-11
Page
18
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, 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 ..\blp\api\APIv3\JavaAPI\lib\blpapi3.jar or ..\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 In your Bloomberg terminal, type WAPI {GO} to open the API Developer’s Help Site screen. b Click API Download Center, then click Desktop API. c After downloading blpapi3.jar on your system, add it to the MATLAB Java class path using the javaaddpath function. Execute the javaaddpath function for every session of MATLAB. To avoid executing the javaaddpath function 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” (MATLAB). For details about editing your startup.m file, see “Startup Options in MATLAB Startup File” (MATLAB). 2 Connect to the Bloomberg EMSX test service. c = emsx('//blp/emapisvc_beta') 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 test service • Port number of the machine running the Bloomberg EMSX test service Create 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.EMSX_ORDER_TYPE = 'MKT'; order.EMSX_SIDE = 'BUY'; 1 Getting Started 1-12
Page
19
order.EMSX_TICKER = 'IBM'; order.EMSX_AMOUNT = int32(400); order.EMSX_BROKER = 'EFIX'; order.EMSX_HAND_INSTRUCTION = 'ANY'; order.EMSX_TIF = 'DAY'; Create and Route Market Order Create and route the market order using the Bloomberg EMSX connection c and 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 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 Close Bloomberg EMSX Connection close(c) See Also close | createOrderAndRoute | emsx Related Examples • “Create and Manage a Bloomberg EMSX Order” on page 4-10 • “Create and Manage a Bloomberg EMSX Route” on page 4-14 • “Manage a Bloomberg EMSX Order and Route” on page 4-18 More About • “Workflow for Bloomberg EMSX” on page 2-2 External Websites • EMSX API Programmers Guide Create an Order Using Bloomberg EMSX 1-13
Page
20
Create an Order Using X_TRADER 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 Instrument for 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',... 'ProdType','Future','Contract','Aug14',... 'Alias','SubmitOrderInstrument3') Register Event Handler for 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 Order Set and Set Order Properties Create an empty order set. Then, set order set properties. Setting the first 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 = 1; c.OrderSet(1).EnableOrderUpdateData = 1; c.OrderSet(1).OrderStatusNotifyMode = 'ORD_NOTIFY_NORMAL'; Set Position Limit Checks c.OrderSet(1).Set('NetLimits',false) 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)}) 1 Getting Started 1-14
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A task-oriented reference for MATLAB users who need to connect to brokerage and market-data systems, route orders, and run transaction-cost and portfolio-liquidation analyses from within MATLAB. Best suited to practitioners with an existing broker/data license and MATLAB fluency, not to readers seeking trading theory.
【Book Arc】
- **Opening (~0%–10%)**: Getting-started material on installing and configuring third-party connections (Interactive Brokers Trader Workstation, Trading Technologies, Bloomberg EMSX, CQG, FIX Flyer, X_TRADER) and placing a first order through each, solving the "how do I connect and send an order" problem.
- **Early (~10%–32%)**: Transaction cost analysis built around the Kissell Research Group (krg) object — market-impact parameters, sensitivity analysis, portfolio liquidation, and optimization via fminbnd/fsolve — plus the first full workflow examples for EMSX and IB.
- **Middle (~32%–48%)**: Sample-code workflows across providers: EMSX order/route creation and management, IB contract and order objects, CQG historical and real-time data requests, and the function reference for EMSX objects and methods.
- **Late (~48% onward)**: The remaining function reference (createOrder, deleteOrder, modifyOrder, routeOrder, subscriptions, timers) and WDS topics on using snapshot and historical data to decide on trades; excerpts thin out here.
- **Ending**: Reference-style API documentation rather than a narrative close — the excerpts do not cover the final chapters in detail.
【Book Arc note】The progression is fundamentals (connect) → analysis (cost models) → practice (worked workflows) → reference (function-by-function lookup).
【Key Takeaways】
- **Connections are provider-specific and license-gated** (Opening): each broker (EMSX, IB, CQG, TT, FIX Flyer, X_TRADER) has its own setup steps and requires a valid license before MATLAB can talk to it.
- **Order lifecycle follows a repeatable pattern** (Early): connect → build an order/contract structure → create/route → subscribe to events → modify or delete → close. Learning one provider's flow transfers to the others.
- **Event handling is central to the API** (Early–Middle): default handlers process order events, while custom handler functions run on a MATLAB timer with start/stop/delete, letting you react to fills and route updates.
- **Transaction cost analysis is a first-class module** (Early): the krg object pulls market-impact parameters (e.g., from the Kissell Research Group FTP site) and supports sensitivity, stress, and back tests on portfolios.
- **Optimization ties cost models to decisions** (Early): liquidation and trade-schedule problems are framed as minimization (market-impact cost, trade schedule) solved with Optimization Toolbox functions like fmincon, fsolve, and fminbnd — an Optimization Toolbox license is required.
- **Data requests split into historical and real-time** (Middle): CQG's history and realtime functions, plus WDS snapshot/historical topics, show how to pull prices for analysis and trading decisions.
- **The back half is a lookup reference** (Late): object functions for EMSX (createOrder, routeOrder, modifyOrder, deleteOrder, groupRouteOrder, createBasket, manualFill) are documented method-by-method for on-the-job use.
【Reading Tips】
- **Skim the provider setup chapter** and deep-read only the broker you actually use; the configuration steps are near-identical in structure across vendors.
- **Work the sample workflows hands-on** (EMSX order/route, IB contract/order, CQG history) — the code is the real content, and the prose mostly narrates it.
- **Treat the function reference as a dictionary**, not a read-through; jump in when a specific method's arguments or return fields are unclear.
- **Watch licensing dependencies**: transaction cost analysis and optimization examples assume Optimization Toolbox and Kissell Research Group data access; confirm you have these before attempting them.
- **Take away the workflow skeleton** (connect → subscribe → act → close) rather than memorizing provider-specific field names.
【Coverage Limits】
The excerpts are dominated by setup steps, worked examples, and function reference entries; they do not cover the book's later chapters or any conceptual trading-strategy discussion in depth, so this guide reflects the API/workflow character of the material rather than a full chapter map.
Passage locations
Page 19
ee Also close | createOrderAndRoute | emsx Related Examples • “Create and Manage a Bloomberg EMSX Order” on page 4-10 • “Create and Manage a Bloomberg EMSX R...
View in text
Excerpt 2
= CovarianceData(1:n,1:n); C = table2array(CovarianceData); For a description of the example data, see “Kissell Research Group Data Sets” on page 3-7. Define...
View in text
Page 18
oomberg EMSX session object • Bloomberg EMSX service object • IP address of the machine running the Bloomberg EMSX test service • Port number of the machine...
View in text
Excerpt 4
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...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay