Skip to content

Instantly share code, notes, and snippets.

@anthonyng2
Created August 4, 2017 07:32
Show Gist options
  • Save anthonyng2/c525376bb17c7c388efbdf988adfd121 to your computer and use it in GitHub Desktop.
Save anthonyng2/c525376bb17c7c388efbdf988adfd121 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# IbPy and Interactive Brokers Features Demonstration\n",
"Tested on Python 2\n",
"\n",
"## Learning Outcomes\n",
"At the end of this simple workshop, you will be able to \n",
"1. Extract Account and Portfolio Informatioin\n",
"2. Placing Orders\n",
"3. Request Market Data\n",
"4. Obtain Historical Data\n",
"5. Access Market Depth Informaation\n",
"6. Download Real Time Bars\n",
"7. Extract Executions Information, including commission report"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import warnings\n",
"warnings.filterwarnings('ignore')\n",
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import time\n",
"from datetime import datetime\n",
"from IBWrapper import IBWrapper, contract\n",
"from ib.ext.EClientSocket import EClientSocket\n",
"from ib.ext.ScannerSubscription import ScannerSubscription"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the example to follow, **`callback`** is our `IBWrapper` instantiated. We **receive** information via `callback`.\n",
"\n",
"\n",
"In the example to follow, **`tws`** is our `EClientSocket` instantiated. We **request** information via `tws`"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"accountName = \"DU254946\"\n",
"callback = IBWrapper() # Instantiate IBWrapper. callback \n",
"tws = EClientSocket(callback) # Instantiate EClientSocket and return data to callback\n",
"host = \"\"\n",
"port = 4001\n",
"clientId = 5555"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Server Version: 76\n",
"TWS Time at connection:20160512 15:46:21 SGT\n"
]
}
],
"source": [
"tws.eConnect(host, port, clientId) # Connect to TWS"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.setServerLogLevel(5) # Set error output to verbose"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"create = contract() # Instantiate contract class\n",
"callback.initiate_variables()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note how the work flow goes. We send a request via the prefix **tws.** followed by the request for the specific type of data after the dot for the information we are interested in. \n",
"\n",
"For example, we would like to get an update on account time, which required us calling `reqAccountUpdates`. \n",
"\n",
"We request for info by calling **`tws.reqAccountUpdates`** and the data will be returned via our callback function. In this case **`callback.update_AccountTime`**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Account and Portfolio\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Account Updates\n",
" * Account Value\n",
" * Portfolio\n",
" * Account Time\n",
"2. Account Summary\n",
"3. Positions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Account and Portfolio \n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqAccountUpdates | updateAccountValue | self.update_AccountValue |\n",
"| | updatePortfolio | self.update_Portfolio |\n",
"| | updateAccountTime | self.update_AccountTime |\n",
"| reqAccountSummary | accountSummary | self.account_Summary |\n",
"| reqPositions | position | self.update_Position |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sending Account Updates Request\n",
"`reqAccountUpdates`"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"tws.reqAccountUpdates(1, accountName)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Obtaining Account Value\n",
"`self.update_AccountValue`"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>key</th>\n",
" <th>value</th>\n",
" <th>currency</th>\n",
" <th>accountName</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>AccountType</td>\n",
" <td>INDIVIDUAL</td>\n",
" <td>None</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>AccountCode</td>\n",
" <td>DU254946</td>\n",
" <td>None</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>AccountReady</td>\n",
" <td>true</td>\n",
" <td>None</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" key value currency accountName\n",
"0 AccountType INDIVIDUAL None DU254946\n",
"1 AccountCode DU254946 None DU254946\n",
"2 AccountReady true None DU254946"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.update_AccountValue, \n",
" columns = ['key', 'value', 'currency', 'accountName'])[:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Obtaining Portfolio Value\n",
"`self.update_Portfolio`"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Contract ID</th>\n",
" <th>Currency</th>\n",
" <th>Expiry</th>\n",
" <th>Include Expired</th>\n",
" <th>Local Symbol</th>\n",
" <th>Multiplier</th>\n",
" <th>Primary Exchange</th>\n",
" <th>Right</th>\n",
" <th>Security Type</th>\n",
" <th>Strike</th>\n",
" <th>Symbol</th>\n",
" <th>Trading Class</th>\n",
" <th>Position</th>\n",
" <th>Market Price</th>\n",
" <th>Market Value</th>\n",
" <th>Average Cost</th>\n",
" <th>Unrealised PnL</th>\n",
" <th>Realised PnL</th>\n",
" <th>Account Name</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>215465490</td>\n",
" <td>USD</td>\n",
" <td>20170317</td>\n",
" <td>False</td>\n",
" <td>ESH7</td>\n",
" <td>50</td>\n",
" <td>GLOBEX</td>\n",
" <td>0</td>\n",
" <td>FUT</td>\n",
" <td>0.0</td>\n",
" <td>ES</td>\n",
" <td>ES</td>\n",
" <td>5</td>\n",
" <td>2039.325000</td>\n",
" <td>509831.25</td>\n",
" <td>102324.530000</td>\n",
" <td>-1791.40</td>\n",
" <td>0.0</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>12087792</td>\n",
" <td>USD</td>\n",
" <td>None</td>\n",
" <td>False</td>\n",
" <td>EUR.USD</td>\n",
" <td>None</td>\n",
" <td>IDEALPRO</td>\n",
" <td>0</td>\n",
" <td>CASH</td>\n",
" <td>0.0</td>\n",
" <td>EUR</td>\n",
" <td>EUR.USD</td>\n",
" <td>670000</td>\n",
" <td>1.141020</td>\n",
" <td>764483.44</td>\n",
" <td>1.090984</td>\n",
" <td>33524.48</td>\n",
" <td>0.0</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>15016059</td>\n",
" <td>JPY</td>\n",
" <td>None</td>\n",
" <td>False</td>\n",
" <td>USD.JPY</td>\n",
" <td>None</td>\n",
" <td>IDEALPRO</td>\n",
" <td>0</td>\n",
" <td>CASH</td>\n",
" <td>0.0</td>\n",
" <td>USD</td>\n",
" <td>USD.JPY</td>\n",
" <td>100000</td>\n",
" <td>108.861999</td>\n",
" <td>10886199.95</td>\n",
" <td>118.603250</td>\n",
" <td>-974125.05</td>\n",
" <td>0.0</td>\n",
" <td>DU254946</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Contract ID Currency Expiry Include Expired Local Symbol Multiplier \\\n",
"0 215465490 USD 20170317 False ESH7 50 \n",
"1 12087792 USD None False EUR.USD None \n",
"2 15016059 JPY None False USD.JPY None \n",
"\n",
" Primary Exchange Right Security Type Strike Symbol Trading Class Position \\\n",
"0 GLOBEX 0 FUT 0.0 ES ES 5 \n",
"1 IDEALPRO 0 CASH 0.0 EUR EUR.USD 670000 \n",
"2 IDEALPRO 0 CASH 0.0 USD USD.JPY 100000 \n",
"\n",
" Market Price Market Value Average Cost Unrealised PnL Realised PnL \\\n",
"0 2039.325000 509831.25 102324.530000 -1791.40 0.0 \n",
"1 1.141020 764483.44 1.090984 33524.48 0.0 \n",
"2 108.861999 10886199.95 118.603250 -974125.05 0.0 \n",
"\n",
" Account Name \n",
"0 DU254946 \n",
"1 DU254946 \n",
"2 DU254946 "
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.update_Portfolio, \n",
" columns=['Contract ID','Currency',\n",
" 'Expiry','Include Expired',\n",
" 'Local Symbol','Multiplier',\n",
" 'Primary Exchange','Right',\n",
" 'Security Type','Strike',\n",
" 'Symbol','Trading Class',\n",
" 'Position','Market Price','Market Value',\n",
" 'Average Cost', 'Unrealised PnL', 'Realised PnL', \n",
" 'Account Name'])[:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Obtaining Account Time\n",
"`self.update_AccountTime`"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'15:46'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"callback.update_AccountTime"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sending Account Summary Request\n",
"`reqAccountSummary`\n",
"\n",
"This function call can only be made when connected to a Financial Advisor (FA) account. Another way to look at this is that if you have more than one account, use this function."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.reqAccountSummary(2,\"All\",\"NetLiquidation\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Obtaining Account Summary\n",
"`self.account_Summary`"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Request_ID</th>\n",
" <th>Account</th>\n",
" <th>Tag</th>\n",
" <th>Value</th>\n",
" <th>Curency</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>2</td>\n",
" <td>DI246990</td>\n",
" <td>NetLiquidation</td>\n",
" <td>1032397.94</td>\n",
" <td>USD</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" <td>DU254946</td>\n",
" <td>NetLiquidation</td>\n",
" <td>803830.58</td>\n",
" <td>USD</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Request_ID Account Tag Value Curency\n",
"0 2 DI246990 NetLiquidation 1032397.94 USD\n",
"1 2 DU254946 NetLiquidation 803830.58 USD"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.account_Summary, \n",
" columns = ['Request_ID','Account','Tag','Value','Curency'])[:2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sending Position Request\n",
"`reqPositions`\n",
"\n",
"This function call request all positions for all accounts. This is more suitable for Financial Advisor. In the following example, I used pandas selection criteria to disply a specific account position."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.reqPositions()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Obtaining Position\n",
"`self.update_Position`"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Account</th>\n",
" <th>Contract ID</th>\n",
" <th>Currency</th>\n",
" <th>Exchange</th>\n",
" <th>Expiry</th>\n",
" <th>Include Expired</th>\n",
" <th>Local Symbol</th>\n",
" <th>Multiplier</th>\n",
" <th>Right</th>\n",
" <th>Security Type</th>\n",
" <th>Strike</th>\n",
" <th>Symbol</th>\n",
" <th>Trading Class</th>\n",
" <th>Position</th>\n",
" <th>Average Cost</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>67</th>\n",
" <td>DU254946</td>\n",
" <td>215465490</td>\n",
" <td>USD</td>\n",
" <td>None</td>\n",
" <td>20170317</td>\n",
" <td>False</td>\n",
" <td>ESH7</td>\n",
" <td>50</td>\n",
" <td>None</td>\n",
" <td>FUT</td>\n",
" <td>0.0</td>\n",
" <td>ES</td>\n",
" <td>ES</td>\n",
" <td>5</td>\n",
" <td>102324.530000</td>\n",
" </tr>\n",
" <tr>\n",
" <th>68</th>\n",
" <td>DU254946</td>\n",
" <td>12087792</td>\n",
" <td>USD</td>\n",
" <td>None</td>\n",
" <td>None</td>\n",
" <td>False</td>\n",
" <td>EUR.USD</td>\n",
" <td>None</td>\n",
" <td>None</td>\n",
" <td>CASH</td>\n",
" <td>0.0</td>\n",
" <td>EUR</td>\n",
" <td>EUR.USD</td>\n",
" <td>670000</td>\n",
" <td>1.090984</td>\n",
" </tr>\n",
" <tr>\n",
" <th>69</th>\n",
" <td>DU254946</td>\n",
" <td>15016059</td>\n",
" <td>JPY</td>\n",
" <td>None</td>\n",
" <td>None</td>\n",
" <td>False</td>\n",
" <td>USD.JPY</td>\n",
" <td>None</td>\n",
" <td>None</td>\n",
" <td>CASH</td>\n",
" <td>0.0</td>\n",
" <td>USD</td>\n",
" <td>USD.JPY</td>\n",
" <td>100000</td>\n",
" <td>118.603250</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Account Contract ID Currency Exchange Expiry Include Expired \\\n",
"67 DU254946 215465490 USD None 20170317 False \n",
"68 DU254946 12087792 USD None None False \n",
"69 DU254946 15016059 JPY None None False \n",
"\n",
" Local Symbol Multiplier Right Security Type Strike Symbol Trading Class \\\n",
"67 ESH7 50 None FUT 0.0 ES ES \n",
"68 EUR.USD None None CASH 0.0 EUR EUR.USD \n",
"69 USD.JPY None None CASH 0.0 USD USD.JPY \n",
"\n",
" Position Average Cost \n",
"67 5 102324.530000 \n",
"68 670000 1.090984 \n",
"69 100000 118.603250 "
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dat = pd.DataFrame(callback.update_Position, \n",
" columns=['Account','Contract ID','Currency','Exchange','Expiry',\n",
" 'Include Expired','Local Symbol','Multiplier','Right',\n",
" 'Security Type','Strike','Symbol','Trading Class',\n",
" 'Position','Average Cost'])\n",
"dat[dat[\"Account\"] == accountName]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Orders\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Open Order\n",
"2. Next Valid ID\n",
"3. Order Status"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Orders\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqIds | nextValidId | self.next_ValidId |\n",
"| placeOrder | orderStatus | self.order_Status |\n",
"| cancelOrder | | |\n",
"| reqOpenOrders & reqAllOpenOrders | openOrder | self.open_Order |\n",
"| | orderStatus | self.order_Status |\n",
"| reqGlobalCancel | | |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Demo - Stock Purchase\n",
"* ** Request Next Valid Id**. `reqIds`\n",
"* ** Using Create**. `create`"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.reqIds(1)\n",
"order_id = callback.next_ValidId + 1\n",
"contract_info = create.create_contract(\"GOOG\", \"STK\", \"SMART\", \"USD\")\n",
"order_info = create.create_order(accountName, \"MKT\", 100, \"BUY\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Placing an Order\n",
"`placeOrder`"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.placeOrder(order_id, contract_info, order_info)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Checking Order Status\n",
"`self.order_Status`"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 399, 'Order Message:\\nBUY 100 GOOG NASDAQ.NMS\\nWarning: your order will not be placed at the exchange until 2016-05-12 09:30:00 US/Eastern']\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>orderId</th>\n",
" <th>status</th>\n",
" <th>filled</th>\n",
" <th>remaining</th>\n",
" <th>avgFillPrice</th>\n",
" <th>permId</th>\n",
" <th>parentId</th>\n",
" <th>lastFillPrice</th>\n",
" <th>clientId</th>\n",
" <th>whyHeld</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>2</td>\n",
" <td>PreSubmitted</td>\n",
" <td>0</td>\n",
" <td>100</td>\n",
" <td>0.0</td>\n",
" <td>2119447479</td>\n",
" <td>0</td>\n",
" <td>0.0</td>\n",
" <td>5555</td>\n",
" <td>None</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" orderId status filled remaining avgFillPrice permId \\\n",
"0 2 PreSubmitted 0 100 0.0 2119447479 \n",
"\n",
" parentId lastFillPrice clientId whyHeld \n",
"0 0 0.0 5555 None "
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.order_Status,\n",
" columns = ['orderId', 'status', 'filled', 'remaining', 'avgFillPrice',\n",
" 'permId', 'parentId', 'lastFillPrice', 'clientId', 'whyHeld'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Checking on Open Order\n",
"`self.open_Order`"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(2,\n",
" <ib.ext.Contract.Contract at 0x8a98c88>,\n",
" <ib.ext.Order.Order at 0x89fb208>,\n",
" <ib.ext.OrderState.OrderState at 0x8a98940>)]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"callback.open_Order[:1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Cancelling Open Order\n",
"`cancelOrder`"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.cancelOrder(order_id)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Demo\n",
"* ** Request Next Valid Id**. `reqIds`\n",
"* ** Using Create**. `create`\n",
"* ** Placing an Order to purchase Futures**. `placeOrder`"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 202, 'Order Canceled - reason:']\n"
]
}
],
"source": [
"tws.reqIds(1)\n",
"order_id = callback.next_ValidId + 1\n",
"contract_info = create.create_contract(symbol = \"ES\", secType = \"FUT\", \n",
" exchange = \"GLOBEX\", currency = \"USD\", \n",
" right = None, strike = None,\n",
" expiry = \"201703\", multiplier=None,\n",
" tradingClass=None)\n",
"order_info = create.create_order(accountName, \"MKT\", 1, \"BUY\")\n",
"tws.placeOrder(order_id, contract_info, order_info)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Checking Order Status"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 104, \"Can't modify a filled order\"]\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>orderId</th>\n",
" <th>status</th>\n",
" <th>filled</th>\n",
" <th>remaining</th>\n",
" <th>avgFillPrice</th>\n",
" <th>permId</th>\n",
" <th>parentId</th>\n",
" <th>lastFillPrice</th>\n",
" <th>clientId</th>\n",
" <th>whyHeld</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>2</td>\n",
" <td>PreSubmitted</td>\n",
" <td>0</td>\n",
" <td>100</td>\n",
" <td>0.0</td>\n",
" <td>2119447479</td>\n",
" <td>0</td>\n",
" <td>0.0</td>\n",
" <td>5555</td>\n",
" <td>None</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>2</td>\n",
" <td>PendingCancel</td>\n",
" <td>0</td>\n",
" <td>100</td>\n",
" <td>0.0</td>\n",
" <td>2119447479</td>\n",
" <td>0</td>\n",
" <td>0.0</td>\n",
" <td>5555</td>\n",
" <td>None</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>2</td>\n",
" <td>Cancelled</td>\n",
" <td>0</td>\n",
" <td>100</td>\n",
" <td>0.0</td>\n",
" <td>2119447479</td>\n",
" <td>0</td>\n",
" <td>0.0</td>\n",
" <td>5555</td>\n",
" <td>None</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" orderId status filled remaining avgFillPrice permId \\\n",
"0 2 PreSubmitted 0 100 0.0 2119447479 \n",
"1 2 PendingCancel 0 100 0.0 2119447479 \n",
"2 2 Cancelled 0 100 0.0 2119447479 \n",
"\n",
" parentId lastFillPrice clientId whyHeld \n",
"0 0 0.0 5555 None \n",
"1 0 0.0 5555 None \n",
"2 0 0.0 5555 None "
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.order_Status,\n",
" columns = ['orderId', 'status', 'filled', 'remaining', 'avgFillPrice',\n",
" 'permId', 'parentId', 'lastFillPrice', 'clientId', 'whyHeld'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"IB provided two more methods:\n",
"* `reqOpenOrders()` to request any open orders that were placed from this API client.\n",
"* `reqAllOpenOrders()` to request all open orders that were placed from all API clients linked to one TWS and also from the TWS.\n",
"\n",
"Each open order will be fed back through `openOrder()` and `orderStatus()` methods."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, use `reqGlobalCancel()` to cancel all open orders globally."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# Market Data\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Request Market Data\n",
" * Tick Price\n",
" * Tick Size\n",
"2. Cancel Market Data\n",
"3. Calculate Implied Volatility\n",
"4. Calculate Option Price"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Market Data\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqMktData | tickPrice | self.tick_Price |\n",
"| | tickSize | self.tick_Size |\n",
"| | tickOptionComputation | self.tick_OptionComputation |\n",
"| | tickGeneric | self.tick_Generic |\n",
"| | tickString | self.tick_String |\n",
"| | tickEFP | self.tick_EFP |\n",
"| | tickSnapshotEnd | self.tickSnapshotEnd_flag |\n",
"| cancelMktData | | |\n",
"| calculateImpliedVolatility | tickOptionComputation | self.tick_OptionComputation |\n",
"| cancelcalculateImpliedVolatility | | |\n",
"| calculateOptionPrice | tickOptionComputation | self.tick_OptionComputation |\n",
"| cancelCalculateOptionPrice | | |\n",
"| reqMktDataType | marketDataType | self.market_DataType |\n",
"\n",
"The method `reqMktDataType` allows you to toggle between receiving real-time or frozen market data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Requesting Market Data\n",
"`reqMktData`"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2119, 'Market data farm is connecting:cashfarm']\n",
"[-1, 2104, 'Market data farm connection is OK:cashfarm']\n"
]
}
],
"source": [
"contract_info = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')\n",
"tickedId = 1002\n",
"tws.reqMktData(tickedId, contract_info, \"\", False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Receiving Tick Price\n",
"`self.tick_Price`"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>tickerId</th>\n",
" <th>field</th>\n",
" <th>price</th>\n",
" <th>canAutoExecute</th>\n",
" <th>Type</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1002</td>\n",
" <td>6</td>\n",
" <td>1.14295</td>\n",
" <td>0</td>\n",
" <td>HIGH</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>1002</td>\n",
" <td>7</td>\n",
" <td>1.14050</td>\n",
" <td>0</td>\n",
" <td>LOW</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>1002</td>\n",
" <td>9</td>\n",
" <td>1.14270</td>\n",
" <td>0</td>\n",
" <td>CLOSE PRICE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>1002</td>\n",
" <td>1</td>\n",
" <td>1.14105</td>\n",
" <td>1</td>\n",
" <td>BID PRICE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>1002</td>\n",
" <td>2</td>\n",
" <td>1.14110</td>\n",
" <td>1</td>\n",
" <td>ASK PRICE</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tickerId field price canAutoExecute Type\n",
"0 1002 6 1.14295 0 HIGH\n",
"1 1002 7 1.14050 0 LOW\n",
"2 1002 9 1.14270 0 CLOSE PRICE\n",
"3 1002 1 1.14105 1 BID PRICE\n",
"4 1002 2 1.14110 1 ASK PRICE"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tick_data = pd.DataFrame(callback.tick_Price, \n",
" columns = ['tickerId', 'field', 'price', 'canAutoExecute'])\n",
"tick_type = {0 : \"BID SIZE\",\n",
" 1 : \"BID PRICE\",\n",
" 2 : \"ASK PRICE\",\n",
" 3 : \"ASK SIZE\",\n",
" 4 : \"LAST PRICE\",\n",
" 5 : \"LAST SIZE\",\n",
" 6 : \"HIGH\",\n",
" 7 : \"LOW\",\n",
" 8 : \"VOLUME\",\n",
" 9 : \"CLOSE PRICE\",\n",
" 10 : \"BID OPTION COMPUTATION\",\n",
" 11 : \"ASK OPTION COMPUTATION\",\n",
" 12 : \"LAST OPTION COMPUTATION\",\n",
" 13 : \"MODEL OPTION COMPUTATION\",\n",
" 14 : \"OPEN_TICK\",\n",
" 15 : \"LOW 13 WEEK\",\n",
" 16 : \"HIGH 13 WEEK\",\n",
" 17 : \"LOW 26 WEEK\",\n",
" 18 : \"HIGH 26 WEEK\",\n",
" 19 : \"LOW 52 WEEK\",\n",
" 20 : \"HIGH 52 WEEK\",\n",
" 21 : \"AVG VOLUME\",\n",
" 22 : \"OPEN INTEREST\",\n",
" 23 : \"OPTION HISTORICAL VOL\",\n",
" 24 : \"OPTION IMPLIED VOL\",\n",
" 27 : \"OPTION CALL OPEN INTEREST\",\n",
" 28 : \"OPTION PUT OPEN INTEREST\",\n",
" 29 : \"OPTION CALL VOLUME\"}\n",
"tick_data[\"Type\"] = tick_data[\"field\"].map(tick_type)\n",
"tick_data[-10:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Receiving Tick Size\n",
"`self.tick_Size`"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>tickerId</th>\n",
" <th>field</th>\n",
" <th>size</th>\n",
" <th>Type</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>49</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>15605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>50</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>14605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>51</th>\n",
" <td>1002</td>\n",
" <td>3</td>\n",
" <td>1000000</td>\n",
" <td>ASK SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>52</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>17605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>53</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>14605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>54</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>16605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>55</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>17605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>56</th>\n",
" <td>1002</td>\n",
" <td>3</td>\n",
" <td>18350000</td>\n",
" <td>ASK SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>57</th>\n",
" <td>1002</td>\n",
" <td>3</td>\n",
" <td>18350000</td>\n",
" <td>ASK SIZE</td>\n",
" </tr>\n",
" <tr>\n",
" <th>58</th>\n",
" <td>1002</td>\n",
" <td>0</td>\n",
" <td>18605000</td>\n",
" <td>BID SIZE</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tickerId field size Type\n",
"49 1002 0 15605000 BID SIZE\n",
"50 1002 0 14605000 BID SIZE\n",
"51 1002 3 1000000 ASK SIZE\n",
"52 1002 0 17605000 BID SIZE\n",
"53 1002 0 14605000 BID SIZE\n",
"54 1002 0 16605000 BID SIZE\n",
"55 1002 0 17605000 BID SIZE\n",
"56 1002 3 18350000 ASK SIZE\n",
"57 1002 3 18350000 ASK SIZE\n",
"58 1002 0 18605000 BID SIZE"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tick_data = pd.DataFrame(callback.tick_Size, \n",
" columns = [\"tickerId\", \"field\", \"size\"])\n",
"tick_data[\"Type\"] = tick_data[\"field\"].map(tick_type)\n",
"tick_data[-10:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Calculate Implied Volatility\n",
"`calculateImpliedVolatility`"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"contract_info = create.create_contract(symbol='NFLX 160819C00095000',\n",
" secType='OPT', exchange='SMART', \n",
" currency='USD',\n",
" right='CALL', \n",
" strike='95', \n",
" expiry='20160819',\n",
" multiplier=100, \n",
" tradingClass=\"NFLX\")\n",
"tws.calculateImpliedVolatility(tickedId, \n",
" contract_info, \n",
" 5.89, \n",
" 89.91)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>tickerId</th>\n",
" <th>field</th>\n",
" <th>impliedVol</th>\n",
" <th>delta</th>\n",
" <th>optPrice</th>\n",
" <th>pvDividend</th>\n",
" <th>gamma</th>\n",
" <th>vega</th>\n",
" <th>theta</th>\n",
" <th>undPrice</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1002</td>\n",
" <td>53</td>\n",
" <td>0.425206</td>\n",
" <td>2147483647</td>\n",
" <td>5.89</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>89.91</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tickerId field impliedVol delta optPrice pvDividend gamma \\\n",
"0 1002 53 0.425206 2147483647 5.89 2147483647 2147483647 \n",
"\n",
" vega theta undPrice \n",
"0 2147483647 2147483647 89.91 "
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.tick_OptionComputation,\n",
" columns=[\"tickerId\", \"field\", \"impliedVol\", \"delta\",\n",
" \"optPrice\", \"pvDividend\", \"gamma\", \"vega\",\n",
" \"theta\", \"undPrice\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Calculate Option Price\n",
"`tick_OptionComputation`"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"tws.calculateOptionPrice(tickedId, \n",
" contract_info, \n",
" 0.84, \n",
" 89.91)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2119, 'Market data farm is connecting:usopt']\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>tickerId</th>\n",
" <th>field</th>\n",
" <th>impliedVol</th>\n",
" <th>delta</th>\n",
" <th>optPrice</th>\n",
" <th>pvDividend</th>\n",
" <th>gamma</th>\n",
" <th>vega</th>\n",
" <th>theta</th>\n",
" <th>undPrice</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1002</td>\n",
" <td>53</td>\n",
" <td>0.425206</td>\n",
" <td>2147483647</td>\n",
" <td>5.89</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>2147483647</td>\n",
" <td>89.91</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tickerId field impliedVol delta optPrice pvDividend gamma \\\n",
"0 1002 53 0.425206 2147483647 5.89 2147483647 2147483647 \n",
"\n",
" vega theta undPrice \n",
"0 2147483647 2147483647 89.91 "
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.tick_OptionComputation,\n",
" columns=[\"tickerId\", \"field\", \"impliedVol\", \"delta\",\n",
" \"optPrice\", \"pvDividend\", \"gamma\", \"vega\",\n",
" \"theta\", \"undPrice\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Cancelling Market Data Stream\n",
"`cancelMktData`"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2104, 'Market data farm connection is OK:usopt']\n"
]
}
],
"source": [
"tws.cancelMktData(tickedId)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Historical Data\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Historical Data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Historical Data\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqHistoricalData | historicalData | self.historical_Data |"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2108, 'Market data farm connection is inactive but should be available upon demand.cashfarm']\n",
"[-1, 2108, 'Market data farm connection is inactive but should be available upon demand.cashfarm']\n"
]
}
],
"source": [
"#contract_Details = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')\n",
"contract_Details = create.create_contract('AAPL', 'STK', 'SMART', 'USD')"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"data_endtime = datetime.now().strftime(\"%Y%m%d %H:%M:%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Requesting Historical Data\n",
"`reqHistoricalData`"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tickerId = 9002\n",
"tws.reqHistoricalData(tickerId, \n",
" contract_Details, \n",
" data_endtime,\n",
" \"1 M\", \n",
" \"1 day\", \n",
" \"BID\", \n",
" 0, \n",
" 1)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>reqId</th>\n",
" <th>date</th>\n",
" <th>open</th>\n",
" <th>high</th>\n",
" <th>low</th>\n",
" <th>close</th>\n",
" <th>volume</th>\n",
" <th>count</th>\n",
" <th>WAP</th>\n",
" <th>hasGaps</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>13</th>\n",
" <td>9002</td>\n",
" <td>20160429</td>\n",
" <td>94.45</td>\n",
" <td>94.95</td>\n",
" <td>92.51</td>\n",
" <td>93.60</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>14</th>\n",
" <td>9002</td>\n",
" <td>20160502</td>\n",
" <td>93.75</td>\n",
" <td>94.30</td>\n",
" <td>92.40</td>\n",
" <td>93.81</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>15</th>\n",
" <td>9002</td>\n",
" <td>20160503</td>\n",
" <td>93.50</td>\n",
" <td>95.73</td>\n",
" <td>93.01</td>\n",
" <td>95.12</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>16</th>\n",
" <td>9002</td>\n",
" <td>20160504</td>\n",
" <td>95.23</td>\n",
" <td>95.88</td>\n",
" <td>93.82</td>\n",
" <td>94.36</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>17</th>\n",
" <td>9002</td>\n",
" <td>20160505</td>\n",
" <td>1.00</td>\n",
" <td>94.37</td>\n",
" <td>1.00</td>\n",
" <td>93.12</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>18</th>\n",
" <td>9002</td>\n",
" <td>20160506</td>\n",
" <td>89.80</td>\n",
" <td>93.48</td>\n",
" <td>89.80</td>\n",
" <td>92.67</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>19</th>\n",
" <td>9002</td>\n",
" <td>20160509</td>\n",
" <td>89.80</td>\n",
" <td>93.76</td>\n",
" <td>89.80</td>\n",
" <td>92.61</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>20</th>\n",
" <td>9002</td>\n",
" <td>20160510</td>\n",
" <td>89.80</td>\n",
" <td>93.57</td>\n",
" <td>89.80</td>\n",
" <td>93.26</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>21</th>\n",
" <td>9002</td>\n",
" <td>20160511</td>\n",
" <td>92.50</td>\n",
" <td>93.56</td>\n",
" <td>92.25</td>\n",
" <td>92.34</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" <tr>\n",
" <th>22</th>\n",
" <td>9002</td>\n",
" <td>finished-20160412 15:43:47-20160512 15:43:47</td>\n",
" <td>-1.00</td>\n",
" <td>-1.00</td>\n",
" <td>-1.00</td>\n",
" <td>-1.00</td>\n",
" <td>-1</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>False</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" reqId date open high \\\n",
"13 9002 20160429 94.45 94.95 \n",
"14 9002 20160502 93.75 94.30 \n",
"15 9002 20160503 93.50 95.73 \n",
"16 9002 20160504 95.23 95.88 \n",
"17 9002 20160505 1.00 94.37 \n",
"18 9002 20160506 89.80 93.48 \n",
"19 9002 20160509 89.80 93.76 \n",
"20 9002 20160510 89.80 93.57 \n",
"21 9002 20160511 92.50 93.56 \n",
"22 9002 finished-20160412 15:43:47-20160512 15:43:47 -1.00 -1.00 \n",
"\n",
" low close volume count WAP hasGaps \n",
"13 92.51 93.60 -1 -1 -1.0 False \n",
"14 92.40 93.81 -1 -1 -1.0 False \n",
"15 93.01 95.12 -1 -1 -1.0 False \n",
"16 93.82 94.36 -1 -1 -1.0 False \n",
"17 1.00 93.12 -1 -1 -1.0 False \n",
"18 89.80 92.67 -1 -1 -1.0 False \n",
"19 89.80 92.61 -1 -1 -1.0 False \n",
"20 89.80 93.26 -1 -1 -1.0 False \n",
"21 92.25 92.34 -1 -1 -1.0 False \n",
"22 -1.00 -1.00 -1 -1 -1.0 False "
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data= pd.DataFrame(callback.historical_Data, \n",
" columns = [\"reqId\", \"date\", \"open\",\n",
" \"high\", \"low\", \"close\", \n",
" \"volume\", \"count\", \"WAP\", \n",
" \"hasGaps\"])\n",
"data[-10:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Market Depth\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Request Market Depth"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Market Depth\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqMktDepth | updateMktDepth | self.update_MktDepth |"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"contract_info = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tickerId = 7000\n",
"tws.reqMktDepth(tickerId, contract_info, 5)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2119, 'Market data farm is connecting:cashfarm']\n"
]
}
],
"source": [
"operation_type = {0 : \"Insert\",\n",
" 1 : \"Update\",\n",
" 2 : \"Delete\",}\n",
"side_type = {0 : \"Ask\",\n",
" 1 : \"Bid\"}"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-1, 2104, 'Market data farm connection is OK:cashfarm']\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>tickerId</th>\n",
" <th>position</th>\n",
" <th>operation</th>\n",
" <th>side</th>\n",
" <th>price</th>\n",
" <th>size</th>\n",
" <th>operation_type</th>\n",
" <th>side_type</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>70</th>\n",
" <td>7000</td>\n",
" <td>3</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1.14120</td>\n",
" <td>1040000</td>\n",
" <td>Update</td>\n",
" <td>Ask</td>\n",
" </tr>\n",
" <tr>\n",
" <th>71</th>\n",
" <td>7000</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1.14095</td>\n",
" <td>17605000</td>\n",
" <td>Update</td>\n",
" <td>Bid</td>\n",
" </tr>\n",
" <tr>\n",
" <th>72</th>\n",
" <td>7000</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1.14105</td>\n",
" <td>17175000</td>\n",
" <td>Update</td>\n",
" <td>Ask</td>\n",
" </tr>\n",
" <tr>\n",
" <th>73</th>\n",
" <td>7000</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1.14095</td>\n",
" <td>17430000</td>\n",
" <td>Update</td>\n",
" <td>Bid</td>\n",
" </tr>\n",
" <tr>\n",
" <th>74</th>\n",
" <td>7000</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1.14095</td>\n",
" <td>16430000</td>\n",
" <td>Update</td>\n",
" <td>Bid</td>\n",
" </tr>\n",
" <tr>\n",
" <th>75</th>\n",
" <td>7000</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1.14105</td>\n",
" <td>16175000</td>\n",
" <td>Update</td>\n",
" <td>Ask</td>\n",
" </tr>\n",
" <tr>\n",
" <th>76</th>\n",
" <td>7000</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1.14095</td>\n",
" <td>17430000</td>\n",
" <td>Update</td>\n",
" <td>Bid</td>\n",
" </tr>\n",
" <tr>\n",
" <th>77</th>\n",
" <td>7000</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1.14105</td>\n",
" <td>17175000</td>\n",
" <td>Update</td>\n",
" <td>Ask</td>\n",
" </tr>\n",
" <tr>\n",
" <th>78</th>\n",
" <td>7000</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>1.14095</td>\n",
" <td>16430000</td>\n",
" <td>Update</td>\n",
" <td>Bid</td>\n",
" </tr>\n",
" <tr>\n",
" <th>79</th>\n",
" <td>7000</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1.14105</td>\n",
" <td>16175000</td>\n",
" <td>Update</td>\n",
" <td>Ask</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" tickerId position operation side price size operation_type \\\n",
"70 7000 3 1 0 1.14120 1040000 Update \n",
"71 7000 0 1 1 1.14095 17605000 Update \n",
"72 7000 1 1 0 1.14105 17175000 Update \n",
"73 7000 0 1 1 1.14095 17430000 Update \n",
"74 7000 0 1 1 1.14095 16430000 Update \n",
"75 7000 1 1 0 1.14105 16175000 Update \n",
"76 7000 0 1 1 1.14095 17430000 Update \n",
"77 7000 1 1 0 1.14105 17175000 Update \n",
"78 7000 0 1 1 1.14095 16430000 Update \n",
"79 7000 1 1 0 1.14105 16175000 Update \n",
"\n",
" side_type \n",
"70 Ask \n",
"71 Bid \n",
"72 Ask \n",
"73 Bid \n",
"74 Bid \n",
"75 Ask \n",
"76 Bid \n",
"77 Ask \n",
"78 Bid \n",
"79 Ask "
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data_mktdepth = pd.DataFrame(callback.update_MktDepth,\n",
" columns = [\"tickerId\", \"position\", \n",
" \"operation\", \"side\", \n",
" \"price\", \"size\"])\n",
"data_mktdepth[\"operation_type\"] = data_mktdepth[\"operation\"].map(operation_type)\n",
"data_mktdepth[\"side_type\"] = data_mktdepth[\"side\"].map(side_type)\n",
"data_mktdepth[-10:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Real Time Bars\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Request Real Time Bars\n",
"\n",
"Note:\n",
"* **barSize**. Only 5 sec bars are supported. \n",
"* **whatToShow**:\n",
" * TRADES\n",
" * BID\n",
" * ASK\n",
" * MIDPOINT\n",
"* **useRTH**:\n",
" * 0 = all data\n",
" * 1 = only data within **R**egular **T**rading **H**ours"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Real Time Bars\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqRealTimeBars | realtimeBar | self.real_timeBar |"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"contract_Details = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"tickerId = 10000\n",
"tws.reqRealTimeBars(tickerId, \n",
" contract_Details, \n",
" 5, \n",
" \"MIDPOINT\", \n",
" 0)"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>reqId</th>\n",
" <th>time</th>\n",
" <th>open</th>\n",
" <th>high</th>\n",
" <th>low</th>\n",
" <th>close</th>\n",
" <th>volume</th>\n",
" <th>wap</th>\n",
" <th>count</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>10000</td>\n",
" <td>1463039280</td>\n",
" <td>1.140975</td>\n",
" <td>1.141025</td>\n",
" <td>1.140975</td>\n",
" <td>1.140975</td>\n",
" <td>-1</td>\n",
" <td>-1.0</td>\n",
" <td>-1</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" reqId time open high low close volume wap \\\n",
"0 10000 1463039280 1.140975 1.141025 1.140975 1.140975 -1 -1.0 \n",
"\n",
" count \n",
"0 -1 "
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.real_timeBar, \n",
" columns = [\"reqId\", \"time\", \"open\", \"high\", \"low\", \"close\", \"volume\", \"wap\", \"count\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*****"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Executions\n",
"### Learning Outcomes\n",
"For this section, you will learn how you can obtain the following information:\n",
"1. Request Executions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary of Executions\n",
"\n",
"| Request Call | Functions Utilised | Data Stored in |\n",
"| --- | --- | --- |\n",
"| reqExecutions | execDetails | self.exec_Details_reqId |\n",
"| | | self.exec_Details_contract |\n",
"| | | self.exec_Details_execution |\n",
"| | execDetailsEnd |self.exec_DetailsEnd_flag |\n",
"| | commissionReport | self.commission_Report |"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.reqIds(1)\n",
"order_id = callback.next_ValidId + 1\n",
"contract_info = create.create_contract(symbol = \"ES\", secType = \"FUT\", \n",
" exchange = \"GLOBEX\", currency = \"USD\", \n",
" right = None, strike = None,\n",
" expiry = \"201703\", multiplier=None,\n",
" tradingClass=None)\n",
"order_info = create.create_order(accountName, \"MKT\", 1, \"BUY\")\n",
"tws.placeOrder(order_id, contract_info, order_info)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"tws.reqExecutions(3050, create.exec_filter(clientId, accountName, contract_info))"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"3050"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"callback.exec_Details_reqId"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'m_conId': 215465490,\n",
" 'm_currency': 'USD',\n",
" 'm_exchange': 'GLOBEX',\n",
" 'm_expiry': '20170317',\n",
" 'm_includeExpired': False,\n",
" 'm_localSymbol': 'ESH7',\n",
" 'm_multiplier': '50',\n",
" 'm_right': None,\n",
" 'm_secType': 'FUT',\n",
" 'm_strike': 0.0,\n",
" 'm_symbol': 'ES',\n",
" 'm_tradingClass': 'ES'}"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"callback.exec_Details_contract.__dict__"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'m_acctNumber': 'DU254946',\n",
" 'm_avgPrice': 2045.5,\n",
" 'm_clientId': 5555,\n",
" 'm_cumQty': 1,\n",
" 'm_evMultiplier': 0,\n",
" 'm_evRule': None,\n",
" 'm_exchange': 'GLOBEX',\n",
" 'm_execId': '0001f4e5.5733bba7.01.01',\n",
" 'm_liquidation': 0,\n",
" 'm_orderId': 4,\n",
" 'm_orderRef': None,\n",
" 'm_permId': 2119447480,\n",
" 'm_price': 2045.5,\n",
" 'm_shares': 1,\n",
" 'm_side': 'BOT',\n",
" 'm_time': '20160512 15:48:14'}"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"callback.exec_Details_execution.__dict__"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>m_commission</th>\n",
" <th>m_currency</th>\n",
" <th>m_execId</th>\n",
" <th>m_realizedPNL</th>\n",
" <th>m_yield</th>\n",
" <th>m_yieldRedemptionDate</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>2.03</td>\n",
" <td>USD</td>\n",
" <td>0001f4e5.5733bba7.01.01</td>\n",
" <td>1.797693e+308</td>\n",
" <td>1.797693e+308</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" m_commission m_currency m_execId m_realizedPNL \\\n",
"0 2.03 USD 0001f4e5.5733bba7.01.01 1.797693e+308 \n",
"\n",
" m_yield m_yieldRedemptionDate \n",
"0 1.797693e+308 0 "
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame(callback.commission_Report.__dict__, index=[0])"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tws.eDisconnect()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.11"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment