MATLAB as an Automated Execution System



Similar documents
ATF Trading Platform Manual (Demo)

How To Use Mts Bondspro From A Computer To A Trading System

Turk s ES ZigZag Day Trading Strategy

ECLIPSE DAY TRADING SYSTEM USER GUIDE

Day Trading Stock Controller

I Day. article. In. you but. I just. Entry. Trend. I risk. 2.5% per. equity. a "runner" trading

MOON-ES DAY TRADING SYSTEM USER GUIDE

Handbook for finding the right FX Broker

Haksun Li MY EXPERIENCE WITH ALGORITHMIC TRADING

Pairs Trading: A Professional Approach. Russell Wojcik Illinois Institute of Technology

How To Trade The Emni And Oil And Light Sweet Crude Oil

MetaTrader 4 for iphone Guide

Day Trade Warrior. Business Plan Trading as a Business

Real-time trading in MATLAB

Strategies for Trading Inverse Volatility

DELIVERED BY NEO TRADING PLATFORM EMPOWERING RETAIL FOREX TRADERS NEO ALGO TRADER REVOLUTIONARY ALGORITHMIC TRADING PLATFORM

(This Page Intentionally Left Blank)

J-TRADER QUICK START USERGUIDE For Version 8.0

Contents Risk Disclaimer... 3 Introduction... 4 Choosing the Right Broker... 4 The Financial Markets... 5 The Forex Market...

Daytrading Stock Pairs

A powerful dashboard utility to improve situational awareness of the markets, place precise orders, and graphically monitor trading positions.

Algorithmic Trading Session 1 Introduction. Oliver Steinki, CFA, FRM

How to Win the Stock Market Game

HIGH PROBABILITY. Trading Made Easy! Nirvana s PairTrader 2.0. The POWER of Pair Trading CD Seminar see page 5. INSIDE:

MT4 ANDROID USER GUIDE. FASTEST GROWING FX PROVIDER 2012 World Finance Awards. BEST TRADING PLATFORM World Finance Awards

Using Historical Probabilities to Trade the Opening Gap

Algorithmic Trading Session 6 Trade Signal Generation IV Momentum Strategies. Oliver Steinki, CFA, FRM

The following section includes my own personal reviews of a few major software packages.

Pairs Trading STRATEGIES

MT4 Multiterminal USER MANUAL

EF MetaTrader 5 for Android OS

Table of contents. 1. About the platform MetaTrader 4 platform Installation Logging in 5 - Common log in problems 5

Quantitative Trading. How to Build Your Own Algorithmic Trading Business. Wiley Trading

How To Build A Trading Engine In A Microsoft Microsoft Matlab (A Trading Engine)

CFDs YOUR STARTER KIT

A Powerful Day Trading Strategy For Futures And Forex Markets Markus Heitkoetter

UNUSUAL VOLUME SYSTEM

OANDA FXTrade Platform: User Interface Reference Manual

Developing Algo Trading Applications with SmartQuant Framework The Getting Started Guide SmartQuant Ltd Dr. Anton B.

60 Minute Trader. Author: Chris Kobewka. Published By: Internet Unlimited LLC. 26C Trolley Square Wilmington DE, USA

Chapter 6 - Condor finder

No duplication of transmission of the material included within except with express written permission from the author.

iphone Application User Guide

Forex Cantata User Manual

The FOREX Master Plan

EUR/USD Trading Strategy

TOMORROW'S TRADING TECHNOLOGY. 100% automated Fibonacci support and resistance levels that you can count on every single trading day in an instant.

Overlapping ETF: Pair trading between two gold stocks

Session IX: Lecturer: Dr. Jose Olmo. Module: Economics of Financial Markets. MSc. Financial Economics

Pivot Trading the FOREX Markets

MICHAEL HODGES AND BRETT COOPER

Simpler Options. Indicator guide. An informative reference for John Carter s commonly used trading indicators.

MetaTrader 4 for Android TM Guide

How To Know When A Market Is In A Strong Trending Phase

Financial Markets And Financial Instruments - Part II. How Securities are Traded? Spread. Brokerage Accounts. Commissions. Commissions: Online Brokers

