{ "cells": [ { "cell_type": "code", "execution_count": 13, "id": "69d88f26-f288-4a23-8be5-3e8317e23731", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "ERROR -1 2104 Market data farm connection is OK:usfarm.nj\n", "ERROR -1 2104 Market data farm connection is OK:usfuture\n", "ERROR -1 2104 Market data farm connection is OK:cashfarm\n", "ERROR -1 2104 Market data farm connection is OK:usfarm\n", "ERROR -1 2106 HMDS data farm connection is OK:ushmds\n", "ERROR -1 2158 Sec-def data farm connection is OK:secdefnj\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Historical Data Ended\n", " Date Open High Low Close Volume\n", "0 20241030 18:00:00 69.10 69.10 68.96 69.02 378\n", "1 20241030 18:05:00 69.02 69.07 69.01 69.05 99\n", "2 20241030 18:10:00 69.06 69.07 69.01 69.01 103\n", "3 20241030 18:15:00 69.01 69.02 69.00 69.00 54\n", "4 20241030 18:20:00 69.01 69.01 68.99 69.00 25\n", "5 20241030 18:25:00 69.00 69.05 69.00 69.04 40\n", "6 20241030 18:30:00 69.05 69.05 69.03 69.03 63\n", "7 20241030 18:35:00 69.03 69.03 69.00 69.00 64\n", "8 20241030 18:40:00 68.99 69.01 68.98 68.99 60\n", "9 20241030 18:45:00 68.99 68.99 68.95 68.97 66\n", "10 20241030 18:50:00 68.97 69.00 68.96 68.99 44\n", "11 20241030 18:55:00 68.98 68.98 68.97 68.98 23\n", "12 20241030 19:00:00 68.98 69.02 68.98 69.01 48\n", "13 20241030 19:05:00 69.02 69.03 69.00 69.01 31\n", "14 20241030 19:10:00 69.02 69.02 69.00 69.00 22\n", "15 20241030 19:15:00 69.00 69.00 68.99 68.99 11\n", "16 20241030 19:20:00 68.99 68.99 68.95 68.95 40\n", "17 20241030 19:25:00 68.95 68.95 68.94 68.94 55\n", "18 20241030 19:30:00 68.94 68.96 68.93 68.95 54\n", "19 20241030 19:35:00 68.95 68.97 68.95 68.96 29\n", "20 20241030 19:40:00 68.96 68.98 68.96 68.98 47\n", "21 20241030 19:45:00 68.98 68.99 68.95 68.95 65\n", "22 20241030 19:50:00 68.96 68.98 68.96 68.97 16\n", "23 20241030 19:55:00 68.97 68.97 68.94 68.94 35\n", "24 20241030 20:00:00 68.95 68.99 68.91 68.92 369\n", "25 20241030 20:05:00 68.91 68.94 68.91 68.93 74\n", "26 20241030 20:10:00 68.93 68.95 68.89 68.94 187\n", "27 20241030 20:15:00 68.94 68.95 68.92 68.94 81\n", "28 20241030 20:20:00 68.95 68.97 68.94 68.96 89\n", "29 20241030 20:25:00 68.96 68.96 68.92 68.94 96\n", "30 20241030 20:30:00 68.94 68.98 68.93 68.96 94\n", "31 20241030 20:35:00 68.97 68.97 68.93 68.94 66\n", "32 20241030 20:40:00 68.95 68.95 68.93 68.94 44\n", "33 20241030 20:45:00 68.93 68.96 68.93 68.94 98\n", "34 20241030 20:50:00 68.94 68.94 68.92 68.92 95\n" ] } ], "source": [ "from ibapi.client import EClient\n", "from ibapi.wrapper import EWrapper\n", "from ibapi.contract import Contract\n", "import threading\n", "import time\n", "import pandas as pd\n", "\n", "# Define the IB API app\n", "class IBApi(EWrapper, EClient):\n", " def __init__(self):\n", " EClient.__init__(self, self)\n", " self.data = [] # Initialize an empty list to store data\n", "\n", " # Override the historicalData function to process and store incoming data\n", " def historicalData(self, reqId, bar):\n", " # Append the data as a dictionary to self.data\n", " self.data.append({\n", " \"Date\": bar.date,\n", " \"Open\": bar.open,\n", " \"High\": bar.high,\n", " \"Low\": bar.low,\n", " \"Close\": bar.close,\n", " \"Volume\": bar.volume\n", " })\n", "\n", " def historicalDataEnd(self, reqId, start, end):\n", " print(\"Historical Data Ended\")\n", " # Convert the data to a DataFrame when data collection is complete\n", " self.df = pd.DataFrame(self.data)\n", " print(self.df) # Display the DataFrame to verify\n", " self.disconnect() # Disconnect after data collection is complete\n", "\n", "# Define the app handler for running in the notebook\n", "class IBApp:\n", " def __init__(self):\n", " self.app = IBApi()\n", "\n", " def connect(self):\n", " self.app.connect(\"127.0.0.1\", 7496, 0) # Change port if needed\n", " thread = threading.Thread(target=self.run_app, daemon=True)\n", " thread.start()\n", " time.sleep(1) # Allow time for the connection to establish\n", "\n", " def run_app(self):\n", " self.app.run()\n", "\n", " def request_oil_data(self):\n", " # Define the contract for Crude Oil Futures\n", " contract = Contract()\n", " contract.symbol = \"CL\"\n", " contract.secType = \"FUT\"\n", " contract.exchange = \"NYMEX\"\n", " contract.currency = \"USD\"\n", " contract.lastTradeDateOrContractMonth = \"202412\" # Example: Dec 2024 contract\n", "\n", " # Request historical data\n", " self.app.reqHistoricalData(\n", " reqId=1,\n", " contract=contract,\n", " endDateTime='',\n", " durationStr='1 D', # 1 month\n", " barSizeSetting='5 mins',\n", " whatToShow='TRADES',\n", " useRTH=0,\n", " formatDate=1,\n", " keepUpToDate=False,\n", " chartOptions=[]\n", " )\n", "\n", " def disconnect(self):\n", " self.app.disconnect()\n", "\n", "# Create an instance and connect\n", "app = IBApp()\n", "app.connect()\n", "\n", "# Request data and output to a DataFrame\n", "app.request_oil_data()\n", "\n", "# Wait for data retrieval to complete\n", "time.sleep(10)\n", "\n", "# Access the DataFrame\n", "df = app.app.df if hasattr(app.app, 'df') else pd.DataFrame()" ] }, { "cell_type": "code", "execution_count": 17, "id": "2088c621-81d3-46f0-8596-ce05d1a89fd4", "metadata": {}, "outputs": [], "source": [ "data = df.to_csv()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }