pythonstockalgorithmic-tradinginteractive-brokers

How to Implement Simple IBKR Buy and Sell Using Web API


I am currently developing a simple IBKR trading bot in Python.
I want the bot to do these operations daily:

  1. sell all of my owned stocks (when market opens)
  2. use the entire money to buy a recommended symbol that I generate (after I sell everything)

I don't have an account yet, but to minimize my inactivity time on the IBKR platform, I want to know how to implement what I want beforehand.

What I have now from my limited understanding:

def main():
    sell_stock(previous_day_stock)
    buy_stock(daily_recommended_stock)

def get_available_money():
    return requests.get(f"https://localhost:5000/v1/api/portfolio/{account_id}/summary").json()["availablefunds"]["amount"]

def get_owned_stocks_value():
    return requests.get(f"https://localhost:5000/v1/api/portfolio/{account_id}/positions/").json()["avgPrice"]

def buy_stock(symbol):
    account_id = 1234
    payload = {
        "conid": get_contract_id(symbol),
        "secType": "STK",
        "orderType": "MKT",
        "cashQty": get_available_money(),
        "side": "BUY",
        "tif": "DAY"
    }

    return requests.post(f"https://localhost:5000/v1/api/iserver/account/{account_id}/orders", payload)

def sell_stock(symbol):
    account_id = 1234
    payload = {
        "conid": get_contract_id(symbol),
        "secType": "STK",
        "orderType": "MKT",
        "cashQty": get_owned_stocks_value(),
        "side": "SELL",
        "tif": "DAY"
    }

    return requests.post(f"https://localhost:5000/v1/api/iserver/account/{account_id}/orders", payload)

def get_contract_id(symbol):
    return requests.get(f"https://localhost:5000/v1/api/trsrv/stocks/symbols={symbol}").json()["contracts"]["conid"]

I feel like the way I'm doing it is not correct, and I don't have access to the API yet to understand what I should do, and if my code even makes sense. I'd love to know the correct way to do what I want.


Solution

  • Firstly, you can access the ibapi library without having an IB account - it's just a python library downloaded from pypi (https://pypi.org/project/ibapi/) or interactive brokers (https://interactivebrokers.github.io). You should do this as it provides all the objects, functions and callbacks you will need to interact with the API/TWS.

    The tasks you outline will require quite a bit of work to program, but in rough outline the steps you will need are:

    1. Establish a connection to the TWS via the API
    2. Request current position information using reqAccountUpdates or reqPositions
    3. Receive position information via the position callback
    4. Iterate through the positions and generate a Contract and an Order object to place your exit order for each position.
    5. Place the exit orders using placeOrder
    6. Wait for positions to exit, and confirm by viewing order status via reqopenOrder and openOrder callback
    7. Determine your available funds using the updateAccountValue callback
    8. Place your entry order using another Contract and Order objects in placeOrder

    Details on all of these are available in the API documentation here https://interactivebrokers.github.io/tws-api/

    You should note carefully that it will very much be a non-trivial exercise to program even this simple set of procedures, and the more you program the more you will discover things you hadn't thought of that will require additional time/programming.

    I'm not sure it's the right approach to try to code it all before setting up an account. You will only discover most of the issues when you start using your code with the TWS.