GithubHelp home page GithubHelp logo

utilmon / easyib Goto Github PK

View Code? Open in Web Editor NEW
84.0 6.0 24.0 1.09 MB

Python wrapper for Interactive Brokers Client Portal Web API

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
python interactive-brokers client-portal rest-api trading-api

easyib's Introduction

EasyIB: Python Wrapper for Interactive Brokers API

https://img.shields.io/pypi/v/easyib https://img.shields.io/pypi/pyversions/easyib https://img.shields.io/pypi/l/easyib Documentation Status

https://raw.githubusercontent.com/ashpipe/EasyIB/main/docs/logo.png

"Logo for 'EasyIB'" according to Midjourney


EasyIB is an unofficial python wrapper for Interactive Brokers Client Portal Web API. The motivation for the project was to build a Python wrapper that can run on Linux/cloud environments. Thus, Client Portal API was preferred over Trader Workstation (TWS) API.

Please see https://easyib.readthedocs.io for the full documentation.

Features

Notable functionality includes:

  • Pull account info, portfolio, cash balance, the net value
  • Pull historical market data
  • Submit, modify, cancel orders
  • Get order status, list of live orders
  • Ping (tickle) server, get authentication status, re-authenticate

How to install

EasyIB assumes a gateway session is active and authenticated. Follow instructions at https://interactivebrokers.github.io/cpwebapi/ for authentication. A custom package such as Voyz/IBeam can also be used for setting up an active session. Part Time Larry has an excellent youtube tutorial on this topic: https://www.youtube.com/watch?v=O1OhiiCx6Ho.

EasyIB was developed under the Voyz/IBeam docker image environment. You can verify if a gateway session is active by typing curl -X GET "https://localhost:5000/v1/api/one/user" -k at bash terminal.

Once a gateway session is running, pip command can be used to install EasyIB:

pip install easyib

Quick start

Historical data

import easyib

ib = easyib.REST() # default parameters: url="https://localhost:5000", ssl=False

bars = ib.get_bars("AAPL", period="1w", bar="1d")
print(bars)

Submitting an order

list_of_orders = [
    {
        "conid": ib.get_conid("AAPL"),
        "orderType": "MKT",
        "side": "BUY",
        "quantity": 7,
        "tif": "GTC",
    }
]

order = ib.submit_orders(list_of_orders)
print(order)

Reference

For the complete reference, please visit https://easyib.readthedocs.io/en/latest/reference.html.

REST

By default, EasyIB assumes the gateway session is open at https://localhost:5000 without an SSL certificate. A custom URL and SSL certificate can be set by:

ib = easyib.REST(url="https://localhost:5000", ssl=False)

API REST Methods

Documentation of available functions is at https://easyib.readthedocs.io/en/latest/reference.html.

See the official documentation of the End Point at https://www.interactivebrokers.com/api/doc.html.

REST Method End Point Result
get_accounts() Get portfolio/accounts list
switch_account(accountId: str) Post iserver/account/{accountId} dict
get_cash() Get portfolio/{accountId}/ledger float
get_netvalue() Get portfolio/{accountId}/ledger float
get_conid(symbol: str, instrument_filters: Dict = None, contract_filters: Dict = {"isUS": True}) Get trsv/stocks int
get_fut_conids(symbol: str) Get trsv/futures list
get_portfolio() Get portfolio/{accountId}/positions/0 dict
reply_yes(id: str) Post iserver/reply/{id} dict
submit_orders(list_of_orders: list, reply_yes=True) Post iserver/account/{acountId}/orders dict
get_order(orderId: str) Get iserver/account/order/status/ dict
get_live_orders(filters=None) Get iserver/account/orders dict
cancel_order(orderId: str) Delete iserver/account/{accountId}/order/{orderId} dict
modify_order(orderId=None, order=None, reply_yes=True) Post iserver/account/{accountId}/order/{orderId} dict
get_bars(symbol: str, period="1w", bar="1d", outsideRth=False, conid="default") Get iserver/marketdata/history dict
ping_server() Post tickle dict
get_auth_status() Post iserver/auth/status dict
re_authenticate() Post iserver/reauthenticate None
log_out() Post logout None

