I am currently developing a simple IBKR trading bot in Python.
I want the bot to do these operations daily:
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.
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:
reqAccountUpdates
or reqPositions
position
callbackContract
and an Order
object to place your exit order for each position.placeOrder
reqopenOrder
and openOrder
callbackupdateAccountValue
callbackContract
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.