# How to Connect Python to Your Broker's API and Place Your First Automated Order

AI agents: this is one page from QuantIDE's site, in Markdown.
Canonical HTML: https://www.quantide.io/guides/connect-python-to-broker-api-first-automated-order
Full index of Markdown pages: https://www.quantide.io/llms.txt
Full text of recent articles: https://www.quantide.io/llms-full.txt

---
*2026-11-19 · QuantIDE Team · 5 min read*

Connecting Python to a broker takes about an hour the first time, and most of it is setup, not code. Here is the full path — Alpaca and Interactive Brokers, paper first — with code that was actually run.

## In brief

- Connect to paper first: Alpaca paper=True or IBKR paper TWS on port 7497 — the live switch is one flag, so verify the host every time.
- Size the order from risk before you build it: dollars at risk divided by distance to the stop.
- Submitted is not filled: confirm the fill status before doing anything else.
- TWS API 10.40 added a Python-only synchronous wrapper that removes the classic callback plumbing.

## The short answer

Connecting Python to your broker takes about an hour the first time, and most of that hour is setup, not code. Pick a broker with a real paper-trading API, install its official Python library, connect to the paper endpoint, size the order from your risk limit, submit it, and then confirm the fill. Submitted is not filled. Everything below runs against paper money first. The switch to live is one flag — and that is exactly why it deserves respect.

## Pick the broker by its API, not its app

Two brokers cover almost every first automation, and they work differently. Alpaca is REST-based: you send HTTPS requests to an API host, no software running on your machine. Its paper host is `paper-api.alpaca.markets`, its live host is `api.alpaca.markets`, and paper and live keys are separate — a live key does not work on the paper API, or the other way round. Paper trading is free and opens with a $100,000 simulated balance.

Interactive Brokers works through the Trader Workstation (TWS) API: your code talks over a local socket to TWS or IB Gateway running on your machine, which forwards orders to IB. The default ports tell you which world you are in — 7497 for paper TWS, 7496 for live TWS, 4002 for paper Gateway, 4001 for live Gateway. The API is free to use, but the local app has to be running and API access has to be enabled in its settings before your code can connect at all.

There is also a genuinely new reason to look at IBKR now. With TWS API 10.40, Interactive Brokers shipped a synchronous wrapper class (`TWSSyncWrapper`) that returns values directly from the call instead of through separate streaming callbacks — the classic async `EClient`/`EWrapper` dance, collapsed. It is Python-only, and the official docs were updated for it on October 20, 2026. If you have ever bounced off the IBKR API because of its callback plumbing, that is the version to start from.

Choose Alpaca if you want the shortest path to a first order in US stocks. Choose IBKR if you want the widest market access — stocks, options, futures, forex — and you are willing to keep a Gateway running. Either way, the rest of the flow is the same.

## Step 1: Connect — and prove you're on paper

With Alpaca, the whole connection is a client object. Keys live in environment variables, never in the code:

```python
import os
from alpaca.trading.client import TradingClient

client = TradingClient(
    os.environ["APCA_API_KEY_ID"],
    os.environ["APCA_API_SECRET_KEY"],
    paper=True,  # paper-api.alpaca.markets, never the live host
)
```

The `paper=True` flag is the entire difference between practice and real money. Before you submit anything, print the account and read it: a paper account shows the simulated balance. If the number looks like your real money, stop — you are on the wrong host.

With IBKR, the connection is a socket to the local app, and the port is the tell:

```python
# Paper TWS on 7497. Live TWS is 7496 — one digit apart.
# If TWS or Gateway is not running, this fails immediately.
ib.connect("127.0.0.1", 7497, clientId=1)
```

## Step 2: Size the order from risk, not from confidence

Never decide the share count by feel. Decide the dollars you are willing to lose on the trade, then let the distance to your stop set the size. This is the function that runs before any order in the code below:

```python
def size_position(account_equity, risk_pct, entry, stop):
    risk_dollars = account_equity * risk_pct
    per_share_risk = entry - stop
    return int(risk_dollars // per_share_risk)

shares = size_position(100_000, 0.01, 250.00, 245.00)
# 200 shares: 1% of $100k is $1,000 of risk, $5 of risk per share
```

Risking 1% of a $100,000 paper account with a $5 stop means 200 shares. Change the stop and the size changes with it — that is the point. Sizing is the risk control; the order is just the delivery mechanism. If you skipped the [backtesting guide](/guides/how-to-backtest-a-trading-strategy-in-python), run the strategy there first: an order is only as good as the rule behind it.

## Step 3: Build the order, then submit it

An Alpaca order is a request object passed to `submit_order()`. This is the exact code from the dry run — executed against the real SDK, with the broker side stood in locally so no keys or live connection were involved:

