如何在Python中迭代检索盈透证券历史数据?

问题描述 投票:0回答:1

我是盈透证券原生 API 用户的初学者。现在,我的交易系统需要迭代检索盈透证券的历史数据,例如每一小时的柱数据。现在我的问题是,尽管ibapi类中的init配置是[],但最终的数据列表附加了所有曾经请求的历史数据。

它应该在第一分钟下载历史 60 个 1 分钟柱。下一分钟,到目前为止仍然是 60 个 1 分钟柱。下一分钟,60 小节。但结果是 60 条。下一分钟,120小节。下一分钟,180 条。它附加所有一次请求的历史数据

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import datetime
import threading
import time
import pandas
from ibapi.order import Order
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'DateTime: {bar.date}  Open: {bar.open}  High: {bar.high} Close: {bar.close}  Low: {bar.low}  Volume: {bar.volume}')
        self.data.append([bar.date, bar.open,bar.high,bar.close,bar.low,bar.volume])

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 = 'N225M'
contract.secType = 'FUT'
contract.exchange = 'OSE.JPN'
contract.currency = 'JPY'
contract.lastTradeDateOrContractMonth = '202310'


starttime = time.time()
timeout = time.time() + 60*60*6
while (time.time() <= timeout ):

    if (datetime.datetime.now().minute % 1==0 )and (datetime.datetime.now().second<10):
        app.reqHistoricalData(1, contract, '', '3600 S', '1 min', 'TRADES', 0, 1, False, [])
        # 
        time.sleep(2)  # sleep to allow enough time for data to be returned
        # headers = ['DateTime', 'Open', 'High', 'Low', 'Close','Volume']
        # print(dict(zip(headers, app.data)))
        # df_data = {}
        df = pandas.DataFrame(app.data)
        df.columns=['DateTime','Open','High','Close','Low','Volume']
        # df['Datetime'] = df['Datetime'].dt.tz_convert('Asia/Shanghai')
        print( len(df))
        print(df)
python iteration trading interactive-brokers
1个回答
0
投票

如果想在请求完成后清除self.data,请为historyDataEnd编写一个方法:

def historicalDataEnd(self, reqId, start, end):
    self.data = []
© www.soinside.com 2019 - 2024. All rights reserved.