EXCHANGE APPLICATION PROGRAMMINGINTERFACES The major exchanges all have APIs to which developers can write to create market data feed and order routing applications.. The Chicago Mercant
Trang 1relating to interoperability of systems, particularly in legacysystems using Component Object Model (COM) objects.
APPLICATION PROGRAMMING INTERFACES
In short, a software application’s API defines the proper way forother applications to interact with and request services from it Inthe trading industry, APIs facilitate the exchange of data betweendifferent software applications and will provide for interoperabilitybetween financial industry software packages and our ownsoftware built in VB.NET Through APIs we are able to integratemultiple commercial off-the-shelf (COTS) software products withour own proprietary software to create customized trading and riskmanagement systems—and at a fraction of the cost of developing acomplete system from the ground up APIs allow us to create a kind
of middleware that shares data across different trading platformsand networks Most, if not all, software packages that you willencounter as a financial engineer will have APIs that either are afree bundled part of their software package itself or are separatelylicensed packages available for a fee
An API is a set of rules for writing function calls orinstantiating objects that access function definitions or classes in alibrary, usually in the form of a dll file Programs we create that usethese functions or classes can communicate with the COTSsoftware to, for example, run an optimization routine, exchangeinformation such as market data feeds, process buy and selltransactions, and post trade fill information to a database Once wehave created objects based upon the classes in the library, the APIclasses do all the work for us, totally transparent to our application
In addition to performing data-sharing tasks, APIs usually checknetwork parameters and error conditions for us so as to deliverrobust interoperation between the programs
As opposed to fully open source code, which exposes thesoftware maker’s proprietary methods, APIs represent a stream-lined way to grant access to an application without giving awayintellectual property APIs grant less access than open source codebut certainly more than entirely closed software
Trang 2Among financial markets COTS software, APIs exist in manydifferent forms You should fully understand the implementation
of the API, contained in the software vendor’s API documentation,before you proceed
EXCHANGE APPLICATION PROGRAMMINGINTERFACES
The major exchanges all have APIs to which developers can write
to create market data feed and order routing applications Writing
to an exchange API, or alternatively to the FIX interface, andbuilding proprietary software from the ground up requires ahealthy amount of research, time, and money As was discussed inChapter 1, for most small firms this is not a feasible option forbuilding automated trading systems However, we can gain asomewhat greater understanding of market connectively andelectronic exchange order routing if we briefly look at threeexchange APIs
The Chicago Board Options Exchange offers an API throughwhich developers can access the CBOE’s Electronic TradingSystem The CBOE also supports the FIX messages for thepurposes of order routing This FIX interface is available as analternative to connection through the API
The all-electronic International Securities Exchange (ISE)offers an API to which member firms can program to accessmarket data, send trades, and receive trade fill confirmations andinformation Through this API, the ISE’s electronic access membersand market makers can develop applications for automated tradingpurposes or for back-office systems
The Chicago Mercantile Exchange has the Globex system,which contains open APIs for market data and order routing so thattrading firms can write applications to receive real-time marketdata from and place automated orders on the CME’s electronicmarkets
As we have seen previously, firms involved in trading onmultiple markets will need to connect to multiple APIs for marketdata and order entry And every exchange API is different.Furthermore, to add to the complexity, in most cases applications
Trang 3developed to interact with an exchange’s API must be approved bythe exchange itself Fortunately several third-party developershave written customized applications to the respective exchangeAPIs for market data and execution of securities, futures, andoptions trades We will look at how to connect to two of these COTSsoftware applications in Chapter 17.
COM INTEROPERATION
As we have seen in Chapter 10, in order to create VB.NET code thatrequests services from an external component, we must first add areference to it The components can be of the following types:
^ NET class libraries
^ COM components
^ XML web services
We have, up till now, looked only at NET class libraries.Although the new NET libraries and assemblies are now a much-improved model for development, at times we need to make use ofCOM objects .NET applications may someday replace COM ones,but until then, if we need to use a COM object in a VB.NETapplication, we will need to understand something about COMitself and how it differs from the NET Framework
COM is a Microsoft specification used prior to NET thatcontrols library usage and compatibility and communication.Through COM, objects are exposed and their functionality isavailable to other applications Via COM, libraries are ensured to behighly organized and reusable Microsoft defined COM so thatdevelopers could create compatible libraries of classes andcomponents Virtually all Windows libraries that were constructedprior to the advent of the NET Framework adhere to the COMspecification, and most software today includes COM objects ButCOM is difficult to program and deploy because developers mustguarantee that new COM components are compatible If a COMlibrary is placed on a system without being properly registered,applications will be unable to find or use the library
An understanding of COM involves an understanding of howCOM objects exist in memory Whereas NET objects are held in
Trang 4managed memory, which is controlled by CLR (the commonlanguage run time), COM objects are held in unmanaged memory.The CLR in NET manages certain tasks such as dynamic memoryallocation and type checking VB.NET uses managed code, but wecan access the unmanaged COM code using interoperabilityassemblies Many companies have invested significant amounts oftime and effort into creating COM components but now findthemselves eager for a migration to NET Fortunately Microsoftcreated tools for integrating legacy systems and COM componentsinto NET Framework implementations.
The NET Framework provides for direct interaction betweenobjects in managed and unmanaged memory These tools enableinteroperability with COM so that we can use existing COM objects
in our VB.NET programs This process is known within the NETFramework as COM interop
VB.NET uses an interoperability assembly to find COMmethods and translate data between the NET and COM types Thistranslation is performed by the run-time callable wrapper (RCW),which is created by NET based upon the information in an object’sinterop assembly As we discussed in Chapter 10, assemblies arecollections of functionality usually in the form of classes contained
in one or several files with their assembly manifest Assemblymanifests perform the same function in NET as type libraries do inCOM components They include information about versionnumbering, constituent files, types and resources, compile-timedependencies, and permissions
The RCW controls the COM object and carries outcommunication between NET and COM code When we create
an instance of a COM object in VB.NET, we are really creating anew instance of the RCW of the object Fortunately for VB.NETdevelopers, the communication between an RCW and its COMobject is completely transparent to us So we can create and interactwith COM objects as if they were NET objects Adding references
to COM objects is the same as in previous incarnations of VisualBasic except that NET adds the creation of this interop assembly tothe process References to the COM object properties and methods
in VB.NET are routed to the interop assembly prior to proceeding tothe actual COM object code On the way back, responses are routed
Trang 5first to the interop assembly and before being forwarded back tocalling code in NET.
Should the need arise, we can create new COM objects inVB.NET by using the NET Framework’s COM class template,which can create a new class and configures the project so as togenerate the COM class and register it with the operating system.COM objects referenced via interop assemblies must be registered,which we accomplish by using the Regsvr32 utility included withall Windows operating systems If you are familiar with VB 6.0, youare aware that ActiveX controls are commonly used COMcomponents Through the interop assembly, we can import ActiveXcontrols into our NET IDE toolbox using the Customize Toolboxoption, which will list all the COM components that are registeredwith the operating system We are then free to use the ActiveXcontrol in our VB.NET application .NET Framework components
do not need to be registered since NET components maintain all oftheir type identification information internally
In Visual Basic NET, adding references to COM objects thathave type libraries is similar to doing so in previous versions ofVisual Basic However, Visual Basic NET adds the creation of aninterop assembly to the procedure References to the members ofthe COM object are routed to the interop assembly and thenforwarded to the actual COM object Responses from the COMobject are routed to the interop assembly and forwarded to your.NET application If, for example, the input argument and returnvalues of a COM object’s properties and methods use different datatypes than NET does, a process called interop marshaling convertsequivalent data types as they flow back and forth between COMobjects In fact all NET programs share a set of common types thatpermit interoperability of objects, regardless of the programminglanguage
While COM objects have been the foundation of Visual Basicapplications for many years, NET applications designed for CLRoffer many advantages In the NET framework, COM componentsare no longer necessary Through the use of assembly manifests,.NET components hold on to the benefits of COM while solvingmany of its inherent problems
Trang 6The financial markets of the twenty-first century requireconnectivity and interoperability of disparate hardware andsoftware systems The use of APIs and XML will enable software
we create in VB.NET to connect and exchange information withother systems Furthermore, even within Visual Basic itself thereare interoperability issues to confront, particularly those pertaining
to legacy systems making use of COM components
Trang 9Connecting to
Trading Software
An important problem to solve when developing automatedtrading or risk management systems is market connectivity.Connecting to live electronic markets is no small task Millions ofdollars and literally years of time can be spent building such asystem from the ground up However, we can substantially reducethe amount of up-front time and expense needed to establish aconnection to a market by licensing third-party software thatalready provides the required functionality What’s more, most ofthese software packages already connect to more than one market,sometimes dozens of them, around the world enabling traders, orfinancial engineers, to be active in multiple markets simul-taneously More often than not, this kind of third-party softwarewill include an API that we can write to in VB.NET
These APIs usually exist in a single dll library file or a set of.dll files These libraries contain classes that enable us to connect tothe licensed COTS software When we create objects based uponthe classes in such a library, we can use the functionality provided
by these objects to interact with the software and subsequently passdata back and forth Such functionality might include getting live,real-time market quotes, placing buy and sell orders, or receivingtrade fill confirmations
Rather than require that you license some of this commercialsoftware yourself, we have provided two libraries on the CD, calledTrader API.dll and OptionsAPI.dll
Trang 10CONNECTING TO A FUTURES MARKET
The classes in the TraderAPI.dll library allow us to simulate aconnection to a popular industry software package from TradingTechnologies, Inc., called X_Trader Trading Technologies, Inc (TT)develops high-performance derivatives trading software includingthe X_TRADER product, which provides professional traders withconnectivity to electronic derivatives markets around the world.Furthermore, the X_TRADER application contains an API consist-ing of 10 classes that financial engineers can instantiate for thepurposes of developing, among other things, automated analytics,order entry, and trade fill information processing systems.However, you do not need to license X_Trader to use theTraderAPI.dll library included on the CD
As we said, by creating objects from the classes inTraderAPI.dll, we achieve the goal of market connectivity, albeitsimulated As a result, a VB.NET program that adds a reference toTraderAPI.dll and instantiates the objects in it can see the “real-time” market price movements of the S&P 500 eMini futuresmarket, can place market buy and sell orders, and can receive tradefill confirmations
TraderAPI.dll can be used to create applications to customizeorder entry screens, monitor live fill feeds, perform live profit andloss calculations, and automatically execute trades based uponoutside conditions and customized algorithms While providingonly a subset of all the possible functionalities, TraderAPI.dll willgive our programs the look and feel of connecting to real marketsthrough TT’s X_Trader API While APIs are always changing andbeing upgraded, we have, in every way possible, tried to make thearchitecture of TraderAPI.dll mimic the API that comes withX_TRADER
The TraderAPI.dll file included with this book uses the sameclasses, method calls, and methodology, albeit somewhat abbre-viated in functionality, as if you were in a real-life environmentusing the X_TRADER API TraderAPI.dll contains five classes thatsimulate a portion of the X_TRADER API’s functionality The fiveclasses are:
Trang 11InstrObj A tradable object
InstrNotify Must be attached to an InstrObj so when the instrument changes,
messages can be sent OrderProfile Contains all order information for submission
OrderSet Represents a subset of orders on this machine
FillObj Stores all information about each fill
InstrObj Class
An InstrObj object represents a tradable object, that is, aninstrument If we want to receive prices or submit orders, wemust create an InstrObj object Attaching an InstrNotify object to anInstrObj object will allow us to receive price updates as they occur
To create an active InstrObj object, we must supply values for theExchange, ProdType, Product, and Contract properties Here arethe public properties and methods associated with the InstrObjclass
Public
ProdType Product type of the instrument
CreateNotifyObject() Creates a notification object for the instrument GetData() Returns the current values of properties identified by
parameter string Open() Establishes a connection to the instrument
InstrNotify Class
An InstrNotify object, which is attached to an InstrObj object, alertsour application when some aspect, namely the price, of an InstrObjchanges If we want to monitor a price feed for an instrument,
we must create an InstrNotify object To create an InstrNotifyobject, we must use the InstrObj object’s CreateNotifyObject()method
Trang 12Dim myInstrument as New InstrObj()
Dim myInstrNotifyObj = New myInstrument.CreateNotifyObject()
OnNotifyFound() Fires when a connection to the instrument is established
OrderProfile Class
An OrderProfile object contains the information needed for ordersubmission An OrderProfile uses an OrderSet object to actuallysend an order The public properties and methods are listed here:
GetPrice Returns the price of an instrument
GetProduct Returns the product name of an instrument
Instrument Instrument to be traded
Quantity Order quantity
SetTradeParams() Market orders only; TraderAPI.dll does not support limit orders SetTradeType() Sets the trade type
OrderSet Class
An OrderSet object is used to submit orders An OrderSet receivesthe order information from an OrderProfile object and then sendsthe order Characteristics include the following:
EnableOrderAutoDelete Deletes all orders in the OrderSet EnableOrderFillData Returns all the fill information
OnOrderFillData() Fires when a fill has been received
Trang 13FillObj Class
TraderAPI creates a new FillObj when it is notified of a new fill TheOrderSet’s OnOrderFillData event will receive a fill object as aninput argument It’s characterized by this public method:
GetFillInfo() Returns the current values of the fill object
In our VB.NET applications, we can add a reference to theTraderAPI.dll file, import it, and instantiate objects based upon theclasses in the library In this way, we can “connect to the market” toget a simulated data feed, place buy and sell orders, and receivetrade fill information Again, TraderAPI.dll is a stripped-downversion of TT’s X_Trader API and provides only basic functionality,but it will give you the look and feel of creating real automatedtrading software
Let’s create a program that connects to the market in the eMiniS&P 500 futures contracts traded on the Chicago MercantileExchange
Step 1 Start a new Windows application named PriceFeed.Step 2 To your Form1, add five labels in a row
Step 3 In the Projects menu tab, select Add Reference Select
Browse and find the TraderAPI.dll file In the codewindow, above the class definition for Form1, add:
Imports TraderAPI
Step 4 To get a price feed, we need to set up an InstrObj
object and an InstNotify object In the generaldeclarations section of the Form1 code window,add the following code:
Private WithEvents InstNoti As InstrNotify Dim Inst1 As InstrObj
Step 5 Also we will need an array of strings to receive the
quote information Add the code to declare andinstantiate an array of strings in the generaldeclarations section:
Dim MyData As String() = New String() {}
Trang 14Step 6 In the form load event, add the code to create the
objects and open the connection with the ChicagoMercantile Exchange for the eMini S&P 500 contractfor December 2003 This will require setting the fourproperties of the InstrObj object
Private Sub Form1_Load(ByVal sender As ) Handles MyBase.Load
Inst1 = New InstrObj() InstNoti = Inst1.CreateNotifyObj() Inst1.Exchange = "CME-S" ’ Setup gateway name Inst1.Product = "ES" ’ Setup Product name Inst1.ProdType = "FUTURE" ’ Setup Product type Inst1.Contract = "Dec03" ’ Setup Expiry information Inst1.Open() ’ Open/access the instrument End Sub
Step 7 The InstrNotify object has an event,
OnNotify-Found(), that fires when the price of the instrumentobject changes When this happens, we want toretrieve the new bid and ask prices, the bid and askquantities, and the last price Add the followingevent handler for the OnNotifyFound() event in theForm1 code window:
Private Sub InstNoti_OnNotifyFound(ByRef pInstr As InstrObj) _
Handles InstNoti.OnNotifyFound MyData = pInstr.GetData("BidQty,Bid,Ask,AskQty,Last")
Step 8 Run the program You should see the form window
populated with a simulated moving market—with amoving bid and offer, moving quantities, and lastprices hitting the bid and offer See Figure 17.1.Now let’s add the ability to place some orders and get backtrade fill confirmations
Step 9 To place orders, we will need an OrderSet object and
an OrderProfile object In the general declarationssection of the Form1 code window, add:
Dim WithEvents LiveOrderSet As OrderSet Dim CurOrdProf As OrderProfile
Trang 15Step 10 To the Form1_Load event, add the following code to
create the OrderSet object and enable orders to besent:
LiveOrderSet = New OrderSet() LiveOrderSet.EnableOrderFillData = True LiveOrderSet.EnableOrderAutoDelete = False LiveOrderSet.SetLimits("NetLimits", False) LiveOrderSet.EnableOrderSend = True
LiveOrderSet.Open()
Step 11 Add two buttons to your form Change the text
properties to say “Buy” and “Sell,” respectively Inthe Button Click events, add the following code:
Private Sub Button1_Click(ByVal sender As ) Handles Button1.Click
SendOrder("Buy") End Sub
Private Sub Button2_Click(ByVal sender As ) Handles Button2.Click
SendOrder("Sell") End Sub
Step 12 In the form code window, add the following
subroutine called SendOrder():
Private Sub SendOrder(ByVal BuySell As String)
CurOrdProf = New OrderProfile() Dim intSent As Integer
CurOrdProf.Instrument = Inst1 CurOrdProf.SetTradeType("M2", "L") CurOrdProf.SetTradeParams(BuySell, 1, "Market") intSent = LiveOrderSet.SendOrder(CurOrdProf) CurOrdProf = Nothing
End Sub
Trang 16The SendOrder() subroutine creates an order profile, sets theInstrument property, and calls the SetTradeType() and SetTrade-Params() methods In the code above, we are sending a quantity ofone contract Later, when you become a more accomplished trader,
we will allow you to trade larger amounts Finally, we send theorder by calling the SendOrder() method of the OrderSet object.Our method of handling the trade fill confirmations that comeback to us from the market will be to simply print them out in amessage box
Step 13 Add the following subroutine to handle the
OnOrderFillData() event associated with theOrderSet object:
Private Sub LiveOrderSet_OnOrderFillData(ByRef my FillObj As FillObj) _
Handles LiveOrderSet.OnOrderFillData Dim strFillData As String()
strFillData = myFillObj.GetFillInfo("Contract,BuySell,NetQty,Price") MsgBox(strFillData(0) & " " & strFillData(1) & " " & _
strFillData(2) & " @ " & strFillData(3), , "TradeFilled")
to taking a look at the code, you can feel free to test your tradingacumen using this program
Trang 17CONNECTING TO AN OPTIONS MARKET
The classes in the OptionsAPI.dll library allow us to simulate aconnection to a popular options industry software package fromMicroHedge, Inc (MH) MH develops high-end equity optionstrading and analytics software that provides professional marketmakers and traders with a wealth of high-level option portfolioanalytics and risk management tools MH’s flexible design, whichincludes a robust COM wrapper, enables efficient interoperationwith third-party software systems like the one we will build in thischapter As a result, trading institutions often use MicroHedge as afoundation on which they create proprietary systems
With MH’s Screen Based Trading (SBT) software suite,automated market analysis and order selection are greatlysimplified through the use of its API, which consists of dozens ofclasses Furthermore, SBT users can send orders to any of the majorU.S options exchanges, the NYSE, and AMEX, as well as severalECNs Through the MH software developer’s kit (SDK) and SBT,market makers create a single software application to autoquotemarkets, manage risk, and employ custom models As anotherexample of SBT flexibility, options traders can set implied volatilitycurves with one of twenty different calculations, analyze theirportfolio risk under a multiplicity of “what-if” scenarios, andmonitor the national best bids and offers
As we discussed in Chapter 1, it is extremely important torealize that most, if not all, of the options exchanges prohibitautomated order entry in their bylaws There must be humanintervention and trade approval at some point along the way toentering an order We will demonstrate this functionality in theexample program As with the futures example, you do not need tolicense MicroHedge software in order to use the OptionsAPI.dlllibrary included on the CD
By creating objects from the classes in Options API.dll, we canachieve the goal of options market connectivity, albeit simulatedand very stripped down Options analytics requires a huge piece ofsoftware, which MicroHedge is, and we will be able to onlydemonstrate the simplest functionality In any case, a VB.NETprogram that adds a reference to OptionsAPI.dll and instantiatesthe objects in it can monitor “real-time” price movements of the
Trang 18S&P 500 options market, can place market buy and sell orders, andcan receive trade fill confirmations.
OptionsAPI.dll can be used to gain practice creatingapplications to customize order entry screens, monitor live fillfeeds, perform live profit and loss calculations, and execute tradesbased upon outside conditions and customized algorithms Whileproviding only a very small subset of all the possible functional-ities, OptionsAPI.dll will give our programs the look and feel ofconnecting to real options markets through MicroHedge’s API Thearchitecture of OptionsAPI.dll attempts to mimic the SBT API thatyou can license from MicroHedge
The OptionsAPI.dll file included with this book uses the sameclasses, method calls, and methodology (although again they areabbreviated in functionality) as if you were in a real-lifeenvironment using the MH SBT API As we said, OptionsAPI.dllcontains classes that simulate a portion of the SBT API’sfunctionality Here are the classes included in the OptionsAPI.dllfile:
In our VB.NET applications, we can add a reference to theOptionsAPI.dll file, import it, and instantiate objects based uponthe classes in the library In this way we can “connect to the market”
to monitor market quotes, place buy and sell orders, and receivetrade fill information Again, OptionsAPI.dll is a stripped-downversion of MH’s SBT API and provides only basic functionality, but
it will give you the look and feel of creating real trading software.Let’s create a program that connects to the market in the S&P
500 options contracts traded on the Chicago Board OptionsExchange
Step 1 Start a new VB.NET Windows application named
OptionOrders
Trang 19Step 2 To your Form1, add a single text box and a button.
Change the Multiline property of the text box to True.Step 3 In the Projects menu tab, select Add Reference Select
browse and find the OptionsAPI.dll file In the codewindow, above the class definition for Form1, add:
Imports OptionsAPI
Step 4 To get market prices, we need to set up objects for the
MicroHedge, MHSBT, and MHPosition classes In thegeneral declarations section of the Form1 code win-dow, add the following code:
Public WithEvents mhApp As MicroHedge Public WithEvents myMHSBT As MHSBT Dim Pos As MHPosition
Step 5 In the form load event, add the code to create
instances of the objects
Private Sub Form1_Load(ByVal sender As ) Handles MyBase.Load myMHSBT = New MHSBT()
mhApp = New MicroHedge() Pos = mhApp.GetSymbol("SPY.TEST", True, False) End Sub
Because MicroHedge is actually a COM object, we would inthe real world use the CreateObject() function to create an instance
of “MicroHedge.Application” in the following way:
mhApp = CreateObject("MicroHedge.Application")
However, in our simulated environment where we may not haveMicroHedge licensed software, we will use the method forinstantiation as shown COM objects use something calledunmanaged code, which lacks the benefits of VB.NET’s commonlanguage run time But it should not prevent you from creatingefficient applications in VB.NET Since a certain amount ofcomplexity is involved in mixing the VB.NET code with COMobjects, we suggest you contact MicroHedge if you intend to use a.NET platform for development
Step 6 To the Button1_Click event, add the following code:
Private Sub Button1_Click(ByVal sender As ) Handles Button1.Click
GetQuotes() End Sub
Trang 20The method for accessing options data is significantlydifferent from what we looked at for futures data In the previousexample using TT and futures, we connected to the market for asingle instrument and were able to see the market in real time Inthis options example, however, we want to monitor several ormaybe hundreds of option contracts at the same time This willnecessitate looping through the contracts and refreshing the data atspecified intervals In this case the data will refresh, GetQuotes(),when the user clicks the button.
Step 7 Add the following code for the GetQuotes() function
For simplicity’s sake, the OptionsAPI program willonly show data for 20 call options on the SPY Theprice of the underlying index is approximately 841.00and will not move
Private Sub GetQuotes()
TextBox1.Text = "SYMBOL" & vbTab & " BID" & vbTab & _
" ASK" & vbTab & "THEO" & vbCrLf & vbCrLf For i = 0 To 19
TextBox1.Text &= cSym(i) & vbTab & Format(cBid(i), "##.00") & _
vbTab & Format(cAsk(i), "##.00") & vbTab & _ Format(cThv(i), "##.00") & vbCrLf
Next i
End Sub
Here the GetQuotes() function retrieves the bid, ask, theoreticalvalue, symbol, days till expiration, and strike every time it is called.Furthermore it prints the information into TextBox1
Step 8 Run the program You should see the form window,
similar to Figure 17.3, populated with simulatedmarket data when you click the button The data isnot live, however, and will not change Click thebutton again and you will see that the markets dochange slightly with each refresh