Hello, and welcome to this lesson on the Interactive Brokers Client Portal API. In this tutorial, we will be covering how to configure the Client Portal Gateway, how to authenticate on the Gateway and how to confirm your authentication status. To begin, lets go to the Client Portal API documentation at interactivebrokers.github.io/cpwebapi. The documentation provides all the information you’ll need for utilizing the Client Portal API.
Please note that you will need to have an opened and funded Interactive Brokers account to be able to connect through the Client Portal API.
Setting up and running the Client Portal API Gateway
To begin, let’s first navigate to the Client Portal documentation site, and click on the Quickstart tab on the left. Then, on top right of the Quickstart page you should see the API Gateway and Java download panel for downloading the gateway software and Java installer. The gateway is a Java based program that requires a Java Runtime Environment (JRE) running on your machine. To check if you already have a JRE running, please open the command prompt and type the command ‘java –version’. If you received “’java’ is not recognized as an internal or external command” message, please download and install the Java on your machine following the Java download link. Otherwise, it should return the details of the Java & JRE version, and you are ready to download, extract, and run the gateway. By default, the Client Portal Gateway’s ZIP file will download to your user’s Downloads folder.
Once you have everything downloaded and installed, it is time to run the Gateway and get authenticated. Firstly, open a command prompt terminal and navigate to the directory that you extracted the clientportal.gw folder from step 2. To do this, use the command ‘cd {Your Directory}\clientportal.gw’. Once you are inside the directory, run the command ‘bin\run.bat root\conf.yaml’ for Windows or ‘bin/run.sh root/conf.yaml’ for Unix. Keep in mind to leave this window open while using the Client Portal gateway.
After the new window has been opened, the gateway should be up and running, and it’s ready to authenticate the user’s session. Let’s open a browser and navigate to https://localhost:5000 on your local network then login with your Live or Paper Account credentials.
Please note that you cannot be logged into the account you are authenticating with anywhere else before you authenticate. You should make sure to log out of the account before attempting to authenticate by using the “Log Out” option on our other platforms. Just closing the window or application may cause a stale login session that could prevent the authentication from working properly so using the log out option is important. If the authentication is successful, a new page will load with the message ‘Client login succeeds’. If the page reloads back to this page again, simply log in again.
For any questions you may have regarding authentication, please visit our Authentication page in our documentation, as your question may already be answered here. A few important questions to highlight are: “How long does a session remain authenticated?”, and “How can I prevent the session from timing out?”
Update gateway certificate
The gateway comes with a default certificate. This will likely present an insecure server message when navigating to the page and making requests to your localhost. It is important to note that the insecure connection is between you and your localhost, or the connection on the same machine. The connection between the localhost and Interactive Brokers will remain secure. However, you may replace it with your own self-signed certificate or public certificate. To update the gateway certificate, replace the default certificate with your own certificate under the gateway directory \root and modify the sslCert and sslPwd fields in the conf.yaml file. And if your gateway was already running, be sure to restart the program.
Using /auth/status
Now, let’s start writing a simple program to confirm our authentication status. This can be called at any point to confirm authentication status on your machine. I will start by creating a new Python program and importing a few modules. We can do this by writing “import requests”.
I will also import a library called “urllib3”. This library gives us access to a method to disable SSL errors when using the default certificate. This is not a required module and is used purely for aesthetics. With this, I will write a quick call for “urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)”
I will also create a confirmStatus() method that contains no arguments. For the moment, I will only put “pass” in this method. Afterwards, I will create the Python Name-Main idiom to automatically run our method if this is the primary file, and reference our confirmStatus() method.
With our framework complete, we can return to our confirmStatus() method to call the endpoint. I will begin with a variable, base_url, and set it equal to “https://localhost:5000/v1/api/”. This is the standard base URL for all requests in the Client Portal API. Now, I will create a variable called ‘endpoint’ which I’ll set to “iserver/auth/status”.
Next, we can build the request. To do this, I will call my variable, auth_req, and set it equal to “requests.get(url=base_url+endpoint, verify=False)”. This will create an http GET request, with a targeted URL of our combined base url and endpoint, or “https://localhost:5000/v1/api/iserver/auth/status”. I had also set the ‘verify’ parameter to False, so that we do not require SSL verification on our request. Finally, I will print the “auth_req” variable, as well as “auth_req.text” this will print both the response as well as the response body. Now we can run the code.
If we take a look at our response in the terminal, I can see we received a “<Response [200]>” indicating an “OK” response. This indicates a successful request. Below that, we can see our body, indicating our authentication and connected status’. While there are more values returned, most of these are inconsequential. If we see “connected” equal to false, there may be an issue with the gateway, and you may wish to relaunch your application. If we see “authenticated” to false, your brokerage session is not authenticated. This can mean that either a stale session prevented your login, or you have recently logged in elsewhere, such as the Trader Workstation. This can end your Client Portal session.
Given our Authenticated and Connected status’ showing ‘true’, that means we are fully authenticated and connected and are now ready to send additional queries for market data or order placement.
Thank you for watching this lesson on Configuring the Client Portal Gateway in the Client Portal API. If you find this lesson helpful, please check out our other lessons in the Client Portal API tutorial series.
Code Snippet – confirmStatus.py
import requests # Disable SSL Warnings import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # reauthenticate def confirmStatus(): base_url = "https://localhost:5000/v1/api/" endpoint = "iserver/auth/status" auth_req = requests.get(url=base_url+endpoint,verify=False) print(auth_req) print(auth_req.text) if __name__ == "__main__": confirmStatus()
Yooh, it’s complicated, but helpful
Thank you for the feedback, Vusumuzi. We are glad you found the content helpful.
Is it the same for Mac?
Hello Tom, thank you for asking. Please visit interactivebrokers.github.io/cpwebapi to review the Client Portal API documentation for more information. The Quickstart Guide does provide a slightly different command for Unix systems: https://interactivebrokers.github.io/cpwebapi/quickstart. We hope this helps!
It says the ‘requests’ module is missing. Please help?
Hello, we appreciate your question. Because the Client Portal API is built on a RESTful interface using HTML, we do not provide Python specific libraries for users to implement. For users less familiar with Python module, you will need to download and install these modules using tools such as “pip” or “conda” depending on your enviornment. For more information on this process, we recommend reviewing their respective documentation on installation, available here: https://pypi.org/project/requests/ Please reach back out if you have any more questions. We are here to help!
Are there Node.js examples available?
Hello, thank you for reaching out. At this time, we do not have any Node.js samples. However, we are considering it for future tutorials. We appreciate your interest.
I’m confused, I’ve managed to do it but I thought this was a step to to connect the API to my TWS locally? I guess not since if I open TWS it terminates the connection.
Hello Ed, thank you for reaching out. This lesson is for the Client Portal API. Please note that you cannot be logged into the account you are authenticating with anywhere else before you authenticate. Please view these FAQs for more information about getting started with Client Portal API and TWS API:
https://www.ibkr.com/faq?id=56690671
https://www.ibkr.com/faq?id=54823116
We hope this helps!
I’m not really acustomed with Python and I tried instead to start the same GET request using a REST client (Postman in my case).
Unfortunately, I ended up with a 401 Unauthorized error.
Here’s the CURL command generated by the tool.
curl –location ‘https://localhost:5000/v1/api/iserver/auth/status’ \
–header ‘Cookie: x-sess-uuid=0.dc741002.1703157354.1279980’
Any explanation?
Hello Anonymous, thank you for reaching out. There is no requirement to use Python to operate the Client Portal API after all. A 401 Unauthorized error typically is caused by the user not being fully authenticated through the Client Portal Gateway. Please make sure to keep the Client Portal Gateway running after seeing “Client Login Succeeds”. If you continue to have errors, please free to contact API Support: http://spr.ly/IBKR_CreateWebTicket
Our API experts will be happy to guide you!
OK In the meantime, my session was disconnected.
Reproducing the sequence, I’ve got the following 200 response along with a JSON response.
Hello Anonymous, thank you for reaching out. For this situation, please call client services: http://spr.ly/IBKR_ClientServicesCampus
Saying I’ve the same acount name and password to access the paper trading account, this is not clear how to proceed to log the CPAPI to the paper trading account.
More explanations welcome.
Hi Anonymous, thank you for reaching out. You can connect the Client Portal API to the paper trading account by following these instructions:
1. Log in to the Client Portal
2. Select the Head & Shoulders Icon
3. Click “Settings”.
4. On the left under “Account Configuration” select “Paper Trading Account”
5. You should see a Paper Trading Username, Paper Trading Account Number, as well as options for linking your Market Data.
If you do not know your password already, it is recommended to select “Reset Paper Trading Password” to have a unique password for paper trading. This can be reset at any time.
You may now log in to the Client Portal Gateway using your newfound Paper Trading username and password. Please reach back out if you have any more questions. We are here to help!
Hello Thanks very interesting! I am testing in paper trade, I got . Does that mean my connection is properly authentified? Are there any changes for the script or certificate as I am in paper trade? Thank you
Hello, thank you for reaching out. This error message signifies a length restriction, and that the condition order type does not support this contract. Please view this User Guide for more information: https://interactivebrokers.github.io/tws-api/message_codes.html. If you are still in in need of assistance please feel free to create a web ticket to contact our API experts. They would be happy to help.
https://www.interactivebrokers.com/sso/resolver?action=NEW_TICKET
*I got Response [401]
I am having trouble with paper trading account. I can get session authenticated without any problems when I am logged in with my trading account. However with the same code (python and curl) I can’t get anything done due to
error”: “not authenticated”,
“statusCode”: 401
however the web page where I entered paper trading accounts credentials says “Client login succeeds”.
What’s going on ?
Hello, So my question is how to integrate Interactive Broker Client Portal API with a application as a connector ??
Please visit this website: https://www.ibkrcampusdev.wpengine.com/campus/ibkr-api-page/webapi-doc/
Is there a way to prevent session time out or a way to re-authenticate through the API instead of going to localhost:5000 and login again manually?
Hello, thank you for reaching out. Individuals must use authentication initially through the localhost portal. However, in most scenarios, users can reauthenticate using the /iserver/auth/ssodh/init endpoint. Please review this Campus course for more details: https://www.ibkrcampusdev.wpengine.com/campus/ibkr-api-page/cpapi-v1/#ssodh-init
We hope this answers your question!
Hello, I was trying to hit your Authentication status API from my .net Core application. without disabling SSL certificate validation, I was getting SSL certificate error. and after disabling that I am getting exception like System.Net.Http.HttpRequestException: ‘Response status code does not indicate success: 403 (Forbidden).’ Note : I have logged in https://localhost:5000/ with my credentials before hitting the above API. Can you please let me know where I am going wrong. public async Task APITesting() { try { var apiUrl = “https://localhost:5000/v1/api/iserver/auth/status”; HttpClientHandler handler = new HttpClientHandler(); // Disable SSL certificate validation handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; // Pass the handler to httpclient(from you are calling api) HttpClient client = new HttpClient(handler); // Make the GET request var response = await client.GetFromJsonAsync(apiUrl); // Process the response if (response != null) { var oResponseModel = new ApiResponse { authenticated = response.authenticated, competing = response.competing, connected = response.connected, message = response.message, MAC = response.MAC, serverInfo = response.serverInfo, hardware_info = response.hardware_info, fail = response.fail }; return oResponseModel; } else { throw new Exception(“No data received from the API.”); //Console.WriteLine(“No data received from the API.”); } } catch (HttpRequestException e) { throw new Exception(“No data received from the API.”); } }
Hi, thank you for reaching out. Please create a web ticket for this inquiry; we have a category specifically for “API.” One of our API experts will be happy to guide you! http://spr.ly/IBKR_ClientServicesCampus
How do I solve the new multifactor authentication with automatic login? Can I use a cert or some other solution to automatically reconnect?
Hello, thank you for reaching out. IBKR requires all users to be two-factor authenticated and does not allow users to partially or fully opt out.
Please view this FAQ for more details: https://www.ibkr.com/faq?id=29079898
Please reach back out with any additional questions. We are here to help!
I installed the API Gateway and successfully authenticated and logged in the broker session, but after a while, even sending commands in /tickle, my connection drops (error 401). I don’t understand what’s happening. Can you help me?
Hello Humberto, thank you for reaching out. A 401 Unauthorized error typically is caused by the user not being fully authenticated through the Client Portal Gateway. Please make sure to keep the Client Portal Gateway running after seeing “Client Login Succeeds”. If you continue to have errors, please free to contact API Support: http://spr.ly/IBKR_CreateWebTicket
Our API experts will be happy to guide you!
Same issue as Humberto has: after a while, despite proper tickles, I get 401 and have to re-authenticate. No issues with Internet connection, it’s something with the API gateway and it’s quite severe: it’s basically breaking the advertised behavior that once logged-in, the session should last for 24h (with proper tickles of course).
Hello John, thank you for reaching out. A 401 Unauthorized error typically is caused by the user not being fully authenticated through the Client Portal Gateway. Please make sure to keep the Client Portal Gateway running after seeing “Client Login Succeeds”. If you continue to have errors, please free to contact API Support: http://spr.ly/IBKR_CreateWebTicket
Our API experts will be happy to guide you!