交互式代理api的pythonic客户端
ezIBp的Python项目详细描述
ezibpy:ibpy的pythonic包装器
eziby是IbPy的python包装器。 图书馆由@blampe, 是为了加速 依赖于 Interactive Brokers 市场数据和订单执行。
1.12.67版本现在支持多个/fa帐户!
- 连接时指定IB帐户的选项。或者,您可以…
- 使用getAccount('DUXXXXXX')、getPositions('DUXXXXXX')、getPortfolio('DUXXXXXX')或getOrders('DUXXXXXX') 获取信息
- 通过在createOrder()、placeOrder()、createBracketOrder()、createTrailingStopOrder()、createStopOrder()和createTargetOrder()方法中指定account=DUXXXXXX向特定帐户提交订单
注
从9.73版开始,InteractiveBrokers正式支持一个新的Python 3 API client。 虽然这是一个好消息,但我并不认为eziby很快就会过时,因为ib的api在imo中不是pythonic或者抽象的。 我确实计划放弃ibpy,转而使用ib的官方python api,尽管我还没有这个转换的时间表。
如果您是一名开发人员,并且有兴趣帮助将ezibpy转换为使用ib的python api,请告诉我:)
代码示例
*确保您有最新版本的 交互代理TWS或 IB Gateway已在计算机上安装并运行。
市场数据
***要使用这些方法,必须有活动的市场数据订阅***
订单执行
- Submit an Order
- Submit a Bracket Order
- Moving Stop Manually
- Bracket Order with Trailing Stop
- Combo Orders
其他材料
请求市场数据:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()# connect to IB (7496/7497 = TWS, 4001 = IBGateway)ibConn.connect(clientId=100,host="localhost",port=4001)# create some contracts using dedicated methodsstk_contract=ibConn.createStockContract("AAPL")fut_contract=ibConn.createFuturesContract("ES",expiry="201606")cont_fut_contract=ibConn.createContinuousFuturesContract("CL","NYMEX")csh_contract=ibConn.createCashContract("EUR",currency="USD")opt_contract=ibConn.createOptionContract("AAPL",expiry="20160425",strike=105.0,otype="PUT")# ...or using a contract tupleoil_contract=ibConn.createContract(("CL","FUT","NYMEX","USD","201606",0.0,""))# request market data for all created contractsibConn.requestMarketData()# wait 30 secondstime.sleep(30)# cancel market data request & disconnectibConn.cancelMarketData()ibConn.disconnect()
请求市场深度:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contract & request market depthcontract=ibConn.createCashContract("EUR",currency="USD")ibConn.requestMarketDepth()# wait 30 secondstime.sleep(30)# cancel market data request & disconnectibConn.cancelMarketData()ibConn.disconnect()
请求历史数据:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contractcontract=ibConn.createStockContract("AAPL")# request 30 days of 1 minute data and save it to ~/DesktopibConn.requestHistoricalData(resolution="1 min",lookback="2 D",csv_path='~/Desktop/')# wait until stopped using Ctrl-ctry:whileTrue:time.sleep(1)except(KeyboardInterrupt,SystemExit):# cancel request & disconnectibConn.cancelHistoricalData()ibConn.disconnect()
提交订单:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contractcontract=ibConn.createFuturesContract("ES",exchange="GLOBEX",expiry="201609")# create an orderorder=ibConn.createOrder(quantity=1)# use price=X for LMT orders# submit an order (returns order id)orderId=ibConn.placeOrder(contract,order)# to submit an order to a specific account (ie DUXXXXXX), use:# orderId = ibConn.placeOrder(contract, order, account="DUXXXXXX")# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# disconnectibConn.disconnect()
提交括号顺序:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contractcontract=ibConn.createFuturesContract("ES",exchange="GLOBEX",expiry="201609")# submit a bracket order (entry=0 = MKT order)order=ibConn.createBracketOrder(contract,quantity=1,entry=0,target=2200.,stop=1900.)# to submit bracket order to a specific account (ie DUXXXXXX), use:# order = ibConn.createBracketOrder(contract, quantity=1, entry=0, target=2200., stop=1900., account="DUXXXXXX")# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# disconnectibConn.disconnect()
提交括号命令并手动移动停止:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contractcontract=ibConn.createFuturesContract("ES",exchange="GLOBEX",expiry="201609")# submit a bracket order (entry=0 = MKT order)order=ibConn.createBracketOrder(contract,quantity=1,entry=0,target=2200.,stop=1900.)# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# move the stoporder['stopOrderId']=ibConn.modifyStopOrder(orderId=order['stopOrderId'],parentId=order['entryOrderId'],newStop=2000,quantity=-1)# disconnectibConn.disconnect()
提交带尾随停止符的括号顺序:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create a contractcontract=ibConn.createFuturesContract("ES",exchange="GLOBEX",expiry="201609")# submit a bracket order (entry=0 = MKT order)order=ibConn.createBracketOrder(contract,quantity=1,entry=0,target=2200.,stop=1900.)# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# create a trailing stop that's triggered at 2190symbol=ibConn.contractString(contract)ibConn.createTriggerableTrailingStop(symbol,-1,triggerPrice=2190,trailAmount=10,# for trail using fixed amount# trailPercent = 10, # for trail using percentageparentId=order['entryOrderId'],stopOrderId=order["stopOrderId"],ticksize=0.25# see note)# ticksize is needed to rounds the stop price to nearest allowed tick size,# so you won't try to buy ES at 2200.128230 :)# NOTE: the stop trigger/trailing is done by the software,# so your script needs to keep running for this functionality to work# disconnect# ibConn.disconnect()
提交组合订单:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# create contracts for an bear call spreadcontract_to_sell=ibConn.createOptionContract("AAPL",expiry=20161118,strike=105.,otype="CALL")contract_to_buy=ibConn.createOptionContract("AAPL",expiry=20161118,strike=100.,otype="CALL")# create combo legsleg1=ibConn.createComboLeg(contract_to_sell,"SELL",ratio=1)leg2=ibConn.createComboLeg(contract_to_buy,"BUY",ratio=1)# build a bag contract with these legscontract=ibConn.createComboContract("AAPL",[leg1,leg2])# create & place order (negative price means this is a credit spread)order=ibConn.createOrder(quantity=1,price=-0.25)orderId=ibConn.placeOrder(contract,order)# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# disconnectibConn.disconnect()
自定义回调:
importezibpyimporttime# define custom callbackdefibCallback(caller,msg,**kwargs):ifcaller=="handleOrders":order=ibConn.orders[msg.orderId]iforder["status"]=="FILLED":print(">>> ORDER FILLED")# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# assign the custom callbackibConn.ibCallback=ibCallback# create a contractcontract=ibConn.createStockContract("AAPL")# create & place orderorder=ibConn.createOrder(quantity=100)orderId=ibConn.placeOrder(contract,order)# let order filltime.sleep(1)# see the positionsprint("Positions")print(ibConn.positions)# disconnectibConn.disconnect()
*有关更多示例,请参见This Gist。
账户信息:
importezibpyimporttime# initialize ezIBpyibConn=ezibpy.ezIBpy()ibConn.connect(clientId=100,host="localhost",port=4001)# available variables (auto-updating)print("Market Data")print(ibConn.marketData)print("Market Depth")print(ibConn.marketDepthData)print("Account Information")print(ibConn.account)print("Positions")print(ibConn.positions)print("Portfolio")print(ibConn.portfolio)print("Contracts")print(ibConn.contracts)print("Orders (by TickId)")print(ibConn.orders)print("Orders (by Symbol)")print(ibConn.symbol_orders)# subscribe to account/position updatesibConn.requestPositionUpdates(subscribe=False)ibConn.requestAccountUpdates(subscribe=False)# disconnectibConn.disconnect()
记录:
ezibpy日志通过标准Python logging facilities 默认情况下,在日志名ezibpy下,级别为ERROR。
您可以更改日志级别:
importloggingimportezibpy# after ezibpy is imported, we can silence error logginglogging.getLogger('ezibpy').setLevel(logging.CRITICAL)# initialize with new logging configrationibConn=ezibpy.ezIBpy()...
或登录到文件:
importloggingimportezibpy# after ezibpy is imported, we can change the logging handler to filelogger=logging.getLogger('ezibpy')logger.addHandler(logging.FileHandler('path/to/ezibpy.log'))logger.setLevel(logging.INFO)logger.propagate=False# do not also log to stderr# initialize with new logging configrationibConn=ezibpy.ezIBpy()...
安装
使用pip:
安装eziby$ pip install ezibpy --upgrade --no-cache-dir
待办事项:
在期权方面,ezibpy目前支持市场 数据检索和订单执行。
如果要添加更多功能(如新闻检索等) 请成为我的客人并提交一个请求。
法律事务
ezibpy是根据apache许可证2.0版授权的。其副本包含在license.txt中。 ezibpy不是交互式代理的产品,也不隶属于交互式代理。
P.S.
我对你和艾兹比的经历很感兴趣。请给我一张便条,上面有你的任何反馈。
ran唤醒