Market vs Limit vs Stop vs Stop-Limit Order API Guide
In a market vs limit vs stop vs stop-limit order API, market has no price, limit sets a worst acceptable price, stop uses stop_price only as a trigger that becomes a market order, and stop-limit triggers into a limit order.
- A stop_price is a trigger and never a fill guarantee: a stop becomes a market order, a stop-limit becomes a limit order.
- IBKR stores the stop trigger in auxPrice, while Alpaca and ccxt use stop_price and stopPrice/triggerPrice respectively.
- A backtest must fill gaps at the open, not at the stop or limit price, or it will overstate results.
- Stop-limit needs two stages (trigger, then limit) and an explicit rule for what happens when both occur in one bar.
- Track fills as events (filled_qty, average price, remaining) because IOC, DAY and GTC orders can all fill partially.
What do the four order types mean in a stop-limit order API?
Every stop-limit order API, and every other broker API, reduces to the same two questions: is there a trigger, and is there a price cap? Market has neither. Limit has a cap. Stop has a trigger. Stop-limit has both.
The mistake that causes most bugs is treating stop_price as a price you will get. It is only the condition that releases the order.
| Type | Trigger field | Price field | Fill behaviour | Main failure mode |
|---|---|---|---|---|
| Market | none | none | Takes best available liquidity now | Slippage; rejected in some sessions |
| Limit | none | limit_price (worst acceptable) | Buy fills at or below, sell at or above | Never fills; marketable limit fills at once |
| Stop | stop_price | none | Becomes a market order once triggered | Fills far past stop in a gap or fast move |
| Stop-limit | stop_price | limit_price | Becomes a limit order once triggered | Triggers but never fills |
How do the field names map across Alpaca, IBKR and ccxt?
The semantics are identical across brokers. Only the names differ, and IBKR hides the stop trigger in a field named auxPrice.
OANDA is different in kind: its STOP order is a pending entry order with a price and a triggerCondition (DEFAULT, INVERSE, BID, ASK, MID), and its protective stops are attached to a trade.
| Concept | Alpaca | IBKR | ccxt (unified) |
|---|---|---|---|
| Order type | type: market, limit, stop, stop_limit | orderType: MKT, LMT, STP, STP LMT | type: market, limit (plus params) |
| Limit price | limit_price | lmtPrice | price argument |
| Stop trigger | stop_price | auxPrice | params stopPrice or triggerPrice |
| Time in force | time_in_force | tif | params timeInForce |
| Client id | client_order_id | orderRef (id is numeric orderId) | params clientOrderId |
# Alpaca REST body: POST /v2/orders
stop_limit = {
"symbol": "AAPL", "qty": "10", "side": "buy",
"type": "stop_limit", "time_in_force": "gtc",
"stop_price": "201.00", "limit_price": "201.50",
"client_order_id": "bot-0001",
}
# Interactive Brokers via ib_insync
from ib_insync import Order
o = Order(action="BUY", totalQuantity=10, orderType="STP LMT",
lmtPrice=201.50, # limit
auxPrice=201.00, # stop trigger lives here
tif="GTC")
# ccxt: unified trigger parameter; support varies, check exchange.has
ex.create_order("BTC/USDT", "limit", "buy", 0.01, 64000,
params={"triggerPrice": 63900, "timeInForce": "GTC"})
# Plain stop (market after trigger) on exchanges that support it:
ex.create_order("BTC/USDT", "market", "sell", 0.01,
params={"stopLossPrice": 60000})Which side of the market must each price sit on?
Direction rules are what validators check first. A buy stop sits above the market and a sell stop below, because a stop fires when price moves toward it. A buy limit sits below the market and a sell limit above.
Put a limit on the wrong side and it becomes a marketable limit: it fills immediately at the best available price, which is at or better than your limit. Put a stop on the wrong side and the broker either rejects it (messages like "stop price would trigger immediately") or triggers it at once.
For a buy stop-limit, limit_price >= stop_price is the normal relationship. If limit < stop, the order can trigger at the stop while the market is already above your limit, so it rests unfilled. A wide gap raises fill probability but lets the fill price drift. A narrow gap does the reverse. That is the fill certainty versus price certainty trade-off in engineering terms, and it is a parameter you should test in simulation rather than guess.
The trigger reference also matters. Equities brokers usually use last trade, though some use bid for sells and ask for buys. Crypto and futures venues often expose a trigger price type: last, mark or index. Mark price can trigger a stop while the last trade never touched it, so a backtest on trade bars can disagree with the live account.
Which time-in-force values apply, and how do partial fills work?
Time in force decides how long the order lives and what happens to the unfilled remainder.
Alpaca accepts day, gtc, opg, cls, ioc and fok on whole-share orders. Fractional orders are DAY only. extended_hours=true works only with a limit order and DAY. Alpaca also expires GTC orders after a fixed period (90 days at the time of writing), so a long-lived order needs a refresh routine. IBKR adds GTD with a goodTillDate. OANDA uses GTC, GTD, GFD, FOK and IOC.
| TIF | Meaning | Partial fill outcome |
|---|---|---|
| DAY | Valid to the session close | Remainder rests, then expires |
| GTC | Good until cancelled (broker cap applies) | Remainder rests on the book |
| IOC | Fill what is available now | Remainder cancelled at once |
| FOK | Fill everything now or nothing | No partial fills; cancelled if it cannot fill fully |
| OPG / CLS | Opening or closing auction only | Fills in the auction or expires |
| GTD | Good until a stated date or time | Remainder rests until the date |
- Treat every fill as an event with its own quantity and price, never as a single final state.
- Keep filled_qty and avg_fill_price from the broker, and also compute remaining = qty - filled_qty yourself.
- Handle the status path: new or accepted, then partially_filled (repeatable), then filled, canceled, expired or rejected.
- On reconnect, re-fetch open orders and recent executions and reconcile by order id. Do not assume a missed event means nothing happened.
- Make the handler idempotent, because streams can redeliver the same fill.
Why was my limit or stop order rejected by the API?
Rejections come from three places: account checks (money, permissions), instrument rules (tick, lot, notional) and order-state rules (session, price side, duplicate ids). The messages below are paraphrased, since exact wording differs by broker and version.
| Cause | Typical signal | Fix |
|---|---|---|
| Insufficient buying power or margin | Alpaca 403 "insufficient buying power"; IBKR 201 margin reject | Account for open orders reserving buying power; reduce qty |
| Tick size violation | IBKR 110 "price does not conform to the minimum price variation"; Binance -1013 PRICE_FILTER | Round to the instrument tick before sending |
| Invalid quantity or lot size | Binance -1013 LOT_SIZE | Round down to the step size |
| Min notional (crypto) | Binance -1013 NOTIONAL | Check price x qty against the minimum |
| Stop on the wrong side | "Order would immediately trigger" | Re-read the last price right before sending, and validate direction locally |
| Price outside collar | Rejection citing price band or limit up/down | Keep the price within the band around the last trade |
| Market closed with unsupported TIF | Alpaca 422; IBKR 201 | Use DAY with a limit and the extended-hours flag where supported |
| Market order in extended hours | Rejected or queued to the open | Use a limit order |
| Short not permitted | Alpaca "cannot be sold short" style message | Check the position and shortable flag first |
| Duplicate id | Alpaca 422 client_order_id not unique; IBKR 103 duplicate order id | Generate unique ids and make retries idempotent |
How do I simulate stop-limit orders in a backtest?
OHLC bars hide the order of events inside the bar, so every rule is an assumption. Make the assumptions explicit and conservative.
Market fills at the next bar open plus slippage. A limit fills at the open if the open is already better than the limit, otherwise at the limit, and only if price trades through it (low < limit for a buy) in conservative mode. A stop that gaps past its trigger fills at the open, not the stop price. Otherwise it fills at the stop plus slippage.
A stop-limit has two stages. If the bar gaps past the stop, trigger at the open and apply limit logic at once. If the stop is crossed intrabar and limit >= stop (buy), the sketch below assumes a fill at the limit, the worst allowed price. If limit < stop, the order triggers but cannot fill until a later bar, because you cannot tell whether price dipped to the limit before or after the trigger.
The function below handles sells by flipping signs so there is one code path. It mutates order["triggered"], and it ignores partial fills and queue position.
def _lim(op, lo, lim, cons):
# buy-side limit in sign-normalised space
if op <= lim:
return op # open is better than limit
if (lo < lim) if cons else (lo <= lim):
return lim # traded through the limit
return None
def fill(order, bar, slip=0.0, cons=True):
"""Return fill price or None for one bar. order keys: side, type,
limit_price, stop_price, triggered. Sells are mirrored via s=-1."""
s = 1 if order["side"] == "buy" else -1
op = s * bar["open"]
hi = bar["high"] if s == 1 else -bar["low"]
lo = bar["low"] if s == 1 else -bar["high"]
lim = None if order.get("limit_price") is None else s * order["limit_price"]
stp = None if order.get("stop_price") is None else s * order["stop_price"]
t = order["type"]
px = None
if t == "market":
px = op + slip
elif t == "limit":
px = _lim(op, lo, lim, cons)
elif t == "stop":
if op >= stp:
px = op + slip # gap: fill at open, not stop
elif hi >= stp:
px = stp + slip
elif t == "stop_limit":
if order.get("triggered"):
px = _lim(op, lo, lim, cons)
elif op >= stp: # gapped through the trigger
order["triggered"] = True
px = _lim(op, lo, lim, cons)
elif hi >= stp: # triggered intrabar
order["triggered"] = True
if lim >= stp:
px = lim if cons else stp
# lim < stp: wait for a later bar
return None if px is None else s * px
# Quick checks
bar = {"open": 98, "high": 99, "low": 97, "close": 98}
assert fill({"side": "sell", "type": "stop", "stop_price": 100}, bar) == 98
assert fill({"side": "buy", "type": "limit", "limit_price": 97.5}, bar) == 97.5
assert fill({"side": "buy", "type": "limit", "limit_price": 99}, bar) == 98 Why do live fills differ from my simulator?
Simple simulators assume you are first in line and always fully filled. Live, a limit sitting at the touch has a queue ahead of it, and a trade-through (not a touch) is what reliably proves your order would have filled. Large orders partially fill, and a bar-based model cannot see it.
Stop handling also differs by venue. Some stops are exchange-native and wait on the book engine. Others are simulated by the broker, which watches the price and sends a market or limit order when the trigger is hit. IBKR, for example, can hold some stop types on its own servers depending on the order and exchange, which adds latency and a different trigger reference. Paper trading often fills at the quote instantly, with no queue and no impact, so paper results are optimistic.
When a backtest and a live account disagree, compare per order: trigger price, trigger time, first fill time, fill price and fill quantity. The gap almost always lands in one of three places: trigger reference (last versus mark), gap handling, or partial fills.
Common questions
What is the difference between a stop order and a stop-limit order?
A stop order becomes a market order when stop_price is touched, so it will almost always fill but at an uncertain price. A stop-limit becomes a limit order at limit_price, so the price is bounded but the order may never fill if the market moves past the limit.
Why does my IBKR stop order have no stop_price field?
IBKR reuses auxPrice for the stop trigger. For STP orders, set auxPrice. For STP LMT orders, set lmtPrice for the limit and auxPrice for the stop.
Can I use a market order outside regular hours?
Many brokers reject market orders in extended hours or hold them until the next open. Alpaca, for instance, requires a DAY limit order with the extended-hours flag. Check the order type against the session before sending.
What happens to a GTC order when the broker's expiry passes?
The order moves to an expired or canceled status without any action from you, and Alpaca applies a cap of about 90 days. Poll or stream order updates and re-submit with a new client_order_id if you still need it.
How should a backtest fill a limit order the price only touches?
The conservative choice is to require a trade-through, meaning the low is strictly below a buy limit. A bare touch may only have filled orders ahead of yours in the queue, so treating it as a fill overstates results.