Files
trading-bot/notebooks/ibkr_scratch.ipynb
T
2026-08-02 22:18:48 +03:00

2.9 KiB

IBKR scratch notebook

This notebook is for quick manual testing of the IBKR gateway connection, portfolio lookup, and a simple SPY order flow.

Use this only with a paper-trading or test setup unless you explicitly intend to submit a live order.

In [ ]:
import sys
from pathlib import Path

from ib_insync import IB, Stock

# Allow the notebook to import local source code from the repository.
repo_root = Path.cwd().resolve()
if (repo_root / "src").exists():
    repo_root = repo_root
else:
    repo_root = repo_root.parent

src_path = repo_root / "src"
if str(src_path) not in sys.path:
    sys.path.insert(0, str(src_path))

from trading_bot.data.fetch_ibkr_daily import (
    IBKR_CLIENT_ID,
    IBKR_CONNECT_TIMEOUT_SECONDS,
    IBKR_HOST,
    IBKR_PORT,
)

ib = IB()
print(f"Connecting to IBKR Gateway at {IBKR_HOST}:{IBKR_PORT} with client id {IBKR_CLIENT_ID}...")
ib.connect(IBKR_HOST, IBKR_PORT, clientId=IBKR_CLIENT_ID, timeout=IBKR_CONNECT_TIMEOUT_SECONDS)
print("Connection established.")
In [ ]:
print(f"Connected: {ib.isConnected()}")
print(f"Client ID: {ib.clientId}")
In [ ]:
portfolio = ib.portfolio()
if not portfolio:
    print("No open portfolio positions were returned.")
else:
    for item in portfolio:
        print(
            f"{item.contract.symbol}: position={item.position}, "
            f"market_value={item.marketValue}, unrealized_pnl={item.unrealizedPNL}"
        )
In [ ]:
from ib_insync import MarketOrder

contract = Stock("SPY", "SMART", "USD")
ib.qualifyContracts(contract)

# Adjust the quantity as needed before running this cell.
order = MarketOrder("BUY", 1)
trade = ib.placeOrder(contract, order)

print(f"Submitted order for {contract.symbol}: {trade}")