easyib's People

Contributors

goldenchrysus avatar jb2483 avatar ruphy avatar utilmon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

easyib's Issues

Key error on placing order

Hi, when I try to create an order I'm getting this message (not always). It's something to do with how it's handling the response during the "reply all" flow (if the response has no position 0). Any thoughts please? Thanks!

placing order for AAPL
Traceback (most recent call last):
  File "/home/xxx/minute_screener_update_dev.py", line 660, in create_order
    response = api.submit_orders(orders, True)
  File "/home/xxx/.local/lib/python3.9/site-packages/easyib/easyib.py", line 191, in submit_orders
    return self._reply_all_yes(response, reply_yes)
  File "/home/xxx/.local/lib/python3.9/site-packages/easyib/easyib.py", line 167, in _reply_all_yes
    dic = response.json()[0]
KeyError: 0

get_bars() not working

This is very nice work! I tried most of the functions and they work well, however, when I run the get_bars() example I get the following error:

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    bars = ib.get_bars("AAPL", period="1w", bar="1d")
  File "/home/rod/Projects/tradingview/ibapi.py", line 252, in get_bars
    return response.json()
  File "/home/rod/Projects/tradingview/venv/lib/python3.8/site-packages/requests/models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

how to get futures data and place orders

As I mainly trade futures I am wondering how to get futures data and place orders? Doing the following:

bars = ib.get_bars("NG", period="1w", bar="1d")
print(bars)

Results in the following error:

{'error': "No data of type EODChart is available for the exchange 'VALUE' and the security type 'Stock' and '1 W' and '1 day'"}

Using ibapi the sequence would go something like this:

contract = Contract()
contract.symbol = 'NG'
contract.exchange = 'NYMEX'
# contract.secType = 'CONTFUT'
contract.secType = 'FUT'
contract.lastTradeDateOrContractMonth  = '202109'

app.reqHistoricalData(1, contract, '20210815 17:59:00', '10 D', '15 mins', 'BID', 0, 2, False, [])

How would this be done using EasyIB?

Can't get portfolio

Hi, I keep getting the error below when I try to get my portfolio. This is a new paper account with no portfolio in place yet, so I'd expect it to return an empty portfolio instead of an error? I've tried restarting ibeam and my server but the error persists. Other service calls work. Any ideas much appreciated! Thanks

Traceback (most recent call last):
  File "/home/xxx/test.py", line 72, in <module>
    print(api.get_portfolio())
  File "/home/xxx/.local/lib/python3.9/site-packages/easyib/easyib.py", line 98, in get_portfolio
    for item in response.json():
  File "/usr/lib/python3/dist-packages/requests/models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is EasyIB still working?

I am using a PAPER account for the test.

Some of requests work, but some of them do not work.
Do you have any idea how to fix them?

① Get live orders

Response:
{'error': 'Please query /accounts first'}

② Get auth status, Get ping server
→ This one works, but why I am not still authenticated?

Response:
{'authenticated': False,
'competing': False,
'connected': False,
'MAC': 'F4:03:43:DA:99:00'}

{'session': '8ce8747753be3a9f1bebe610b3b743 c6',
'ssoExpires': 0,
'collission': False,
'userId': 102651152,
'hmds': {'error': 'no bridge'},
'iserver': {'authStatus': {'authenticated': False,
'competing': False,
'connected': False,
'MAC': 'F4:03:43:DA:99:00'}}}

③ Switch account

Response:
{'error': 'Init session first', 'statusCode': 400}

④ Get Bars (market data)

Response:
{'error': 'Init session first', 'statusCode': 400}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.