Butterfield s Online Investment Centre provides you with online access to your brokerage accounts, night and day, seven days a week.

AbleTrend. Why Haven t Investors Been Told These Facts? Look inside to discover: Buyers. Call Free (888)

NEDIS Connect Quick Start Guide B.N. Vervoort Project Engineer E-Commerce v1.0

Design of an FX trading system using Adaptive Reinforcement Learning

Brief Overview of Futures and Options in Risk Management

HOW TO SELL A STOCK BY KELLY GREEN

Case Package Rotman Online Trading Competition

Content Author's Reference and Cookbook

IndiaNivesh Securities Pvt. Ltd. M-Nivesh Mobile Trading Application

Click on the below banner to learn about my revolutionary method to trade the forex market:

Sirix Tablet 6.5 User Guide

META QUOTES IPAD USER GUIDE

Algorithmic Trading: A Quantitative Approach to Developing an Automated Trading System

The FTS Real Time System lets you create algorithmic trading strategies, as follows:

Understanding ETF Liquidity

Client Software Feature Guide

ELECTRONIC TRADING GLOSSARY

2-Step Credit Spreads

IMPORTANT RISK DISCLOSURE

TRADING GAPS TAIL STRATEGY SPECIAL REPORT #37

Take it E.A.S.Y.! Dean Malone 4X Los Angeles Group - HotComm January 2007

ValueCharts TradeStation

Smart Trading Apps: Market Entry App User Guide

Put and Call Options

SUPER TREND PROFIT. (Trend Indicator with alert popup and alert) DISCLAIMER

What Is an Option? the basics. Types of Options

Evolution of Forex the Active Trader s Market

Portfolio Rotation Simulator User s Guide

Manual: I. Getting Started:

CFD-FX Trading platform Software User Guide. May 2006

INTRADAY STOCK INDEX FUTURES ARBITRAGE WITH TIME LAG EFFECTS. Robert T. Daigler. Associate Professor. Florida International University

G100 VIEWS HIGH FREQUENCY TRADING. Group of 100

Forex Cantata User Manual

A Day Trading Strategy: The Gap System

Conservative Day Trading Strategy for Forex

Proceedings of the 9th WSEAS International Conference on APPLIED COMPUTER SCIENCE

Multi Account Manager

Real Time Market Data and Trade Execution with R

Quick Start Guide Getting Started with Stocks

How To Trade Against A Retail Order On The Stock Market

USER MANNUAL. Version 1.9.6

High-frequency trading: towards capital market efficiency, or a step too far?

Mean Reversion - Illustration of Irregular Returns in US Equity and Fixed Income Markets

Trader Manual. NatureForex.com

Transcription:

MATLAB as an Automated Execution System By Ernest P. Chan, Ph.D. Many traders are familiar with MATLAB as a powerful software platform for backtesting trading strategies. This is especially true for those who would like to analyze and trade a large number (maybe thousands) of stocks simultaneously. MATLAB is a language that is built around matrix manipulation and processing, so many calculations involving multiple stocks are just as easy as calculations involving a single stock. In my book Quantitative Trading (Wiley 2008), I have described a number of examples of how backtesting is usually done in MATLAB. However, it was also true that MATLAB suffered from a major deficiency relative to more familiar trading platforms such as TradeStation after a strategy has been backtested, it wasn t easy to immediately turn it into an execution system and submit orders to your brokerage account. Brokerages that support Application Program Interfaces (API) to various other languages such as Visual Basic, Java, C# or C++ often does not support MATLAB. Therefore, building an automated execution engine involves re-programming the strategy in one of those languages that your brokerage supports, thereby losing the simplicity and ease-of-use of MATLAB. Recently, however, I have discovered a piece of software that can seamlessly connect a MATLAB program to a brokerage account, allowing MATLAB to receive market data, execution and position reports from the brokerage, and to s orders for execution to the brokerage. In other words, turning MATLAB into an automated execution engine. This program is called Matlab2IBAPI (www.exchangeapi.com), created by Exchange Systems Inc. As its name imply, this program is built specifically for connection to Interactive Brokers (IB) but given the widespread adoption of IB as an effective platform for algorithmic traders, this limitation is minor compared to the speed of building an execution engine. (Exchange Systems Inc. also created another API called MATLAB2TT for direct connection to futures exchanges using Trading Technologies International s FIX adaptor, but this is beyond the scope here.) The use of an automated trading system (ATS) is advantageous but optional if your strategy generates orders infrequently. For example, if you s orders only near the market open or close, then you can simply specify all your orders on an Excel spreadsheet, load this spreadsheet up to a basket trader such as the one available from IB, press a button and have the basket trader s out all the orders on the spreadsheet in one fell swoop. This process does involve quite a few manual steps. Using an ATS in this case will allow you to generate and submit orders by one push of a button, and so will certainly make life much easier, though it is not essential. Of course, if you are running a few strategies that all require such manual steps simultaneously, an ATS may become essential even for such strategies with infrequent orders.

