【问题标题】:TWS API Python: How to extract API response into a variable (New version)TWS API Python:如何将 API 响应提取到变量中(新版本)
【发布时间】:2022-09-26 09:41:28
【问题描述】:

我是 TWS API for Python 的初学者,我一直在尝试将 API 响应提供的信息存储到变量中。 例如,在给定时间保存股票当天的低点,以将其用作止损的辅助价格。然而,我发现这是不可能的。

我在这里看到了与此相关的上一个问题:IbPy: How to extract API response into a variable

问题是 IbPy 是旧的 TWS API Python 包装器,不再使用。在那里提供的答案中,它使用类 Downloader 并且关键函数似乎是 self.tws.register,但我无法在 Python 的新 API 中找到它。

如何访问该功能?有任何代码示例可以完成这项工作吗?

    标签: python algorithmic-trading tws


    【解决方案1】:

    这是我编写的一些代码,它在浏览器中打印出历史数据图表,如下所示。这不是您特别要求的,但它可以为完全迷路的人提供模板。

    要保存数据,正如您所要求的,在__init__() 函数中初始化一个列表,然后使用正确的函数,这里是historicalData(),对我来说,保存该数据,因为它从 TWS 流回给您,方法是附加初始化的列表。

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract
    
    import threading
    import time
    
    class IBapi(EWrapper, EClient):
        def __init__(self):
            EClient.__init__(self, self)
            self.data = []
        def historicalData(self, reqId, bar):
            #print("Time: {} Close: {}".format(bar.date, bar.close))
            self.data.append([bar.date, bar.open, bar.close, bar.low, bar.high])
    
    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
    eurusd_contract = Contract()
    eurusd_contract.symbol = 'EUR'
    eurusd_contract.secType = 'CASH'
    eurusd_contract.exchange = 'IDEALPRO'
    eurusd_contract.currency = 'USD'
    
    #Request historical candles
    app.reqHistoricalData(1, eurusd_contract, '', '2 D', '1 hour', 'BID', 0, 2, False, [])
    
    time.sleep(5) #sleep to allow enough time for data to be returned
    
    
    import pandas as pd
    import matplotlib.pyplot as plt
    import plotly.graph_objects as go
    df = pd.DataFrame(app.data, columns=['DateTime','Open','Close','Low','High'])
    df['DateTime'] = pd.to_datetime(df['DateTime'], unit='s')
    df.to_csv('EURUSD_Hourly.csv')
    
    
    fig = go.Figure(data=[go.Candlestick(x=df['DateTime'],
                    open=df['Open'],
                    high = df['High'],
                    low=df['Low'],
                    close=df['Close'])])
    
    fig.show()
    
    print(df)
    
    app.disconnect()
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2019-12-15
      • 2021-01-19
      • 2021-05-26
      • 1970-01-01
      • 2021-12-12
      • 2018-08-23
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多