areed1192 / interactive-broker-python-api Goto Github PK
View Code? Open in Web Editor NEWA python packaged used to interact with the Interactive Brokers REST API.
License: MIT License
A python packaged used to interact with the Interactive Brokers REST API.
License: MIT License
I was getting a http error 500 when using the order reply request
interactive-broker-python-api/ibw/client.py
Line 1805 in 0ab98cd
According to ibrk documentation the confirmation should be boolean :
https://www.interactivebrokers.co.uk/api/doc.html#tag/Order/paths/~1iserver~1account~1orders~1{faGroup}/post
Changing the function signature makes it work
def place_order_reply(self, reply_id: str = None, reply: bool = None):
Please also note that the documentation section of the function looks like it is copy pasted from a different function
The following error is received when I am running the "ib_client.create_session()" call .. The authentication is successful and then some APIs are working fine if I try directly on the browser. For instance : https://localhost:5000/v1/api/iserver/scanner/params
What might have happened is that Interactive Brokers have stopped supporting the "fundamentals" api which was undocumented in the first place ?
_Would you like to make an authenticated request (Yes/No)? Yes
BAD REQUEST - STATUS CODE: 404
RESPONSE URL: https://localhost:5000/v1/portal/fundamentals/landing/265598?widgets=news&lang=en
RESPONSE HEADERS: {'Date': 'Sat, 07 Aug 2021 18:16:02 GMT', 'Server': 'Apache', 'x-response-time': '0ms', 'Content-Type': 'text/html;charset=utf-8', 'Vary': 'Origin', 'Keep-Alive': 'timeout=5, max=200', 'Connection': 'Keep-Alive', 'Transfer-Encoding': 'chunked'}
RESPONSE TEXT:
Hi
Iam Authenticated using the link https://localhost:5000/sso/Dispatcher but it says iam not authenticated
I do not know what is the issue.
Hi, I am getting an error TypeError: init() got an unexpected keyword argument 'is_server_running'
any suggestions?
Hi, I am using the _fundamentals_financials
and it seems like the end point is no longer working? Please see my code and error message below:
ib_client._fundamentals_financials(conid='265598', financial_statement='income', period='quarter')
HTTPError Traceback (most recent call last)
in
----> 1 ib_client._fundamentals_financials(conid='265598',
2 financial_statement='income',
3 period='quarter')
~/Documents/GitHub/invest_better/ibw_sz/client.py in _fundamentals_financials(self, conid, financial_statement, period)
932 endpoint = 'tws.proxy/fundamentals/financials/{}'.format(conid)
933 req_type = 'GET'
--> 934 content = self._make_request(
935 endpoint=endpoint,
936 req_type=req_type,
~/Documents/GitHub/invest_better/ibw_sz/client.py in _make_request(self, endpoint, req_type, headers, params, data, json)
722 elif not response.ok and url != 'https://localhost:5000/v1/portal/iserver/account':
723 print(url)
--> 724 raise requests.HTTPError()
725
726 def _prepare_arguments_list(self, parameter_list: List[str]) -> str:
HTTPError:
Unsure if this is an error on my end or not, but having used both the IBClient and querying the localhost directly I am getting nothing back when using some of the fundamental endpoints, wondering if they maybe have been removed since this code was published?
For example:
https://localhost:5000/v1/api/iserver/fundamentals/{conid}/summary and ib_client.fundamentals_summary both return a summary for a chosen conid as expected.
However:
https://localhost:5000/v1/api/fundamentals/financials/{conid}?type=income&annual=true and ib_client.fundamentals_financials come back as "None" or "Resource not found".
Similarly for ib_client.fundamentals_key_ratios, ib_client.fundamentals_esg, ib_client.fundamentals_dividends, ib_client.data_analyst_forecast, nothing is returned.
I have tried removing and adding the "/iserver/" in the paths to see if maybe it is the wrong path but neither came back with anything. I have tried finding the endpoints by looking at the fundamentals data on my IB account and watching the requests, which are called out to "https://ndcdyn.interactivebrokers.com/tws.proxy/fundamentals/financials/{conid
}?annual=true&type=income" which matches above without the prefix.
Wondering if this is something others have experienced?
Hey,
First of all thanks a lot for the repo, it has helped me pickup the interactive apis quite well. I have an issue where by whenever i call portfolio_account_positions i always get a 401. I also get the same on portfolio_account_position. I am using the api_client that you wrote so it does call the account api before it makes this call. I have tried to simulate the same on swagger docs and i get the same response there too. There is nothing in the response body and nothing in the header that i can correct. Do you have any clue on how can this be fixed. Also, yeah i am authenticated. The account calls print an empty [] (array). I can get the market data after this call too.
Hi,
I am trying to get BONDS info using this api with no success:
But I failed to use the object values to receive usable data about the bond. The conid: 2147483647 is the same one for all bonds in IB so no success..
Am I missing something?
Appreciate any help I can get!
Thanks,
Ashi
Hi Alex, Great lib, thank you for making this. After watching your video series, I'm trying to get continuous market data from IB Websocket API. I could able to connect to Client Portal gateway and also connection to websocket is successful, but I'm not able to subscribe to any quotes. Below is the code I used.
Any guidance on where I might be doing wrong/missing? Thank you.
# -*- coding: utf-8 -*-
import websocket, json
import ssl
web_socket_endpoint = "wss://localhost:5000/v1/portal/ws"
def logout(ws):
print("close")
ws.close()
def on_open(ws):
print("opened")
ws.send("s+md+59392609")
def on_message(ws, message):
print("message recieved")
try:
print(message)
except:
print("JSON Decode Failed")
def on_close(ws):
print("Connection Closed")
def on_error(ws, error):
print("error")
print(error)
try:
websocket.enableTrace(True)
WSCONNECTION = websocket.WebSocketApp(web_socket_endpoint,
on_message = on_message,
on_error = on_error,
on_close = on_close)
WSCONNECTION.on_open = on_open
WSCONNECTION.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
except Exception as e:
print(e)
capture_exception(e)
When I run ib_client.create_session()
, I get the expected message with steps 1-3 telling me how to authenticate. Terminal is opened. However, nothing is run in Terminal so there's nothing running at https://localhost:5000. However, if I cd
to the correct folder and do bin/run.sh root/conf.yaml
then localhost shows the login screen. So it seems the problem is that the command isn't being passed through to Terminal.
client.py contains def _start_server(self)
with this relevant section:
# mac will use the terminal.
elif self._operating_system == 'darwin':
IB_WEB_API_PROC = ["open", "-F", "-a", "Terminal", r"bin/run.sh", r"root/conf.yaml"]
self.server_process = subprocess.Popen(
args=IB_WEB_API_PROC,
cwd=self.client_portal_folder
).pid
My suspicion is that something is up with subprocess
. Not only because of this, but also because after Terminal does nothing and the command prompt in VS Code is asking me Would you like to make an authenticated request (Yes/No)?
, when I type 'No', I get a few errors including
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ibw/client.py", line 483, in close_session
return_code = subprocess.call("TASKKILL /F /PID {} /T".format(self.server_process), creationflags=subprocess.DETACHED_PROCESS)
AttributeError: module 'subprocess' has no attribute 'DETACHED_PROCESS'
After some Googling, someone pointed out that if you have your own subprocess.py
then Python will look through that and not find the expected DETACHED_PROCESS
, but I don't have my own subprocess.py
.
Have I got a corrupt subprocess module, even though it comes as standard with Python? Is something else wrong? Thanks.
When i try to place a Preview LMT order, i am getting {'error': 'Invalid order price fields'}. I have the price set properly as a number and orderType = "LMT". Am i missing a second price field?
How did you find the secType to use in your orders?
for example in the sample code, the secType is "secType": "362673777:FUT"
here's an example order
{
"conid": 362698833,
"secType": "362673777:FUT",
"cOID": "YOUR_CONTRACT_ORDER_ID",
"orderType": "MKT",
"side": "BUY",
"quantity": 1,
"tif": "DAY"
}
A lot of changes have been made in this repository. Please publish them to PyPi!
I am having problem having access to the web api despite that i follow the instructions on https://interactivebrokers.github.io/cpwebapi/ and got Client login succeeds
. please help. the error message is: The requested URL /v1/portal/calendar/events/ was not found on this server.
Hi Alex, great library!
Been having HTTP 500 errors trying to call run_scanner - would you be able to add a test call into test_client.py?
All other test_client.py calls and get_scanner() seem to work for me.
I saw you had sample output available - hoping this isn't too much trouble!
Chuck
DEBUG
function: _make_request
endpoint: /iserver/scanner/run
req_type: POST
params: {'instrument': 'STK', 'type': 'TOP_PERC_GAIN', 'filter': [{'code': 'usdPriceAbove', 'value': 1}],
'location': 'STK.US.MAJOR', 'size': 25}
REQUEST - STATUS CODE: 500
RESPONSE URL: https://localhost:5000/v1/portal//iserver/scanner/run
RESPONSE HEADERS: {'Date': 'Sat, 02 May 2020 15:26:03 GMT', 'Server': 'Apache', 'x-response-time': '0ms', 'Vary': 'Origin', 'Connection': 'close', 'Transfer-Encoding': 'chunked'}
RESPONSE TEXT:
Small issue but in the run_client.py line 69 the code is:
aapl_income_statement = ib_client.fundamentals_financials( conid='265598', financial_statement='income', period
in order for this code to run need to make line 896 in client.py to be
def fundamentals_financials(self, conid: str, financial_statement: str, period: str = 'annual') -> Dict:
Hi,
Thank you for your work and sharing. I had a test script working yesterday but not today. It seemed the hard coded news endpoint was out of date so I replaced it with an account endpoint ...
line 202 - 204 - commented out
line 342 ...
try:
# news_resp = self.data_news(conid='265598')
accs = self.portfolio_accounts()
if len(accs) > 0:
self.authenticated = True
# Log the response.
logging.debug('Had to do Account Update Response: {auth_resp}'.format(
auth_resp=accs
)
)
break
Hi Alex! I installed the package, but when trying to use I get this error below:
Traceback (most recent call last):
File "", line 1, in
ib_client.create_session()
File "C:\Users\User\anaconda3-64bit\lib\site-packages\ibw\client.py", line 146, in create_session
self.connect(start_server=True)
File "C:\Users\User\anaconda3-64bit\lib\site-packages\ibw\client.py", line 455, in connect
server_state = self._start_server()
File "C:\Users\User\anaconda3-64bit\lib\site-packages\ibw\client.py", line 422, in _start_server
creationflags=subprocess.CREATE_NEW_CONSOLE
File "C:\Users\User\anaconda3-64bit\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in init
super(SubprocessPopen, self).init(*args, **kwargs)
File "C:\Users\User\anaconda3-64bit\lib\subprocess.py", line 800, in init
restore_signals, start_new_session)
File "C:\Users\User\anaconda3-64bit\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
NotADirectoryError: [WinError 267] The directory name is invalid
I´m new to Python, bu tried to find this path or to correct things and couldn´t, can you give an idea of what to do?
Best,
I already mentioned it on your youtube channel, but I thought it might also be prudent to note it here:
In essence, even after authenticating the account at the user's end, the server does not accept the authentication request, so the library can not be used. The image attached shows the VSC terminal, as well as the associated command terminal and website confirmation of authentication.
You mentioned it was due to the order in which endpoints were called, and I'd love to learn more about what in particular is causing that problem.
Thank you!
Hi,
I've got the localhost client setup and authenticated with paper trading account:
Client login succeeds
But when I run the code, it fails:
from ibw.client import IBClient
# Create a new session of the IB Web API.
ib_client = IBClient(
username='xxx',
account='xxx',
)
# create a new session.
ib_client.create_session()
with this error:
COULD NOT CREATE A NEW SESSION THAT WAS AUTHENTICATED, EXITING SCRIPT.
Process finished with exit code 0
client.py
@@ -527,8 +552,37 @@
args=IB_WEB_API_PROC,
cwd=self.client_portal_folder
).pid
-
- return self.server_process
+
+ elif self._operating_system == 'linux':
+ IB_WEB_API_PROC = [self.client_portal_folder+r"/bin/run.sh",r"root/conf.yaml"]
+ process = subprocess.Popen(
+ args=IB_WEB_API_PROC,
+ cwd=self.client_portal_folder,
+ stdout=subprocess.PIPE, universal_newlines=True
+ ).pid
+ time.sleep(2)
+ # get the right process by psutil, the above process takes the pid from run.sh, not the java one
+ for proc in psutil.process_iter():
+ try:
+ processID = proc.pid
+ # processName = proc.name()
+ cmd = proc.cmdline()
+ if any(r"root/conf.yaml" in s for s in cmd) and not any('run.sh' in s for s in cmd):
+ self.server_process = processID
+ break
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ pass
+ # keep alive process
+ IB_WEB_ALIVE = r'while true; do /usr/bin/sleep 300; /usr/bin/curl -ks '+self.ib_gateway_path+'/v1/portal/tickle; done'
+ self.server_alive = subprocess.Popen(args=[IB_WEB_ALIVE], shell=True).pid
+
+ return self.server_process,self.server_alive
Do you have example of placing order or modify order using this lib? I am getting bad request error. Perhaps the format of the order is not correct. I would like to see if you have a working example.
Thanks.
I noticed that recently the authentication process is very often like every few hours, is that something common? or how do we fix it?
I looked through the sample orders in the order/market_order location and its limited to a few samples. I was wondering if anyone can provide me with a sample for options buy/sell. I tried build one out but for some reason its defaulting to STK purchase vs a OPT purchase.
Thanks
Im authencitated and get my accounts without any problem.
But when I try to get my positions the page doesnt exist.
Does portfolio_account_positions work for anybody?
Hey!
I just discovered your repo and YouTube video series. Excellent work! I'm looking to use your application to build my strategy using Interactive Brokers.
What I am a bit confused about, is how to create "custom" types of orders. The IB API docs are confusing and don't really highlight what I'm after. (I typed out a request form on their website and hit "Send" where I was then greeted with a "Something went wrong, please try again later" error message eye roll). I'm thinking this might be better served here anyway as I'm hoping we might discover some new order types to add to your examples/samples to help others!
To keep things simple, I'll pseudocode what the order I'm looking to create should look like:
**Buy Stop-Limit Order for 100 shares of AAPL WITH Trailing Stop Loss.**
Stop price (to trigger the buy Limit order) - $25.00
Limit price (once Buy Stop price is triggered) - $30.00
Trailing Stop Loss (once Buy Stop price is triggered) - $20.00
Trailing Stop Amount (to increment every X) - $1.00
I assume one could make some kind of bracket order, just leaving the Take Profit stuff blank as it's not needed in this case? Some potential issues I see with this above order might be:
Looking at the sample for limit orders included in this repo's docs, and this webpage, I would envision it should look something like:
[
// STOP-LIMIT BUY ORDER, ENTER A POSITION.
{
"conid": 251962528, # <- or whatever AAPL's conid is
"secType": "362673777:STK",
"cOID": "limit-buy-order-1",
"orderType": "STP LMT",
"lmtPrice": 30.00,
"auxPrice": 25.00
"side": "BUY",
"quantity": 100,
"tif": "DAY"
},
// TRAILING STOP, EXIT A POSITION.
{
"conid": 251962528,
"secType": "362673777:STK",
"cOID": "market-sell-order-1",
"orderType": "TRAIL",
"trailStopPrice": 20.00,
"trailingPercent": 0.01, # <- 1%? Is there a way to make this $1.00 as described above?
"side": "BUY",
"quantity": 100, # <- is there a way to make this 100% of position?
"tif": "DAY"
}
]
I noticed there might be something to do with defining the transmit attribute too, which is not included above (as I have no clue what I'm doing yet XD)
Hi,
Thank you for all the work you did on this API.
I've been following the YouTube videos, it seems like the API does not provide support for streaming data.
Could you explain how one might integrate streaming data with the existing functionality?
It would be nice to have a stream of market data, and for those using technical indicators, a bit of historical data to warm up the indicators that require more than 1 pricing data point.
Thank you!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.