A Python scanner can reach a broker in two ways. The script can call the broker's order API itself, or it can post each alert to a small web service you run, which then places the order. Both routes need an id that ties each alert to one order and a status check before any retry. Run the whole path on a paper account first.
The sender below is 55 lines of Python on the Requests library. It targets Alpaca's paper API as an illustration, because its order and lookup routes are documented in public.
Should the scanner call the broker or use a relay?
Calling the API directly means the scanner holds the broker keys and sends the order from the process that found the setup. You run one program and read one log. That suits a single script on a machine you control.
A relay is a small HTTP service you host. The scanner posts a short JSON alert to it, and the relay keeps the keys and talks to the broker. The split pays off when several scanners feed one account, or when the scanner runs somewhere you would not store keys. It also lets a charting tool share the same entry point, since a TradingView webhook alert arrives as an HTTP POST with the alert's message as its body.
A relay costs you a public endpoint to secure and one more hop that can fail. It also has a deadline when TradingView is the sender. The same guide says TradingView cancels a webhook request when the receiving server needs more than three seconds. A relay should acknowledge the alert before it starts talking to the broker.
The order logic is identical in both designs.
What does the broker need in an order request?
Alpaca's create-order reference takes a JSON body on POST /v2/orders. Its example for buying shares carries symbol, qty, side, type, time_in_force and limit_price. The authentication page says to "Use the APCA-API-KEY-ID and APCA-API-SECRET-KEY headers to send your key ID and secret key."
A scanner should add client_order_id, which the reference describes as "A unique identifier for the order. Automatically generated if not sent. (<= 128 characters)". The lookup reference adds that "Once an order is placed, it can be queried using the client-side order ID to check the status."
An alert already has an identity made of its symbol, its direction and the bar that triggered it. Hash those three into the client_order_id and one alert always yields one id, however many times the script sees it.
How do you stop one alert becoming two orders?
Duplicates have two causes. A scanner can find the same setup on consecutive passes. A request can also fail in a way that hides whether the broker received it, since a timeout after the order was accepted looks identical to a request that never arrived.
Broker docs are direct about the second cause. tastytrade's idempotency guide says "tastytrade does not provide a generic Idempotency-Key header, so safe retries are a client-side discipline." For an uncertain response its instruction is "do not blindly resubmit."
Alpaca's reference doesn't state what a repeated client_order_id returns, so the sender doesn't rely on the broker to reject it. It looks the id up before every send, and again after any uncertain response.
import hashlib
import os
import requests
BASE = os.environ.get("BROKER_BASE_URL", "https://paper-api.alpaca.markets")
HEADERS = {
"APCA-API-KEY-ID": os.environ["BROKER_KEY_ID"],
"APCA-API-SECRET-KEY": os.environ["BROKER_SECRET_KEY"],
}
TIMEOUT = (3.05, 10)
def order_key(symbol, side, bar_time):
raw = f"{symbol}|{side}|{bar_time}"
return "scan-" + hashlib.sha256(raw.encode()).hexdigest()[:32]
def find_order(key):
r = requests.get(
f"{BASE}/v2/orders:by_client_order_id",
params={"client_order_id": key},
headers=HEADERS,
timeout=TIMEOUT,
)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json()
def send_once(symbol, side, qty, limit_price, bar_time):
key = order_key(symbol, side, bar_time)
existing = find_order(key)
if existing:
return existing
body = {
"symbol": symbol,
"qty": str(qty),
"side": side,
"type": "limit",
"limit_price": str(limit_price),
"time_in_force": "day",
"client_order_id": key,
}
try:
r = requests.post(
f"{BASE}/v2/orders", json=body, headers=HEADERS, timeout=TIMEOUT
)
except requests.exceptions.RequestException:
return find_order(key)
if r.status_code >= 500:
return find_order(key)
r.raise_for_status()
return r.json()
order_key builds the id from the alert. find_order asks the broker whether that id exists. send_once returns the existing order when there is one and posts when there isn't. After a network error or a 5xx it looks again instead of posting again. A result of None means the broker has no record yet, and the next scanner pass repeats the same steps under the same id.
Confirm one detail on your own paper account. The lookup reference documents only a 200 response, and the code assumes an unknown id answers 404.
Every call carries a timeout, because the Requests docs warn that "If no timeout is specified explicitly, requests do not time out."
Which failed requests are safe to retry?
tastytrade's guide sorts responses into four groups, and the grouping works as a default for any order API.
| Response | Retry? | What the sender does |
|---|---|---|
2xx |
No | Returns the order |
4xx except 429
|
No, fix the request | Raises HTTPError
|
429 |
Yes, after backoff | Raises, and the caller waits before the next pass |
5xx or a network error |
Yes, after a status check | Looks the id up and never posts twice in one call |
Alpaca lists two rejections on order creation, 403 "Buying power or shares is not sufficient." and 422 "Input parameters are not recognized." A retry changes neither, so send_once raises on both and leaves the decision to the caller.
What does a paper account prove?
A paper account proves the plumbing. Alpaca's paper trading page says "Paper trading works the same way as live trading end to end - except the order is not routed a live exchange." It adds that "Your paper trading account will have a different API key from your live account" and that "The API spec is the same between the paper trading and live accounts." Going live later changes the keys and the base URL, and the code stays as it is.
Fill quality is a separate question. The same page says paper trading "is not a substitute for real trading and performance may differ", and its list of what the simulator leaves out includes "Price slippage due to latency" and "Market impact of your orders". Size isn't modeled either, since "Your order quantity is not checked against the NBBO quantities."
Sandboxes vary by broker. Tradier's sandbox is "a paper trading account to test your integration with our API, including working with delayed market data and paper trades." Tradier can also validate an order without placing it. With preview=true on the preview route, "all order validation rules are run, including buying power checks." tastytrade's sandbox page says orders there "never reach a real market" and that "The environment resets every 24 hours".
What happens to an order sent outside market hours?
Scanners that work on daily bars usually finish after the close. Alpaca's orders page says of a day order, "By default, the order is only valid during Regular Trading Hours (9:30am - 4:00pm ET)." It continues, "If submitted after the close, it is queued and submitted the following trading day." The order then waits overnight with a limit price set before the close.
An order sent outside the session often shows the status accepted, which the page defines as "The order has been received by Alpaca, but hasn't yet been routed to the execution venue." Log that status as pending and keep polling until the broker reports a fill or a cancel.
For trading outside the regular session, that page says "Only limit orders with time_in_force set to day or gtc orders are accepted as extended hours eligible."
A script can read the session state before it sends. Alpaca's clock route "serves the current market timestamp, whether or not the market is currently open, as well as the times of the next market open and close." Tradier's market clock returns a state of premarket, open, postmarket or closed.
What changes with a different broker?
The pattern carries over to other brokers, but field names and dedupe behavior differ.
| Broker | Field for your own id | Does the broker dedupe on it? | Check without placing |
|---|---|---|---|
| Alpaca | client_order_id |
Not stated in the reference | Paper account |
| tastytrade | external-identifier |
No, "a repeated id does not stop a second order from being placed" | Dry-run route |
| Tradier |
tag, a "User-defined tag for the order" |
Not stated in the reference | preview=true |
Where the docs are silent, assume the broker will accept the duplicate and keep the lookup in your own code.
What should you check before the first live order?
| Check | How to run it on paper | A pass looks like |
|---|---|---|
| Same alert twice | Call send_once twice with one bar time |
One order at the broker |
| Lost reply | Cut the network after the request leaves | The lookup returns the order and no second post goes out |
| Rejection | Ask for more shares than the account can buy |
403 raised, nothing retried |
| After the close | Send a day order after 4:00pm ET |
The order is held for the next session and no fill is logged early |
| Unknown id | Look up an id you never sent | The status your broker uses for "not found" |
Keep the paper keys in place until every row passes.
AI tools wrote this article. Its facts were checked against the official docs linked above, and its code was run against a stubbed exchange.
Trading involves risk of loss.
Top comments (0)