0
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import matplotlib.pyplot as plt
import pandas as pd
import threading
import time


class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.data = [] #Initialize variable to store candle

    def historicalData(self, reqId, bar):
        print(f'Time: {bar.date} Open: {bar.open} High: {bar.high} Low: {bar.low} Close: {bar.close}')
        self.data.append([bar.date, bar.open, bar.high, bar.low, bar.close])
        
    def realtimeBar(self, reqId, bar):
        print(f'Time: {bar.date} Open: {bar.open} High: {bar.high} Low: {bar.low} Close: {bar.close}')
        self.data.append([bar.date, bar.open, bar.high, bar.low, bar.close])

def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7497, 123)

#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1) #Sleep interval to allow time for connection to server

#Create contract object
contract = Contract()
contract.symbol = 'AAPL'
contract.secType = 'STK'
contract.exchange = 'SMART'
contract.currency = 'USD'

#Request historical candles
app.reqHistoricalData(1, contract, '', '2 D', '1 hour', 'BID', 0, 2, False, [])
    
#Create a dataframe from the historical data 
df = pd.DataFrame(app.data,columns=["date","open","high","low","close"]) 

data = pd.DataFrame()
data["date"] = df["date"]
data["open"] = df["open"]
data["high"] = df["high"]
data["low"] = df["low"]
data["close"] = df["close"]

#Plot the candlestick chart 
plt.style.use('bmh')
plt.figure(figsize=(15,8))
plt.title('AAPL Stock Price')
plt.xlabel('date')
plt.ylabel('price')
plt.plot(df.index, df['open'], label='open')
plt.plot(df.index, df['high'], label='high')
plt.plot(df.index, df['low'], label='low')
plt.plot(df.index, df['close'], label='close')
plt.legend()
plt.show()

#Request Live Data Type
app.reqMarketDataType(4)
#Requesting the Live Market Data
app.reqRealTimeBars(1, contract, 1, "MIDPOINT", True, [])

#Create a dataframe from the real-time data 
df2 = pd.DataFrame(app.data,columns=["date","open","high","low","close"])

#Add the real-time data to the historical data 
if not df2.empty:
    df = df.append(df2)

print(df)

#Plot the live candlestick chart 
plt.style.use('bmh')
plt.figure(figsize=(15,8))
plt.title('AAPL Stock Price')
plt.xlabel('date')
plt.ylabel('price')
plt.plot(df.index, df['open'], label='open')
plt.plot(df.index, df['high'], label='high')
plt.plot(df.index, df['low'], label='low')
plt.plot(df.index, df['close'], label='close')
plt.legend()
plt.show()

the error is the following:

Reloaded modules: ibapi, ibapi.message, ibapi.enum_implem, ibapi.object_implem, ibapi.common, ibapi.utils, ibapi.contract, ibapi.softdollartier, ibapi.order, ibapi.order_state, ibapi.execution, ibapi.ticktype, ibapi.commission_report, ibapi.wrapper, ibapi.server_versions, ibapi.tag_value, ibapi.scanner, ibapi.errors, ibapi.comm, ibapi.order_condition, ibapi.orderdecoder, ibapi.decoder, ibapi.reader, ibapi.connection, ibapi.client ERROR 1 504 Not connected ERROR -1 504 Not connected ERROR -1 504 Not connected Empty DataFrame Columns: [date, open, high, low, close] Index: []

can anybody here help me debug it?

Scieoner
  • 11
  • 1
  • 6

0 Answers0