Ibpy with Interactive Brokers API 不工作
Ibpy with Interactive Brokers API not working
我觉得有什么根本性的错误。我从一个示例代码到另一个示例代码都尝试过,但我从来没有成功过。
下面是我 运行 和响应的脚本集合。这些脚本中的大多数来自 Whosebug 上的示例,该人似乎已经成功(在一些帮助之后)。唉,我没有成功,只是觉得我做的事情肯定有问题。
在开始使用此处似乎不起作用的脚本之前,我先了解一下我对交互式经纪商 GUI、TWS 的配置。
API - 设置
选中:启用 ActiveX 和套接字客户端。
未选中:启用 DDE 客户端。
未选中:只读 API。
选中:在连接时下载打开的订单。
选中:发送投资组合时包括外汇头寸。
选中:发送 EEP 的状态更新。
套接字端口 = 7496。
checked:使用负数绑定自动订单。
未选中:创建 API 消息日志文件。
未选中:在 API 日志文件中包含市场数据。
未选中:让 API 帐户请求切换用户可见的 acc 订阅。
日志记录级别 = 错误。
Master API 客户端 ID = 100。
将批量数据发送到 API 的超时时间为 30 秒。
组件 Exch 分隔符 = 空白(此处无条目)。
选中:仅允许来自本地主机的连接。
API - 注意事项
选中:绕过 API 订单的订单预防措施。
此选项卡中的其他所有内容均未选中。
示例 1.
#test_conn.py
from ib.opt import ibConnection
con = ibConnection(port=7496,clientId=100)
print(con.connect())
运行 脚本和响应
C:\Users\alex>python test_conn.py
Server Version: 76
TWS Time at connection:20160314 16:13:59 ICT
True
True
我想我可以连接到 TWS 吗?
示例 2.
#test_portfolio.py
from ib.opt import ibConnection, message
def acct_update(msg):
print(msg)
con = ibConnection(port=7496,clientId=100)
con.register(acct_update,
message.updateAccountValue,
message.updateAccountTime,
message.updatePortfolio)
con.connect()
con.reqAccountUpdates(True,'DU358588')
#don't forget to disconnect somehow when done
con.disconnect()
运行 脚本和响应
C:\Users\alex>python test_portfolio.py
Server Version: 76
TWS Time at connection:20160314 16:25:59 ICT
C:\Users\alex>
所以什么都没有返回?
示例 3.
#test_mkt_data.py
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep
def my_callback_handler(msg):
inside_mkt_bid = ''
inside_mkt_ask = ''
if msg.field == 1:
inside_mkt_bid = msg.price
print 'bid', inside_mkt_bid
elif msg.field == 2:
inside_mkt_ask = msg.price
print 'ask', inside_mkt_ask
tws = ibConnection()
tws.register(my_callback_handler, message.tickSize, message.tickPrice)
tws.connect()
c = Contract()
c.m_symbol = "GOOG"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"
tws.reqMktData(1,c,"",False)
sleep(25)
print 'All done'
tws.disconnect()
运行 脚本和响应
C:\Users\alex>python test_mkt_data.py
Server Version: 76
TWS Time at connection:20160314 16:31:54 ICT
All done
Exception in thread EReader (likely raised during interpreter shutdown):
C:\Users\alex>
再一次,没有返回任何内容?
示例 4.
#test_historical.py
from time import sleep, strftime
from time import sleep
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
def my_account_handler(msg):
print(msg)
def my_tick_handler(msg):
print(msg)
def my_hist_data_handler(msg):
print(msg)
if __name__ == '__main__':
con = ibConnection(port=7496,clientId=100)
con.register(my_account_handler, 'UpdateAccountValue')
con.register(my_tick_handler, message.tickSize, message.tickPrice)
con.register(my_hist_data_handler, message.historicalData)
con.connect()
print(con.isConnected())
def inner():
qqqq = Contract()
qqqq.m_secType = "STK"
qqqq.m_symbol = "GOOG"
qqqq.m_currency = "USD"
qqqq.m_exchange = "SMART"
endtime = strftime('%Y%m%d %H:%M:%S')
print(endtime)
print(con.reqHistoricalData(1,qqqq,endtime,"5 D","1 hour","MIDPOINT",0,1))
sleep(10)
inner()
sleep(5)
print('disconnected', con.disconnect())
print(con.isConnected())
运行 脚本和响应
C:\Users\alex>python test_historical.py
Server Version: 76
TWS Time at connection:20160314 16:38:03 ICT
True
20160314 16:38:04
None
('disconnected', True)
False
C:\Users\alex>
没有历史数据?去掉"print(con.req..."中的"print"还是没有区别
示例 5.
# ib_api_demo.py
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
def error_handler(msg):
"""Handles the capturing of error messages"""
print "Server Error: %s" % msg
def reply_handler(msg):
"""Handles of server replies"""
print "Server Response: %s, %s" % (msg.typeName, msg)
def create_contract(symbol, sec_type, exch, prim_exch, curr):
"""Create a Contract object defining what will
be purchased, at which exchange and in which currency.
symbol - The ticker symbol for the contract
sec_type - The security type for the contract ('STK' is 'stock')
exch - The exchange to carry out the contract on
prim_exch - The primary exchange to carry out the contract on
curr - The currency in which to purchase the contract"""
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = sec_type
contract.m_exchange = exch
contract.m_primaryExch = prim_exch
contract.m_currency = curr
return contract
def create_order(order_type, quantity, action):
"""Create an Order object (Market/Limit) to go long/short.
order_type - 'MKT', 'LMT' for Market or Limit orders
quantity - Integral number of assets to order
action - 'BUY' or 'SELL'"""
order = Order()
order.m_orderType = order_type
order.m_totalQuantity = quantity
order.m_action = action
return order
if __name__ == "__main__":
# Connect to the Trader Workstation (TWS) running on the
# usual port of 7496, with a clientId of 100
# (The clientId is chosen by us and we will need
# separate IDs for both the execution connection and
# market data connection)
tws_conn = Connection.create(port=7496, clientId=100)
tws_conn.connect()
# Assign the error handling function defined above
# to the TWS connection
tws_conn.register(error_handler, 'Error')
# Assign all of the server reply messages to the
# reply_handler function defined above
tws_conn.registerAll(reply_handler)
# Create an order ID which is 'global' for this session. This
# will need incrementing once new orders are submitted.
order_id = 1
# Create a contract in a stock via SMART order routing
goog_contract = create_contract('BHP', 'STK', 'SMART', 'SMART', 'AUD')
# Go long 100 shares of Google
goog_order = create_order('MKT', 100, 'BUY')
# Use the connection to the send the order to IB
tws_conn.placeOrder(order_id, goog_contract, goog_order)
# Disconnect from TWS
tws_conn.disconnect()
运行宁和回应
C:\Users\alex>python ib_api_demo.py
Server Version: 76
TWS Time at connection:20160314 16:43:55 ICT
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>
Server Response: error, <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>
C:\Users\alex>
所以似乎没有任何效果,我觉得我错过了一些基本的东西?当我 运行 python 脚本和 TWS API 设置(见上文)就其他人所说的而言,我已经登录并 运行ning在线。
非常感谢任何帮助。
我试过你提供的代码。
示例 2. 在 con.disconnect()
之前添加 sleep(1)
示例 3. tws = ibConnection() 应更改为 tws = ibConnection(port=7496,clientId=100)
例4,“1小时”-->太多space,只留下一个space,多余的删掉
示例 5. 请注意下一个有效的订单 ID。它应该大于Ib系统中的order id。您可以使用以下代码从系统中获取下一个有效订单 ID。:
def save_order_id(msg):
print('Next Valid ID is ' + str(msg.orderId))
con = ibConnection(port=7496,clientId=100)
con.register(save_order_id, 'NextValidId')
con.connect()
sleep(1)
con.disconnect()
您可以接受上述更改。
我觉得有什么根本性的错误。我从一个示例代码到另一个示例代码都尝试过,但我从来没有成功过。
下面是我 运行 和响应的脚本集合。这些脚本中的大多数来自 Whosebug 上的示例,该人似乎已经成功(在一些帮助之后)。唉,我没有成功,只是觉得我做的事情肯定有问题。
在开始使用此处似乎不起作用的脚本之前,我先了解一下我对交互式经纪商 GUI、TWS 的配置。
API - 设置
选中:启用 ActiveX 和套接字客户端。 未选中:启用 DDE 客户端。 未选中:只读 API。 选中:在连接时下载打开的订单。 选中:发送投资组合时包括外汇头寸。 选中:发送 EEP 的状态更新。 套接字端口 = 7496。 checked:使用负数绑定自动订单。 未选中:创建 API 消息日志文件。 未选中:在 API 日志文件中包含市场数据。 未选中:让 API 帐户请求切换用户可见的 acc 订阅。 日志记录级别 = 错误。 Master API 客户端 ID = 100。 将批量数据发送到 API 的超时时间为 30 秒。 组件 Exch 分隔符 = 空白(此处无条目)。 选中:仅允许来自本地主机的连接。
API - 注意事项 选中:绕过 API 订单的订单预防措施。 此选项卡中的其他所有内容均未选中。
示例 1.
#test_conn.py
from ib.opt import ibConnection
con = ibConnection(port=7496,clientId=100)
print(con.connect())
运行 脚本和响应
C:\Users\alex>python test_conn.py
Server Version: 76
TWS Time at connection:20160314 16:13:59 ICT
True
True
我想我可以连接到 TWS 吗?
示例 2.
#test_portfolio.py
from ib.opt import ibConnection, message
def acct_update(msg):
print(msg)
con = ibConnection(port=7496,clientId=100)
con.register(acct_update,
message.updateAccountValue,
message.updateAccountTime,
message.updatePortfolio)
con.connect()
con.reqAccountUpdates(True,'DU358588')
#don't forget to disconnect somehow when done
con.disconnect()
运行 脚本和响应
C:\Users\alex>python test_portfolio.py
Server Version: 76
TWS Time at connection:20160314 16:25:59 ICT
C:\Users\alex>
所以什么都没有返回?
示例 3.
#test_mkt_data.py
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep
def my_callback_handler(msg):
inside_mkt_bid = ''
inside_mkt_ask = ''
if msg.field == 1:
inside_mkt_bid = msg.price
print 'bid', inside_mkt_bid
elif msg.field == 2:
inside_mkt_ask = msg.price
print 'ask', inside_mkt_ask
tws = ibConnection()
tws.register(my_callback_handler, message.tickSize, message.tickPrice)
tws.connect()
c = Contract()
c.m_symbol = "GOOG"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"
tws.reqMktData(1,c,"",False)
sleep(25)
print 'All done'
tws.disconnect()
运行 脚本和响应
C:\Users\alex>python test_mkt_data.py
Server Version: 76
TWS Time at connection:20160314 16:31:54 ICT
All done
Exception in thread EReader (likely raised during interpreter shutdown):
C:\Users\alex>
再一次,没有返回任何内容?
示例 4.
#test_historical.py
from time import sleep, strftime
from time import sleep
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
def my_account_handler(msg):
print(msg)
def my_tick_handler(msg):
print(msg)
def my_hist_data_handler(msg):
print(msg)
if __name__ == '__main__':
con = ibConnection(port=7496,clientId=100)
con.register(my_account_handler, 'UpdateAccountValue')
con.register(my_tick_handler, message.tickSize, message.tickPrice)
con.register(my_hist_data_handler, message.historicalData)
con.connect()
print(con.isConnected())
def inner():
qqqq = Contract()
qqqq.m_secType = "STK"
qqqq.m_symbol = "GOOG"
qqqq.m_currency = "USD"
qqqq.m_exchange = "SMART"
endtime = strftime('%Y%m%d %H:%M:%S')
print(endtime)
print(con.reqHistoricalData(1,qqqq,endtime,"5 D","1 hour","MIDPOINT",0,1))
sleep(10)
inner()
sleep(5)
print('disconnected', con.disconnect())
print(con.isConnected())
运行 脚本和响应
C:\Users\alex>python test_historical.py
Server Version: 76
TWS Time at connection:20160314 16:38:03 ICT
True
20160314 16:38:04
None
('disconnected', True)
False
C:\Users\alex>
没有历史数据?去掉"print(con.req..."中的"print"还是没有区别
示例 5.
# ib_api_demo.py
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
def error_handler(msg):
"""Handles the capturing of error messages"""
print "Server Error: %s" % msg
def reply_handler(msg):
"""Handles of server replies"""
print "Server Response: %s, %s" % (msg.typeName, msg)
def create_contract(symbol, sec_type, exch, prim_exch, curr):
"""Create a Contract object defining what will
be purchased, at which exchange and in which currency.
symbol - The ticker symbol for the contract
sec_type - The security type for the contract ('STK' is 'stock')
exch - The exchange to carry out the contract on
prim_exch - The primary exchange to carry out the contract on
curr - The currency in which to purchase the contract"""
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = sec_type
contract.m_exchange = exch
contract.m_primaryExch = prim_exch
contract.m_currency = curr
return contract
def create_order(order_type, quantity, action):
"""Create an Order object (Market/Limit) to go long/short.
order_type - 'MKT', 'LMT' for Market or Limit orders
quantity - Integral number of assets to order
action - 'BUY' or 'SELL'"""
order = Order()
order.m_orderType = order_type
order.m_totalQuantity = quantity
order.m_action = action
return order
if __name__ == "__main__":
# Connect to the Trader Workstation (TWS) running on the
# usual port of 7496, with a clientId of 100
# (The clientId is chosen by us and we will need
# separate IDs for both the execution connection and
# market data connection)
tws_conn = Connection.create(port=7496, clientId=100)
tws_conn.connect()
# Assign the error handling function defined above
# to the TWS connection
tws_conn.register(error_handler, 'Error')
# Assign all of the server reply messages to the
# reply_handler function defined above
tws_conn.registerAll(reply_handler)
# Create an order ID which is 'global' for this session. This
# will need incrementing once new orders are submitted.
order_id = 1
# Create a contract in a stock via SMART order routing
goog_contract = create_contract('BHP', 'STK', 'SMART', 'SMART', 'AUD')
# Go long 100 shares of Google
goog_order = create_order('MKT', 100, 'BUY')
# Use the connection to the send the order to IB
tws_conn.placeOrder(order_id, goog_contract, goog_order)
# Disconnect from TWS
tws_conn.disconnect()
运行宁和回应
C:\Users\alex>python ib_api_demo.py
Server Version: 76
TWS Time at connection:20160314 16:43:55 ICT
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>
Server Response: error, <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>
C:\Users\alex>
所以似乎没有任何效果,我觉得我错过了一些基本的东西?当我 运行 python 脚本和 TWS API 设置(见上文)就其他人所说的而言,我已经登录并 运行ning在线。
非常感谢任何帮助。
我试过你提供的代码。
示例 2. 在 con.disconnect()
之前添加 sleep(1)示例 3. tws = ibConnection() 应更改为 tws = ibConnection(port=7496,clientId=100)
例4,“1小时”-->太多space,只留下一个space,多余的删掉
示例 5. 请注意下一个有效的订单 ID。它应该大于Ib系统中的order id。您可以使用以下代码从系统中获取下一个有效订单 ID。:
def save_order_id(msg):
print('Next Valid ID is ' + str(msg.orderId))
con = ibConnection(port=7496,clientId=100)
con.register(save_order_id, 'NextValidId')
con.connect()
sleep(1)
con.disconnect()
您可以接受上述更改。