2017-02-27 80 views
0

我能夠成功地建立從python到TWS的連接,但我無法獲取數據,或者不確定數據是否被提取但未顯示。如何檢索和顯示在Python控制檯從TWS的歷史數據?

我對此很陌生,請問您可以提供如何從TWS獲取歷史數據嗎?

+0

你有什麼試過的?請發佈您的可複製代碼,以便人們可以更好地幫助您。欲瞭解更多信息,請閱讀http://stackoverflow.com/help/how-to-ask。 –

+0

http://stackoverflow.com/a/42815884/2855515 – brian

回答

0

這適用於我。

from ibapi.wrapper import EWrapper 
from ibapi.client import EClient 
from ibapi.utils import iswrapper 
from ibapi.common import * 
from ibapi.contract import * 
from ibapi.ticktype import * 

class TestApp(EWrapper, EClient): 
    def __init__(self): 
    EClient.__init__(self,self) 

    def error(self, reqId: TickerId, errorCode:int, errorString:str): 
    print('Error:', reqId, " ", errorCode, " ", errorString) 

    def contractDetails(self, reqId:int, contractDetails:ContractDetails): 
    print("contractDetails: ", reqId, " ", contractDetails) 

    def marketDataType(self, reqId: TickerId, marketDataType: int): 
    super().marketDataType(reqId, marketDataType) 
    print("MarketDataType. ", reqId, "Type:", marketDataType) 
    @iswrapper 
    def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib): 
    super().tickPrice(reqId, tickType, price, attrib) 
    print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:", price, "CanAutoExecute:", attrib.canAutoExecute, "PastLimit", attrib.pastLimit) 
    @iswrapper 
    def tickSize(self, reqId: TickerId, tickType: TickType, size: int): 
    super().tickSize(reqId, tickType, size) 
    print("Tick Size. Ticker Id:", reqId, "tickType:", tickType, "Size:", size) 

    @iswrapper 
    def tickString(self, reqId: TickerId, tickType: TickType, value: str): 
    super().tickString(reqId, tickType, value) 
    print("Tick string. Ticker Id:", reqId, "Type:", tickType, "Value:", value) 

    @iswrapper 
    def tickGeneric(self, reqId: TickerId, tickType: TickType, value: float): 
    super().tickGeneric(reqId, tickType, value) 
    print("Tick Generic. Ticker Id:", reqId, "tickType:", tickType, "Value:", value) 

def main(): 
    app = TestApp() 
    app.connect("127.0.0.1", 4001, 0) 

    contract = Contract(); 
    contract.symbol = "VIX"; 
    contract.secType = "FUT"; 
    contract.exchange = "CFE"; 
    contract.currency = "USD"; 
    contract.lastTradeDateOrContractMonth = "20170621"; 

    app.reqMktData(1001, contract, "", False, False, []) 

    app.run() 
    sleep(10) 
    app.disconnect() 


if __name__ == '__main__': 
    main()