IbPy
Python API for the Interactive Brokers on-line trading system.
ibpy -
IbPy - Interactive Brokers Python API - Google Project Hosting
I am using ibpy to get the positions of my portfolio. I understand that I can do:
from ib.opt import ibConnection
tws = ibConnection( host = 'localhost',port= 7496, clientId = 123)
tws.reqAccountUpdates(True,'accountnumber')
and then I am supposed to use updatePortfolio()
in some way, but I don't know how.
Thanks
Source: (StackOverflow)
I am new to IBpy
and I am wondering if there is any way to place an order without transmitting it and waiting for a human input to actually transmit the order?
I am using placeOrder
to place orders but I can't find a way of placing them without transmitting them.
Any help will be appreciated.
Source: (StackOverflow)
There are a lot of examples showing how to get particular asset's price from Interactive Brokers. However, when I want to get the whole chain of options for one asset, I don't know which particular strikes are listed. Same for futures, I don't know which expirations are available at the moment. So, i.e., for options, I just loop through all possible strikes and reqMktData
for each, also making a sleep(1)
every 100 messages to avoid hitting the limit for number of requests per second. Obviously, many of these messages return with error "No security definition has been found for the request".
This looks like the wrong approach as it wastes lots of time on non-existing assets. Is there any more clean way to do this, or a special function for such purpose?
Source: (StackOverflow)
I am trying to use IBpy to return historical data from some instruments, but when I try the code in the documentation I get an empty result.
I managed to make it work using R Ibroker but I would really prefer to have it working using the Python API.
Here is the code I am testing.
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)
if __name__ == '__main__':
con = ibConnection()
con.register(my_account_handler, 'UpdateAccountValue')
con.register(my_tick_handler, message.tickSize, message.tickPrice)
con.connect()
def inner():
qqqq = Contract()
qqqq.m_secType = "CASH"
qqqq.m_symbol = "MSFT"
qqqq.m_currency = "USD"
qqqq.m_exchange = "IDEALPRO"
endtime = strftime('%Y%m%d %H:%M:%S')
con.reqHistoricalData(1,qqqq,endtime,"5 D","1 hour","MIDPOINT",1,1)
sleep(10)
inner()
sleep(5)
print('disconnected', con.disconnect())
Any idea what might be going wrong?
Source: (StackOverflow)
I am interested in using ibpy with Interactive Brokers API to get real time tick data for a given universe of 100 stocks. The code below, from examples on the web works for one stock. Can someone tell me how i can do this for 100 stocks at the same time?
Python script:
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 = "DATA"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"
tws.reqMktData(1,c,"",False)
sleep(25)
print 'All done'
tws.disconnect()
Command line output:
Server Version: 76
TWS Time at connection:20150508 13:42:02 EST
bid 111.42
ask 111.5
bid 111.43
bid 111.44
bid 111.42
bid 111.38
bid 111.32
ask 111.44
All done
Source: (StackOverflow)
I am trying to run an IBpy in my linux server machine, I am using IBgateway to connect my api code to IB.
I am ordering a limit order, the problem is that the IBgateway is terminating my client connection.
As soon as it places the order the connection will be closed, making me unable to get the order status.
(This same code works perfectly when I run it in the Windows machine.)
The code I am using to place order:
def place_single_order(self,order_type,action,lmtprice,expiry_date,quantity,conn) :
conn=Connection.create(host='localhost', port=7496, clientId=1,receiver=ib, sender=None, dispatcher=None)
conn.connect()
conn.register(self.error_handler, 'Error')
conn.register(self.executed_order, message.execDetails)
conn.register(self.validids,message.nextValidId)
conn.register(self.my_order_status,message.orderStatus)
newContract = Contract()
newContract.m_symbol = 'ES'
newContract.m_secType = 'FUT'
newContract.m_exchange = 'GLOBEX'
newContract.m_currency = 'USD'
newContract.m_expiry = expiry_date
order = Order()
order.m_action = action
order.m_totalQuantity = quantity
order.m_transmit=True
order.m_orderType = order_type
if lmtprice != 0 and order_type=='LMT' :
order.m_lmtPrice=lmtprice
elif lmtprice != 0 and order_type=='STP' :
order.m_auxPrice=lmtprice
else :
pass
oid=self.new_orderID(conn) #this is to get the new orderid from IB by #
conn.placeOrder(oid,newContract,order)
Source: (StackOverflow)
I want to connect to IB with python, here is my code:
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
def error_handler(msg):
print "Server Error: %s" % msg
def reply_handler(msg):
print "Server Response: %s, %s" % (msg.typeName, msg)
if __name__ == "__main__":
tws_conn = Connection.create(port=7496, clientId=100)
tws_conn.connect()
tws_conn.register(error_handler, 'Error')
tws_conn.registerAll(reply_handler)
Whenever I use this code I receive this error which indicates that I can't connect to server:
Server Error: <error id=-1, errorCode=504, errorMsg=Not connected>
Server Response: error, <error id=-1, errorCode=504, errorMsg=Not connected>
Why I can't connect to IB?
Source: (StackOverflow)
Have set up a python environment using Ubuntu, Virtual Box on a mac OX. I downloaded ibPy in a subdirectory using via gitclone:
cd ~/ibapi
git clone https://github.com/blampe/IbPy
Then installed python setup.py in the subdirectory
Now trying to import Contracts from IbPy while pointing to the subdirectory (VirtualBox prompt reads ~/ibapi/IbPy$) using the following
from ib.ext.Contract import Contract
but getting this error message
from: can't read /var/mail/ib.ext.Contract
Any ideas how to fix this error?
Source: (StackOverflow)
I am quite a rooky in Python but i aim to build trading algos using Python and interactive broker.
I have downloaded ibPy on my Mac. I now have a folder in my "download" directory that I do not know what to do with :
- should I drag it somewhere ? Where ?
- how to actually set up ibPy on my computer.
Please feel free to be as specific as possible since I really do not get how that works. I have been using pip3 randonly (with random success previously) but it does not work here.
thanks for your help.
Source: (StackOverflow)
I freshly installed ibpy and have the following problem:
>>> from ib.opt import *
File "C:\Users\ME\Anaconda\lib\site-packages\ib\ext\EReader.py", line 29
from builtin import float, str, None, True, False
SyntaxError: cannot assign to None
Why it cannot find it? How can i fix this and download some price data?
Thank you all.
Source: (StackOverflow)
I manually installed IbPy by using "python setup.py install" under windows and WinPython. The packages seem to appear in the right dirs;
C:\WinPython-32bit-3.4.3.2\python-3.4.3\Lib\site-packages\ib\ext
C:\WinPython-32bit-3.4.3.2\python-3.4.3\Lib\site-packages\ib\lib
etc.
Running:
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import ibConnection, message
works fine in IPython, but in Python and Eclipse I get:
ImportError: No module named 'ib.ext'; 'ib' is not a package
In Eclipse I can see ib and it subdirs as packages.
Any suggestions? Thx
Source: (StackOverflow)
Hi I'm trying to use IBPy as per here: https://github.com/blampe/IbPy and it is reacting very weirdly. Methods calling upon the EClientSocket class returns data but any EClientSocket method calling to EWrapper or EWrapper methods returns None and/or has issues. I realize IB's API is asynchronous at its source in Java but I can't figure out where it's breaking. I have DDE/Socket connections enabled in TWS, and even a clientId(100) specified.
I am using the IB TWS demo from this link: https://www.interactivebrokers.com/en/index.php?f=553&twsdemo=1 and Python 3.4. My version of IBpy is installed using pip install ib-api.
Here is my code:
from ib.opt import ibConnection, Connection, message
from ib.ext.Contract import Contract
from ib.ext.EWrapper import EWrapper
from ib.ext.EClientSocket import EClientSocket
from ib.ext.ExecutionFilter import ExecutionFilter
from ib.ext.Order import Order
import time
from time import sleep
def reply_handler(msg):
print("Reply:", msg)
def create_contract(symbol, sec_type, exch, prim_exch, curr):
contract = Contract()
contract.m_symbol = symbol
contract.m_sec_type = sec_type
contract.m_exch = exch
contract.m_prim_exch = prim_exch
contract.m_curr = curr
return contract
if __name__ == "__main__":
tws_conn = ibConnection(host='localhost', port=7496, clientId=100)
tws_conn.connect()
tws_conn.registerAll(reply_handler)
contract = Contract()
contract.m_symbol = 'GE'
contract.m_exchange = 'SMART'
contract.m_localSymbol = 'GE'
contract.m_primaryExch = 'SMART'
contract.m_currency = 'USD'
contract.m_secType = 'STK'
#EClientSocket only methods
reply_handler(tws_conn.isConnected())
reply_handler(tws_conn.serverVersion())
reply_handler(tws_conn.TwsConnectionTime())
#EWrapper methods or calls to EWrapper methods
reply_handler(tws_conn.reqCurrentTime())
reply_handler(tws_conn.reqAccountUpdates(1, ''))
reply_handler(tws_conn.currentTime())
reply_handler(tws_conn.reqMktData(1, contract, '', False))
reply_handler(tws_conn.contractDetails(1, contract))
Here is the console output when the script is ran:
Server Version: 76
TWS Time at connection:20150529 23:29:54 PST
Reply: True
Reply: 76
Reply: 20150529 23:29:54 PST
Reply: None
Reply: None
Reply: currentTime time=None
Reply: None
Reply: None
Reply: contractDetails reqId=1, contractDetails=ib.ext.Contract.Contract object at 0x000000000287FB70
Reply: None
You can see that after the 3rd method the last EClientSocket call it stops working. I've looked into IB's and IBpy's documentation and this particular issue is not mentioned anywhere as well on Stackoverflow. Thanks for any help!
Source: (StackOverflow)
I am new to IBPy and really interested to know how to get account parameters for multiple accounts. The code below only gives me the output in the command line but I couldn't figure out how to store those information into a dataframe. the function updateAccountValue() doesn't have a unique id that i can use as index for the dataframe.
from ib.opt import Connection, message
import pandas as pd
import time
def error_handler(msg):
"""Handles the capturing of error messages"""
print "Server Error: %s" % msg
def updateAccount_handler(msg):
if msg.key in ['AccountType','NetLiquidation']:
print msg.key, msg.value
if __name__ == "__main__":
conn = Connection.create(port=7497, clientId = 93)
conn.connect()
conn.register(error_handler, 'Error')
conn.register(updateAccount_handler,message.updateAccountValue)
# we can do a loop, i am just giving a simple example for 2 accounts
conn.reqAccountUpdates(1,"Uxxxx008")
time.sleep(0.5)
conn.reqAccountUpdates(1,"Uxxxx765")
time.sleep(0.5)
conn.disconnect()
the output looks like this:
Server Version: 76
TWS Time at connection:20150729 12:46:56 EST
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfuture>
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfuture.us>
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfarm>
Server Error: <error id=-1, errorCode=2106, errorMsg=HMDS data farm connection is OK:ushmds>
AccountType INDIVIDUAL
NetLiquidation 2625.24
AccountType IRA-ROTH NEW
NetLiquidation 11313.83
End goal is to store these information into a pandas dataframe format with an unique id of account number.
Source: (StackOverflow)
How do I the get buying power and cash available of my account with IBPy?
I'm not seeing anything obvious in IBPy docs.
Source: (StackOverflow)
Here is a pretty standard piece of code I use to request some data from Interactive Brokers API through python:
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
import time
def watcher(msg):
print msg
con = ibConnection()
con.registerAll(watcher)
con.connect()
contract = Contract()
contract.m_symbol = "EUR"
contract.m_exchange = "IDEALPRO"
contract.m_currency = "USD"
contract.m_secType = "CASH"
con.reqMktData(1, contract, '', False)
time.sleep(5)
con.disconnect()
print "DISCONNECTED"
time.sleep(60)
I expect the connection to be closed after con.disconnect()
, however it keeps getting new data (messages print updated bid, ask etc).
Why doesn't disconnect()
seem to do anything and how can I actually close the connection?
Source: (StackOverflow)