# -*- coding: utf-8 -*-

# Doc: https://interactivebrokers.github.io/tws-api/historical_data.html

from ibapi.client import EClient # Client to connect to TWS IBAPI
from ibapi.wrapper import EWrapper # Translate the TWS msg
from ibapi.contract import Contract
import threading
import time
import datetime

class TestWrapper(EWrapper):
    def __init__(self):
        pass
    
class TestClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)
        
        
class TestApp(TestWrapper, TestClient):
    def __init__(self):
        TestWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)
    
    def historicalData(self, reqId, bar):
        # super().historicalData(reqId, bar)
        print("HistoricalData. ReqId: {}, Bar: = {}".format(reqId, bar))
        
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        super().historicalDataEnd(reqId, start, end)
        print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
        
    # def historicalDataUpdate(self, reqId: int, bar: BarData):
    #     print("HistoricalDataUpdate. ReqId:", reqId, "BarData.", bar)
        

# wrapper = TestWrapper()
# client = TestClient(wrapper)

app = TestApp()

def run():
    print("app runing ......")
    app.run()
    print("app complete")
    
print("App connecting")

app.connect("127.0.0.1", 7497, clientId=15)

print("Start thread")

conn_thread = threading.Thread(target=run, daemon=True)
conn_thread.start()


contract = Contract()
contract.symbol = "SPY"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "ARCA"
    
    
print("Get historicalData")
app.reqHistoricalData(reqId=4102, 
                     contract=contract, 
                     endDateTime='', 
                     durationStr="3 M", 
                     barSizeSetting="5 mins", 
                     whatToShow="ADJUSTED_LAST", 
                     useRTH=1, 
                     formatDate=1, 
                     keepUpToDate=False, 
                     chartOptions=[])


time.sleep(5)
print("completed")