If your strategy generates orders at all times of the day, or if it generates orders at high frequency, then an ATS becomes critical. An example is a simple mean-reverting Bollinger-band strategy on ES (the S&P E-mini futures). The strategy simply buys when the price of ES hits the lower Bollinger band (determined by ten 1-minute lookback periods, and 2 standard deviations from the moving average), and sells when the price increases by 1 standard deviation from the moving average. Conversely, it shorts when ES hits the upper band, and then buy-cover when the price decreases by 1 standard deviation. I have backtested this strategy before, and as I mentioned in Chapter 2 of my book, its Sharpe ratio is a very attractive 3 without transaction cost, but is reduced to -3 if we subtract 1 basis point per trade as transaction cost. Even though the strategy as it stands will not survive commissions, not to mention bid-ask spread and slippage, it serves as a good illustration of how to use MATLAB in conjunction with Matlab2ibAPI to build an automated trading system. Furthermore, if you are ingenious enough, you can always take a basic strategy and add enough bells and whistles to make it profitable even in the face of transaction costs. One of the beauties of an ATS is that you can start the program at your leisure and well in advance MATLAB can wake itself up at the right time. Furthermore, MATLAB can automatically exit all existing positions and disconnect from your brokerage account near the market close. In other words, this is truly a turnkey trading program. First, we define a few parameters for the program. localsymbol='esh9'; % Symbol for the front contract symbol='es'; % IB symbol for this future sectype='fut'; % security type exchange='globex'; accountname='u123456'; % This is your Interactive Brokers account name numcontract=1; % Your desired order size lookback=10; % Number of periods used to compute Bollinger band entryz=2; % The distance between the upper and the lower band is % 2*entryZ exitz=1; % Exit when price revert to 1 standard deviation from the mean starthh=9; % Start running strategy at 9:30 ET. startmin=30; hh=16; % Stop running strategy at 16:14:59 ET. mm=14; ss=59; connect2tws % Start a new connection to IB pause(20) % need to pause program to wait for connection to be % established while (1) % Wait until 2 minutes before 9:30 to begin program mytime=clock;

myyyyy=mytime(1); mymm=mytime(2); mydd=mytime(3); myhh=mytime(4); mymin=mytime(5); if (myhh > starthh (myhh == starthh & mymin >= startmin-2)) break; OK, finally it is time to starting getting information from your brokerage account. Note that IB requires a subscription to each symbol (ES in our case) before you can receive market data updates. requestaccountupdates( 1,accountName); % Start receiving account % positions updates reqmktdata(1, symbol, sectype, exchange, '', 0, '', '', localsymbol); % Start receiving market data for this contract isupdated=false; % Indicate whether we have updated the last price in % the current 1-minute bar Now for the main loop for sing orders. for i=1:inf mytime=clock; % Unfortunately matlab2ibapi cannot yet retrieve % server time from IB, hence we need to use local % time % Date and time strings for use in requesting historical data myyyyy=mytime(1); mymm=mytime(2); if (mymm < 10) mymmstr=['0', num2str(mymm)]; else mymmstr=num2str(mymm); mydd=mytime(3); if (mydd < 10) myddstr=['0', num2str(mydd)]; else myddstr=num2str(mydd); myhh=mytime(4); mymin=mytime(5); myss=mytime(6); myss=str2double(regexprep(num2str(myss), '\..*', '')); if (i==1) % As a start, see what we already own in account port=getportfolioupdates(accountname, symbol); if (~isempty(port)) assert(strcmp(port.symbol, symbol));

