您好我曾嘗試下面的代碼來獲得IBPy給我的最後價格證券的名單,然後這些價格保存爲CSVIBPy:從reqMktData獲取陳舊的數據?
from ib.opt import Connection
from ib.ext.Contract import Contract
import time
import csv
Equity = Contract()
Equity.m_secType = 'Stk'
Equity.m_exchange = 'Smart'
Equity.m_currency = 'USD'
EquityList = ['XOM', 'JNJ', 'BRK B', 'JPM','GE','T','WFC','BAC','PG','CVX','VZ','PFE','MRK','HD','C','KO','DIS','V','UNH','PEP','PM','IBM','MO','SLB','ORCL','MMM','MDT','MA','WMT','MCD','ABBV','BMY','BA','HON','CVS','SPY']
PriceList = []
PriceData = csv.writer(open('price.csv','wb'))
def savepx(msg):
global px
if msg.field == 4:
px = msg.price
def main():
conn = Connection.create(port=7496,clientId=100)
conn.connect()
count = 0
for ticker in EquityList:
Equity.m_symbol = ticker
conn.register(savepx,'TickPrice')
conn.reqMktData(count,Equity,225,False)
time.sleep(.15)
conn.cancelMktData(count)
PriceList.insert(count,px)
count = count + 1
conn.disconnect()
PriceData.writerow(EquityList)
PriceData.writerow(PriceList)
當我使用此代碼就開始爲列表中獲取數據我提供的股票,但最終會被一個單一的股票行情所捕獲,它會重複下幾個股票的價格。在整個清單中偶爾會出現這種情況,但是例如在一次運行中,它將SLB的價格定義爲80.63(正確),然後簡單地重複80.63的價格,以便列表中的其餘股票以某種方式不將變量px更新爲新值爲新的代價。每次我運行這個時,這似乎總是發生在列表中正確的數據被拉出的地方,然後幾個後續的代碼具有相同的值。關於如何解決這個問題的任何想法或從IB獲取實時數據的不同方法,以避免此問題出現在股票列表中?