有人可以通过使用IB API Python套接字帮助我弄清楚如何做基本请求吗?(我使用最新的IB API,它似乎支持Python,所以不应该使用人们过去使用的Ibpy)
像这样的代码可以简单地工作并使其连接到TWS.问题是:我不知道如何"看到"从IB发回的消息.
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *
w = wrapper.EWrapper()
myTWS = EClient(w)
myTWS.connect(host='localhost', port=7496, clientId=100)
print("serverVersion:%s connectionTime:%s" % (myTWS.serverVersion(),
myTWS.twsConnectionTime()))
myTWS.startApi()
c = Contract()
c.m_symbol = "AAPL"
c.m_secType = "STK"
c.m_exchange = "ISLAND"
c.m_currency = "USD"
myTWS.reqRealTimeBars(999, c, 5, "MIDPOINT", True, [])
Run Code Online (Sandbox Code Playgroud)
我知道它之前就像是IBPy之类的Register().我只是不知道如何在当前的IB原始python API中做到这一点.给我一个简单的例子可以帮助别人吗?提前致谢.
您必须子类化/覆盖/实现wrapper.EWrapper。这就是您要EClient发送从 TWS 收到的数据的地方。
我从示例程序中删除了几乎所有内容,并且它运行了。
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *
class TestApp(wrapper.EWrapper, EClient):
def __init__(self):
wrapper.EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
self.nextValidOrderId = orderId
#here is where you start using api
contract = Contract()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
self.reqMktData(1101, contract, "", False, None)
@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
@iswrapper
def tickPrice(self, reqId: TickerId , tickType: TickType, price: float,
attrib:TickAttrib):
print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:", price)
#this will disconnect and end this program because loop finishes
self.done = True
def main():
app = TestApp()
app.connect("127.0.0.1", 7496, clientId=123)
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
app.twsConnectionTime()))
app.run()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
一旦您调用app.run()该程序,就会开始几乎无限的循环读取消息,因此您需要一些其他方法来构造您的程序,因为必须启动循环。
有一个新项目简化了Python TWS Api的工作.
它被称为IB-insync,它允许同步和异步处理.对于TWS API中的新手来说,这看起来非常棒.链接到项目页面
使用IB-insync请求历史数据的示例:
from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
contract = Forex('EURUSD')
bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
# convert to pandas dataframe:
df = util.df(bars)
print(df[['date', 'open', 'high', 'low', 'close']])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7265 次 |
| 最近记录: |