```python
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

order = MarketOrderRequest(
    symbol="SPY",
    qty=200,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY,
)
client.submit_order(order)
```

The IBKR shape is the same idea with more ceremony. You describe the instrument as a `Contract` and the instruction as an `Order`, and you hold it with `transmit=False` until every check has passed:

```python
from ibapi.contract import Contract
from ibapi.order import Order

contract = Contract()
contract.symbol = "SPY"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"

order = Order()
order.action = "BUY"
order.orderType = "LMT"
order.totalQuantity = 200
order.lmtPrice = 250.00
order.transmit = False  # held until the checks pass
```

A market order buys at whatever the market gives you; a limit order buys only at your price or better. For a first automated order, use a limit. It is the cheapest insurance in the whole flow, and it costs nothing to add.

## Step 4: Confirm the fill — submitted is not filled

A successful `submit_order` means the broker accepted the order, not that it filled. Check the status before you do anything else — with Alpaca, `client.get_order(order.id)`; with IBKR, the `orderStatus` callback reports `Submitted`, then `Filled`, with the filled quantity and average price. Only a `Filled` status with the quantity you asked for closes the loop.

One paper-trading caveat, stated plainly: Alpaca's simulator fills against current quotes but does not simulate slippage, market impact, dividends, or regulatory fees. A paper fill is proof your plumbing works, not proof your strategy makes money. Treat it as a wiring test and nothing more.

## Four ways a first order goes wrong

**The paper/live mix-up.** Port 7496 instead of 7497, or `paper=False` on a live key. Both mistakes place real orders. Check the account balance and the host before every submit, every time.

**A market order at the open.** The first minutes of the session are the most volatile of the day. A market order there can fill far from the last price you saw. Use a limit order until you know your fill behaviour.

**No stop, no size.** An order without a sizing rule is a bet sized by mood. The sizing function above takes four lines. There is no version of this flow where skipping it is the careful choice.

**Keys in the code.** API keys pasted into a script end up in screenshots, repos, and shared folders. Environment variables, always. If a key has ever appeared in a file you shared, rotate it.

## What to do next

Run the dry run above, then place a one-share paper order, then run a week of paper orders before you touch the live flag. The full loop — signal, sizing, order, execution, monitoring — is the same five-stage system in [Automating a Trading Strategy End to End](/guides/automating-a-trading-strategy-end-to-end); this piece is the one stage where code meets a real broker, and it is the stage worth going slowest on. If your strategy runs on TradingView, the same gap applies in reverse: [QuantIDE vs TradingView](/vs/quantide-vs-tradingview) explains why a Pine Script strategy needs a bridge to go live at all — and Interactive Brokers is one of the brokers it can go live on, via [QuantIDE for Interactive Brokers](/for/interactive-brokers).

If you would rather have an engineer wire the connection, the sizing, and the monitoring up for you than build it yourself, that is what the engineering desk inside [Blackshore Technologies](https://www.blackshoretechnologies.com/) does: describe the strategy, it comes back built, with the broker connection included. Either way, the first order goes to paper. No exceptions.

## Frequently asked questions

### Do I need a funded account to use a broker API?

No. Alpaca paper trading is free with a $100,000 simulated balance and separate paper keys. Interactive Brokers paper trading needs an account and TWS or IB Gateway running locally.

### Can I place my first order without running TWS?

With Alpaca, yes — it is REST-based and needs no local app. With Interactive Brokers, no — your code connects to TWS or IB Gateway on your machine, on port 7497 for paper or 7496 for live.

### How do I know the order actually filled?

A successful submit means the broker accepted the order, not that it filled. Check the order status — Alpaca's get_order or IBKR's orderStatus callback — and look for Filled with the quantity and average price you expected.


## Sources

- [Interactive Brokers — TWS API 10.40 Synchronous Wrapper introduction](https://www.interactivebrokers.com/docs/tws-api/sync-doc/introduction)
- [Interactive Brokers — Automate Trading with Interactive Brokers Python API](https://www.interactivebrokers.com/campus/ibkr-quant-news/automate-trading-with-interactive-brokers-python-api/)
- [Interactive Brokers API Tutorial 2026: Connect, Trade, Stream](https://www.quantt.co.uk/resources/interactive-brokers-api-tutorial)
- [Alpaca — Build and Backtest Bollinger Bands with Alpaca's Trading API](https://alpaca.markets/learn/how-to-build-backtest-bollinger-bands-strategy-with-alpaca-mcp-server)
- [Alpaca API Guide: Build a Python Trading Bot (2026)](https://www.quantvps.com/blog/alpaca-api-python-trading-bot)

*Educational content, not investment advice. Trading involves risk of loss.*