Requesting historical data through TWS API with Visual Basic .Net
Author: Joe
Tutorial Objective: Request historical
quote data from TWS and display it in a ListBox
Souce Code: Download
the full source for this tutorial Here
Disclaimer
This tutorial is to be used at your own risk. By using this tutorial
you agree not to hold the writers of this tutorial, StockBotProgramming.com,
or anyone affiliated with StockBotProgrammign.com liable for any damages
that may occur as a result of using this tutorial and/or provided
source code.
This tutorial will assume you have a copy of Visual Studio 2005 and
have Interactive Broker's TWS API installed. You can get a copy Visual
Studio Here,
and the TWS API is available for download Here.
It is highly recommended that you read Connecting to Interactive Brokers TWS Using Visual
Basic .Net before attempting this tutorial. If you have any suggestions
regarding this tutorial or if you notice any mistakes please suggest it here.
Today we are going to modify our code to read historical data from MSFT and
put it into a table. Go ahead and open up your code from Connecting to Interactive Brokers TWS Using Visual
Basic .Net. If you did not complete the tutorial, you can download the
full source code at the end of its page.
From within the code, add the following lines to the end of the Form_Load
event.
Call Tws1.reqHistoricalData(1, "MSFT",
"STK", "", 0, "", _
"", "smart", "usd", 0, "20070514
11:01:00", _
"3600 S", "5 mins", _
"MIDPOINT", "1", "1")
This is the function call that will tell TWS that you want to receive some
historical data.
Parameter 1: This is your request ID. This ID needs to be unique. Used
later so you know which request the incomming data belongs to and used if
you need to cancel the request. In our example we just used 1. However, if
you went to make a second request in the same program you need to change the
ID to something new each time.
Parameter 2: TICKER Symbol
Parameter 3: Security Type, This is the type of security you are
requesting data for. Valid values "STK","FUT","OPT","IND","FOP","CASH".
The two most commonly used ones are "STK" for stock, and "FUT" for
futures.
Parameter 4: Expiration Date in the format YYYYMM, as you can see in my
above example, you can just put "" if you are requesting data for a security
type that does not have expiration dates.
Parameter 5: Strike Price, this is another field you can just put 0 in
if dealing with a security type that does not use it.
Parameter 6: This field is for "PUT" or "CALL" when dealing with
options, other times just put ""
Parameter 7: Multiplier, used when multiple contracts exist such as with
futures. A valid value is to put ""
Parameter 8: Exchange, for most things you can just put "SMART",
however some securities such as futures you will have to use other values.
For example "ECBOT"
Parameter 9: Currency, selects which currency the security trades in.
Normally just enter "USD"
Parameter 10: isExpired
Parameter 11: End Date, this specifies the date at which you want the
historical data query to end. The format for the date is: yyyymmdd HH:mm:ss
zzz The "zzz" section is optional and is for timezone. As you can see in my
above example I am requesting historical data up until April 24, 200 at
11:01. This date has to be within the past 6 months.
Parameter 12: Duration, in my example I am specifying 3600 seconds which
is 60 minutes. The value is entered by an integer value followed by either
"S" for seconds, "D" for days, or "W" for week
Parameter 13: Bar Size, this is what size each data bar sent will
be in. Valid values are 1 secs, 5 secs, 10 secs, 15 secs, 30 secs,
1 min, 2 mins, 5 mins, 10 mins, 15 mins, 30 mins,1 hour, 1 day,
1 week, 1 month, 3 months, 1 year
Parameter 14: What to show. This field specifies what data to show,
such as "TRADES", "MIDPOINT", "BID","ASK","BID/ASK"
Parameter 15: Use real time hours. Set this value to "1" if you want
data only from the real time hours. If you don't care if the data comes from
pre or after market use "0"
Parameter 16: Date format. You have 2 choices in how the data is
returned for each data bar. "1" means the date will be in the format
yyyymmdd{space}{space}hh:mm:dd and "2" means the date will be a timestamp.
Now that we have made a request for historical data to the running
instance of TWS, we need a place to put this data. From the form
designer window add a "List Box" control. You will want to make
this list box kind of wide to display the data correctly. Now go
back into the code view, and add the following function:
Private Sub Tws1_intradayData(ByVal eventSender
As System.Object, ByVal eventArgs As AxTWSLib._DTwsEvents_historicalDataEvent)
Handles Tws1.historicalData
Dim strData As String = ""
strData = "id=" & eventArgs.reqId & " date=" & eventArgs.date &
" open=" & eventArgs.open & " high=" & eventArgs.high & " low="
& eventArgs.low & " close=" & eventArgs.close & " volume=" & eventArgs.volume
ListBox1.Items.Add(strData)
End Sub
The function "Tws1_intradayData" is the function that is called
anytime the program receives either historical or live streaming
data. What we are doing inside this function is looking at the "Event"
that was passed to us which is in the variable eventArgs. We add
all of the data bars to our ListBox that we created a few minutes
ago. If you have TWS running and run this application you should
see the list box populate with data bars. It sometimes takes a minute
for it to populate. If for some reason your list box is not populating
with data, then add this code:
Private Sub Tws1_errMsg(ByVal eventSender
As System.Object, ByVal eventArgs As AxTWSLib._DTwsEvents_errMsgEvent)
Handles Tws1.errMsg
Dim msg As String
msg = "id: " & eventArgs.id & " | Error Code: " & eventArgs.errorCode
& " | Error Msg: " & eventArgs.errorMsg
MessageBox.Show(msg)
End Sub
What this function does is anytime TWS reports an error to you,
it will output it to a message box. You will notice that everytime
on startup TWS reports a few error messages to you. Ignore these.
You are now one step closer to writing a stock bot.
Download the full source for this project Here
Similar tutorials
|