pos=port.position; else if (myhh >= hh) % Near market close, exit all positions if (pos>0) % S Market Sell orders to exit localsymbol,'sell',pos,'mkt',0,0,'day',''); elseif (pos<0) % S Market Buy orders to exit localsymbol,'buy',abs(pos),'mkt',0,0,'day',''); break; if (i==1) % First time around, get 1 day s worth of 1-min bar % historical data from IB [es]=reqhistdata(i, symbol, sectype, exchange, '', 0, '', '', localsymbol, [num2str(myyyyy) mymmstr myddstr ' ' num2str(myhh) ':' num2str(mymin) ':' num2str(myss)], '1 D','1 min','trades',1,1,2); tic; else % Thereafter, simply get last price every 60 seconds elapsed=toc; if (elapsed >= 60) % sample trade prices every minute lastprice=getlastprice(1); % Update historical price array with last price es.close(1:-1)=es.close(2:); es.close()=lastprice; tic; isupdated=true; if (i==1 isupdated) cls_hist=es.close; % Update historical price array with last % price cls_hist=cls_hist(-lookback+1:); ma=mean(cls_hist); % moving average mstd=std(cls_hist); % moving standard deviation isupdated=false; askprice=getaskprice(1); bidprice=getbidprice(1); lastprice=getlastprice(1);

% Calculate deviation of ask or bid price from moving average zscoreask=(askprice-ma)./mstd; zscorebid=(bidprice-ma)./mstd; % Check if this is time to s orders if (myhh == starthh & mymin < startmin) continue; if (pos==0 & zscoreask < -entryz ) % entry only localsymbol, 'BUY', numcontract, 'MKT',0,0,'DAY',''); pos=numcontract; elseif (pos < 0 & zscoreask < -entryz) % exit and entry localsymbol, 'BUY', 2*numContract, 'MKT',0,0,'DAY',''); pos=numcontract; elseif (pos < 0 & zscoreask < -exitz) % exit only localsymbol, 'BUY', numcontract, 'MKT',0,0,'DAY',''); elseif (pos==0 & zscorebid > entryz) % entry only localsymbol, 'SELL', numcontract, 'MKT',0,0,'DAY',''); pos=-numcontract; elseif (pos > 0 & zscorebid > entryz ) % exit and entry localsymbol, 'SELL', 2*numContract, 'MKT',0,0,'DAY',''); pos=-numcontract; elseif (pos > 0 & zscorebid > exitz ) % exit only localsymbol, 'SELL', numcontract, 'MKT',0,0,'DAY',''); disconnectfromtws; So this is the complete turnkey automated trading system for a Bollinger band strategy for trading ES. (This program can be downloaded from my website epchan.com/book/bollinger.m if you have purchased my aforementioned book, using the same password for all the other programs.) All you need to do is to start this program before the market opens everyday, sit back, and relax. As I said, it isn t likely to be profitable as it stands, but you can probably find enough improvements to make it so. You can use this Matlab2api to trade a large number of stocks simultaneously throughout the day too, thus turning into a true statistical arbitrageur. However, if your strategy trades at high frequency, you will run into some limitations of the IB-Matlab- Matlab2IBapi combination. First, if your account does not generate more than $800 commissions a month for IB (or have more than $1M in equity), you can only get live market data feed on 100 symbols at a time. So if you trade more than 100 symbols, you have to rotate those symbols every few seconds. Second, it will take a second or more to

get updates on your current account positions, or order status. In other words, the IB- Matlab-Matlab2IBapi combination won t work for strategies that have expected holding period of less than a second. Despite this limitation, I hope you will agree with me that Matlab2IBapi provides you with a powerful and convenient platform for implementing most intraday strategies. About the Author Ernie is the founder of the trading strategy consulting firm E.P. Chan & Associates (www.epchan.com) and co-founder of Chicago-based EXP Capital Management, LLC. He is also the author of Quantitative Trading (Wiley, 2008).