RIT - User Guide - VBA API Documentation_2
RIT - User Guide - VBA API Documentation_2
Build 1.03
Table of Contents
Introduction ..................................................................................................................................... 2
Introduction to Excel VBA (Developer) ......................................................................................... 3
VBA API Commands for RIT ...................................................................................................... 10
VBA API Initialization ................................................................................................................. 11
Algorithmic Trading Example - Arbitrage ................................................................................... 22
Copyright © 2014, Rotman School of Management. No part of this publication may be reproduced, stored in a retrieval system,
used in a spreadsheet, or transmitted in any form or by any means – electronic, mechanical, photocopying, recording or
otherwise – without the permission of Rotman School of Management.
Introduction
The Rotman Interactive Trader allows users to query for market data and submit trading instructions
through a Microsoft Excel Visual Basic for Applications (VBA) API as well as through a REST API. The
purpose of this is to allow for program “algorithmic” trading, where the computer executes trades
based on a pre-defined set of instructions or parameters.
This tutorial document focuses on interacting with the Excel VBA API and assumes that the user has
no previous knowledge of VBA, and begins by discussing the concepts of programming before in-
depth trading algorithms are introduced. Those who are already familiar with VBA should skip to the
section entitled “VBA API commands for RIT”.
This document also does not discuss the strategies behind algorithmic trading. Rather, it introduces
the user to the tools that are available through the RIT Excel VBA API. Users are encouraged to
explore possible strategies and techniques and use the building blocks here to implement them.
To access the VBA editor in Excel, first ensure that it is turned on by clicking on “File” on the top-left
corner of the screen, then click on “Options”. Once the “Excel Options” window is opened, choose
“Customize Ribbon” on the left menu bar, and ensure that “Developer” on the right side is checked.
Once this is checked, the Developer Tab will appear in the original list of Excel tabs.
You can access the VBA editor by clicking on the “Visual Basic” icon within the Developer tab.
Hint: You can access this at anytime with the shortcut Alt+F11
We will begin by writing some basic procedures in your Book1.xls. In order to do this, create a module
in your book by going to Insert -> Module.
Module1 will be added to your Book1 project and a code window will open on the right hand side
allowing you to input your programming code.
The first step is to write a very simple procedure. A procedure is a set of programming lines that are
run by the computer whenever instructed to do so. Procedures are defined with the lines “sub
<procedure>” and “end sub” enclosing them. We will define a procedure named “message” by
inputting “Sub message” into the code window. As soon as you type “Sub message” (without quotes)
and press enter, VBA will automatically format the text by adding brackets after message and add
“End Sub” to the next line.
We will start with a basic set of code that references the built-in VBA function “MsgBox”. To do this,
type “MsgBox (“Hello World”)” into the code window between your (Sub) and (end sub). The
”MsgBox” command will cause a pop-up message box to show up in Excel when the code is executed.
After you have typed the code into the window, click on the “Play” button in the VBA editor, your code
will execute and a pop-up message in Excel should appear.
To create the Macro button, go back to the Developer tab in Excel and click on Insert, and then select
the first option “Button”.
Once that is complete, left-click on the button and your “Hello World” message box should appear. If
you ever want to edit this object (resize, redirect, etc.) right click on it and a context menu will appear
allowing you adjust the box.
To understand a little bit more behind the programming, we will revisit the code and modify it to be
slightly more complex. In the Visual Basic Editor, we are going to modify the code to read “MsgBox
Cells(1,1)” instead of “MsgBox (“Hello World”)”.
Much like Microsoft Excel, VBA assumes that any text wrapped in “quotes” is plain text, whereas
anything not wrapped in “quotes” is a function, procedure, or operation. Since there are no quotes
around “Cells(1,1)”, it will not say “Hello Cells(1,1)”, instead, it will follow the command of Cells(1,1).
Replacing (“x”) with Cells(1,1) means we will use the data from the cell located in row 1, column 1.
MsgBox Cells(1,1) means “Create a message box with the data from row 1, column 1”
Now go to the Cell A1 in the current Excel Sheet1 and type in “Bob”. Click on your Macro button, the
result should be a message box that says “Bob”. Hint: If you want to reference cells from other sheets,
you can do this by typing Sheet3.Cells(1,1). This will now use the data from cell A1 on Sheet3.
We can make this more complex by adding an equation into the procedure. Go back to the VBA editor
and change your code to the following:
Go to your Excel Sheet and type “Sally” into Cell A2, and click your macro button. The result should
be:
To clean this up a little bit, we will make another adjustment to the code by adding the word “and”
between the two references. This is accomplished as follows:
The last code adjustment that we will make is to add a mathematical equation to our message box.
This is accomplished as follows:
Type the values “3” and “5” into cells A3 and A4 and run your procedure by clicking the button. The
result should be “Bob and Sally15”. Since we used the asterisk “*” between Cells(3,1) and Cells(4,1),
VBA is instructed to multiply the values from these two cells, and then append them as text to the
rest of the text.
This concludes the basic VBA training that you will need in order to access the RIT API. You are now
able to write a simple set of instructions (a procedure) in VBA using a predesigned function (MsgBox)
and execute it via the Button that was created. In the next section, you will use the skills that you have
learned, and apply them to trading!
Application Programming Interface (API) commands in Excel VBA can both retrieve information
from and perform actions on the Rotman Interactive Trader (RIT).
To begin, start with a NEW spreadsheet and access VBA. In order to access RIT‟s built-in VBA
commands, you will need to add it as a reference to your VBA project by going to: Tools ->
References
When the Reference window appears, scroll down and check the item “Rotman Interactive Trader”.
This step loads the Rotman commands and functions into VBA so that you can reference them.
Next, create a module in your file by going to Insert -> Module.
Then, initialize a new Rotman Interactive Trader API object using the following code:
Once the RIT API object is initialized, you can start writing API commands. In general, the syntax for
an API command is made up of 3 main parts: the object, the method, and the parameter(s) (optional),
as demonstrated in the following sample code:
In this example, API is the object that actions are performed on. The method, CancelOrder, is the
action to perform on API (in this case, the action is to cancel an order). The parameter, order_id,
specifies details of the action (here, it specifies the order ID of the particular order to cancel).
Depending on the action that a method performs, it may or may not require a parameter. In the
example above, API.CancelOrder requires a parameter to specify which order to cancel. In the
following sections you will see examples of methods which do not require a parameter. These
methods perform general actions. There are also examples demonstrating the use of more than one
parameter, separated by a comma.
Other than performing actions, methods can also return a result (called the return value). It can be
stored in a variable or a cell in an Excel worksheet for later reference. The example API.CancelOrder
does not have a return value.
Submitting an Order
Let’s start by simply submitting a buy order. This can be accomplished with the following code:
Sub submitorder()
Dim API As RIT2.API
Set API = New RIT2.API
Dim status as Variant
status = API.AddOrder("CRZY", 1000, 5, API.BUY, API.LMT)
End Sub
Note that the example is setup assuming that students are trading a case with a stock “CRZY”. If you
are trading a different case, you will need to change the ticker otherwise the command will not work
since the security “CRZY” does not exist.
As you type the beginning of the command “API”, you will notice that a dropdown box will appear
showing all of the different API commands that you can access.
Once you have completed the code, you can click on the red Play button in order to run the procedure.
Click the button a few times and visit your RIT Client, you should see limit orders placed at $5.00 to
buy shares of CRZY.
There are a few sample codes you can try in order to practice submitting different types of orders.
Please feel free to try them.
Submit a limit buy order for the stock CRZY with size 1000, at a price of $5.00. Assign True to the
variable status if the order is successful, and assign False otherwise. Use “Range” to call cells that
contain volume and price information. (So in this case, you should type 1000 in cell A1, and type 5 in
Alternative 1:
Dim status as variant
status = API.AddOrder("CRZY", Range("A1"), Range("A2"),
API.BUY, API.LMT)
Alternative 2:
Dim status as variant
status = API.AddOrder("CRZY", Range("A1"), Range("A2"), 1, 1)
Submit a market sell order for the stock CRZY with the size found in the cell A1 at the market price.
Assign True to the variable status if the order is successful, assign False otherwise. Note that the sell
price is specified here (with an arbitrary number, 1) even though it is ignored.
Alternative 1:
Dim status as variant
status = API.AddOrder("CRZY", Range("A1"), 1, API.SELL,
API.MKT)
Alternative 2:
Dim status as variant
status = API.AddOrder("CRZY", Range("A1"), 1, -1, 0)
Submit an order for the stock CRZY with the size found in the cell A1 at the market price. Assign True
to the variable status if the order is successful, assign False otherwise. Whether the market order is
to sell or buy depends on the value in the cell A2. Note that if a cell reference is used for the buy_sell
parameter, the number value must be used in the cells. In other words, the cell A2 must contain 1 or
-1. The strings “API.BUY” or “API.SELL” will not work.
Referencing cells for the lmt_mkt parameter follows the same pattern. The cell being referenced must
contain 0 or 1 instead of the text “API.LMT” or “API.MKT”.
Similar to AddOrder, you can also use AddQueuedOrder to submit a limit or market, buy or sell order.
While all the parameters for AddQueuedOrder are the same as for AddOrder, the difference lies in
the return value. While AddOrder returns True/False, AddQueuedOrder will return -1 (for failure to
submit an order when the case is inactive) or an internal queued order ID* (for successful order
submission).
*When an order is submitted using either AddOrder or AddQueuedOrder API command, the RIT
Server ‘queues’ an order before processing it in the system. Hence, when each order is queued, an
internal queued order ID is first provided, and is converted later to an order ID when it appears on
the Market Depth Book. This entire order submission process is generally completed in a fraction of
a second when there are not many orders. However, one may choose to specifically use
AddQueuedOrder in order to retrieve an internal queued order ID and cancel it individually before
an order is processed. For more detailed information, please refer to ‘Sample Code 3 – Using
CancelQueuedOrder’ under the ‘Cancelling an Order’ section below.
In addition, you can use the IsOrderQueued command to see if any particular order is currently
queued. The command requires an internal queue ID as an input, and returns “True” for the order
that is queued (at the moment), and “False” for any orders that are not queued (i.e. whether the order
has been queued previously but successfully submitted, or simply the order has failed to be queued).
From the above example, the IsOrderQueued command will return “False” because by the time that
the VBA code reaches the “API.IsOrderQueued(status)” line, the order has been already
queued and submitted from the API.AddQueuedOrder command. Hence, the command will return
“False” since the order is not queued anymore. If there are several orders submitted by the API code,
the IsOrderQueued command may return “True” if it is still queued.
Cancelling an Order
The following command cancels an order based on the order ID specified by the parameter.
There are a few code samples you can try in order to practice cancelling orders. Please make sure
that you have submitted orders before you try cancelling them.
Sample Code 1:
Cancel the order with the Order ID 1500. Usually, you would make this more robust by linking the
value to a cell location with the Cells(x,y) or Range(“mx”) functions as in Sample Code 2.
Sub cancelorder()
Dim API As RIT2.API
Set API = New RIT2.API
API.CancelOrder (1500)
End Sub
Sample Code 2:
API.CancelOrder (Range("A1"))
You can use CancelQueuedOrder to cancel an order that is ‘queued’ on the RIT Server before it
appears on the Market Depth Book. Once you retrieve an internal order ID using AddQueuedOrder
API command (from the ‘Sample Code 4 – Using AddQueuedOrder’ under ‘Submitting an Order’
section), you can use the following command to cancel it:
API.CancelQueuedOrder (internal queued order ID)
In case you would like to cancel all queued orders, you can use the following command:
API.ClearQueuedOrders
Again, please note that the above API commands only cancel the queued orders before they appear
on the Market Depth Book. In order to cancel the orders that are submitted and visible on the Market
Depth Book, please use the API.CancelOrder commands from above or follow the Cancel Order
Expression instructions below.
The following command cancels all orders that satisfy the expression specified in the parameter.
API.CancelOrderExpr (order_expr)
Parameters:
Sample Code 1:
Cancel all orders that have a price greater than $20.00 and a volume equal to 400.
Sample Code 2:
Sample Code 3:
Cancel all orders that have a price greater than $20.00 and a volume equal to 400, or all orders
associated with the stock CRZY.
In addition to the order submission and cancellation in RIT, the following API commands can be used
to retrieve real-time data from RIT on institutional tender offers, in addition to accepting/declining
those tender offers. Note that the “Cells” (or “Ranges”) VBA command is used in the examples below
in order to display the result in a cell.
1
If the RTD/API commands do not work, please make sure that you have the most recent version of the RTD.API
Links installed on your PC. You can check this by following the instructions at Step 3 of the following link
https://inside.rotman.utoronto.ca/financelab/rit-downloads/
In addition to the order submission and cancellation in RIT, the following API commands can be used
to retrieve real-time data from RIT instead of using the RTD Link functions in Excel. Note that the
“Cells” (or “Ranges”) VBA command is used in the examples below in order to display the result in a
cell.
Excel result
This API command requires 9 columns in Excel to retrieve the order information as shown below.
Additionally, there are the following additional API commands that can be used to retrieve the real-
time data from RIT.
This example assumes that students are building the arbitrage VBA codes while they are connected
to the RIT Client with the ALGO1 case running. By default, the case runs for 300 seconds and there
is one security that is traded on two different exchanges – CRZY_A and CRZY_M.
Before we start, please make sure that the Rotman Interactive Trader is enabled in Tools
References. (Please refer to the “Setting up RIT API configuration” section in page 11). Once you
create a new module, you should type into the code-box on the right hand side of the window and
define a function. In this example, the function will be called “arb” and it will have one parameter
called “timeremaining”.
While there are many other ways to switch on/off the arbitrage algorithm, we will use the
“timeremaining” to signal when the algorithm can start and stop. Once we initialize the RIT API, we
can have the following ‘if statement’ to control the time that the algorithm is turned on and off.
Operationally, every time the “arb” function is run, Excel will initialize the API, and then check to see
if the time remaining is between 5 and 295. As shown in the above example, the code currently
initializes the API and allows for algorithmic trades to be submitted if the time remaining is between
5 and 295. (However, it will not submit anything because there are no commands written after the
IF statements yet.)
The VBA code is now setup to run the arbitrage function whenever the case is running. The last step
is to go into the code and program the logic to check for arbitrage opportunities, and execute the
appropriate trades.
Now with this data linked in Excel, we can use an IF statement in our algorithm so that it only executes
the buy/sell pair or orders when an arbitrage opportunity exists. Hence, the logic should be to check
for two potential arbitrage opportunities:
If the ask price of CRZY_A is less than the bid price of CRZY_M, then the algorithm should submit a
market order to buy CRZY_A and a market order to sell CRZY_M.
If the ask price of CRZY_M is less than the bid price of CRZY_A, then the algorithm should submit a
market order to sell CRZY_A and a market order to buy CRZY_M.
Here, each cell is named with the security name and bid/ask information. As you can see from the
example below (highlighted in blue) Cell B2 has been named as “CRZY_A_BID”, etc. This is not a
required step, but naming each cell will help you understand the information it contains. You can use
Range(“B2”) instead of Range(“CRZY_A_BID”)
Alternatively, this can be replaced with the examples of the code we used in the “Submitting an Order”
section above as shown below.
Finally, in order to run the “arb” function, you would need to return to the spreadsheet, find a cell
and type in “=ARB(E2)”
This will tell Excel to execute the function “Arb” and pass into the function the value from cell E2
(which happens to be the time remaining in the simulation). In this situation, the time remaining is
300 seconds, so the code in the “IF” statement will not execute. Once the case is started (and
timeremaining is < 295), then the code in the “IF” statement will execute.
While the ALGO1 case is running, whenever the markets become crossed, the algorithm should
automatically buy shares on one market and sell shares on the other and generate a profit.
Excel runs the function (and the code) on a continual basis. Therefore, when students try to
edit the code in VBA, it will cause an error (because Excel is trying to run half-written code).
In order to proceed, students should delete the function =ARB(E2) in the spreadsheet before
editing their code, and then add it back later.
Note that this is a simple arbitrage algorithm. Please feel free to try to improve this by making it
more dynamic (i.e. link the order size and price to Excel), include the gross/net limit restrictions in
the case, etc.