程式

使用 IbPy 從盈透證券下載數據

  • May 3, 2020

我正在嘗試使用下面的程式碼從 Interactive Broker 下載數據,並且能夠創建與 Trader Work Station 的連接(之後我得到一個“True” con.connect())但沒有輸出,即dataDownload變數變為空。

有誰知道為什麼會這樣?

# Adapted from: http://godelsmarket.blogspot.co.uk/2012/07/non-gui-ib-historical-data-downloader.html

from time import sleep, strftime, localtime
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message

new_symbolinput = ['EUR.USD']
newDataList = []
dataDownload = []

def historical_data_handler(msg):
 global newDataList
 #print msg.reqId, msg.date, msg.open, msg.high, msg.low, msg.close, msg.volume
 if ('finished' in str(msg.date)) == False:
   new_symbol = new_symbolinput[msg.reqId]
   dataStr = '%s, %s, %s, %s, %s, %s, %s' % (new_symbol, strftime("%Y-%m-%d %H:%M:%S", localtime(int(msg.date))), msg.open, msg.high, msg.low, msg.close, msg.volume)
   newDataList = newDataList + [dataStr]
 else:
   new_symbol = new_symbolinput[msg.reqId]
   filename = 'minutetrades' + new_symbol + '.csv'
   csvfile = open('csv_day_test/' + filename,'wb')
   for item in newDataList:
     csvfile.write('%s \n' % item)
   csvfile.close()
   newDataList = []
   global dataDownload
   dataDownload.append(new_symbol)

con = ibConnection()
con.register(historical_data_handler, message.historicalData)
con.connect()

symbol_id = 0
for i in new_symbolinput:
 print i
 qqq = Contract()
 qqq.m_symbol = i
 qqq.m_secType = 'STK'
 qqq.m_exchange = 'SMART'
 qqq.m_currency = 'USD'
 con.reqHistoricalData(symbol_id, qqq, '', '1 D', '1 min', 'TRADES', 1, 2)
 symbol_id = symbol_id + 1
 sleep(0.5)

print dataDownload

您需要調整髮送給 IB 的合約輸入

secType 應為 CASH,exchange 應為 IDEALPRO,並添加 whatToShow = “MIDPOINT” or “BID” or “ASK”

引用自:https://quant.stackexchange.com/questions/17033