Steps to Find Open Positions and Close Them
Set Up IBKR API:
Start the IB Gateway or Trader Workstation (TWS) in API mode.
Ensure that API access is enabled and set up the port (default: 7497 for live trading or 7496 for paper trading).
Authenticate via IBKR REST API:
Authenticate using the IBKR Client Portal API or directly through your gateway.
Find Open Positions: Use the /portfolio/accounts and /portfolio/{accountId}/positions endpoints to retrieve the list of open positions.
Close Positions:
Use the /iserver/account/{accountId}/orders endpoint to place a sell order for the open position.
fetch code from https://github.com/CAAutomation/IKBR-api/blob/main/find-open-positions-and-close
Key API Endpoints
Authenticate:
POST /portal/auth
Get Accounts:
GET /portfolio/accounts
Get Open Positions:
GET /portfolio/{accountId}/positions
Close Position (Place Order):
POST /iserver/account/{accountId}/orders
Notes
Authentication: Replace YOUR_ACCESS_TOKEN with a valid token obtained during authentication.
Contract ID (ConId): Retrieve the conid of the position from the /positions API.
Order Type: Use MKT for market orders or LMT for limit orders.
Testing Environment: Test in the IBKR Paper Trading account to avoid live trading risks.