Howwise RSS
Trading Software7 min read

Alpaca Bracket Order in Python: alpaca-py Code and Rules

Short answer

An alpaca bracket order python request is one alpaca-py call with order_class=OrderClass.BRACKET, a whole-share qty, TIF day or gtc, plus take_profit and stop_loss. Alpaca holds the exit legs until the entry fills, then links them as OCO.

Key takeaways
  • Send a bracket as one request with order_class=BRACKET, take_profit.limit_price and stop_loss.stop_price; only whole-share qty and TIF day or gtc are accepted.
  • Use GTC for the bracket: a day bracket expires at the close and leaves any filled position without exit orders.
  • Legs start held, become active after the parent fills, and the sibling is auto-canceled when one leg fills.
  • Most 422 rejections come from prices on the wrong side of the base price, under a one cent offset, or with too many decimals, so validate client-side.
  • Follow fills with the trade_updates stream instead of sleeping, and re-read leg state after any manual cancel.

How do I submit a bracket order with alpaca-py?

A bracket order is a parent entry plus two child exit orders: a take-profit limit and a stop-loss. The request is built from MarketOrderRequest or LimitOrderRequest with order_class=OrderClass.BRACKET, and a TakeProfitRequest and StopLossRequest attached.

The prices below are placeholders to show the structure, not suggested levels.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import (
    MarketOrderRequest, LimitOrderRequest,
    TakeProfitRequest, StopLossRequest,
)
from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass

client = TradingClient(API_KEY, SECRET_KEY, paper=True)

# Market entry
mkt = MarketOrderRequest(
    symbol='AAPL', qty=10, side=OrderSide.BUY,
    time_in_force=TimeInForce.GTC,
    order_class=OrderClass.BRACKET,
    take_profit=TakeProfitRequest(limit_price=210.00),
    stop_loss=StopLossRequest(stop_price=190.00),
)

# Limit entry, stop-limit protective leg
lmt = LimitOrderRequest(
    symbol='AAPL', qty=10, side=OrderSide.BUY,
    limit_price=200.00,
    time_in_force=TimeInForce.GTC,
    order_class=OrderClass.BRACKET,
    take_profit=TakeProfitRequest(limit_price=210.00),
    stop_loss=StopLossRequest(stop_price=190.00, limit_price=189.50),
)

order = client.submit_order(lmt)
print(order.id, order.status, [(l.id, l.order_type, l.status) for l in order.legs])
Warning: Run this with paper=True first. A live key with the same code sends real orders.

What does the same bracket look like as raw REST or legacy alpaca-trade-api?

The SDK only serializes the request to POST /v2/orders. Readers on old code can map the fields one to one: the nested objects are take_profit and stop_loss, and order_class is the string bracket.

The legacy alpaca-trade-api package takes the same nested dicts in submit_order.

POST /v2/orders
{
  "symbol": "AAPL",
  "qty": "10",
  "side": "buy",
  "type": "limit",
  "limit_price": "200.00",
  "time_in_force": "gtc",
  "order_class": "bracket",
  "take_profit": { "limit_price": "210.00" },
  "stop_loss": { "stop_price": "190.00", "limit_price": "189.50" }
}

# legacy alpaca-trade-api (REST object)
api.submit_order(
    symbol='AAPL', qty=10, side='buy', type='limit', limit_price=200.00,
    time_in_force='gtc', order_class='bracket',
    take_profit=dict(limit_price=210.00),
    stop_loss=dict(stop_price=190.00, limit_price=189.50))

How are bracket legs linked, triggered and cancelled?

The parent is the entry order. The two children are the take-profit limit and the stop leg, returned in order.legs and referencing the parent through parent_order_id. The legs are inactive until the parent fills; the stop leg usually shows as held and the take-profit leg as new once the position exists.

The legs are OCO partners. When one fills, Alpaca cancels the other. If a leg partially fills, the sibling quantity is reduced so the two together never exceed the position.

If the parent partially fills, legs size to the filled quantity as the parent fills, so protection tracks what you actually own. Cancelling the parent before it fills cancels both legs. Cancelling the parent after a partial fill stops the remainder, while the legs stay for the filled part.

The state flow below is what to code against.

StageParentTake-profit legStop leg
Submittedaccepted or pending_newheldheld
Parent working (limit not hit)newheldheld
Parent partially filledpartially_filledactive for filled qtyactive for filled qty
Parent filledfillednewheld or new
Take-profit fillsfilledfilledcanceled
Stop triggers and fillsfilledcanceledfilled
Day TIF, market closeexpired (if unfilled)expiredexpired
Tip: Treat leg status strings as data, not a contract. Branch on filled, canceled and expired, and log everything else.

Which order classes and time-in-force values are valid?

Pick the class by what already exists. Bracket opens a position and protects it in one request. OCO is exit only for an existing position: two orders, one cancels the other. OTO sends an entry plus a single leg, either a take-profit or a stop-loss.

Brackets have strict time-in-force rules. Only day and gtc are accepted for the entry, and the legs inherit it. IOC, FOK, OPG and CLS are rejected.

order_classUse whenLegsNotes
simplePlain single orderNoneDefault
bracketNew entry with both exitsTake-profit and stopEntry TIF day or gtc
ocoPosition already held, want two exitsTake-profit and stop, no entryPass the exit side; sibling auto-cancels
otoEntry with only one exitOne take-profit or stopOther exit managed separately
Warning: A day bracket expires at the close. If the entry filled, the exit legs expire with it and the position is unprotected overnight. Use GTC when the exits must persist.

Why is my alpaca bracket order rejected with a 422?

Rejections are validated against a base price: the entry limit for limit entries, or the last quote or trade for market entries. For a buy, the take-profit must be above base and the stop below; for a sell short, reverse both. Alpaca also needs roughly one cent of separation, and the error text looks like take_profit.limit_price must be > base_price + 0.01.

Prices need at most 2 decimals at or above $1 and 4 below $1. Extended-hours flags are not supported on bracket legs, and notional or fractional quantities are refused because legs need whole shares.

Because a market entry's base price moves, a target close to the market can pass validation locally and fail on the server. Leave margin or use a limit entry.

Symptom or messageCauseFix
take_profit.limit_price must be > base_price + 0.01Target at or below base on a buyRaise target or lower the entry
stop_loss.stop_price must be below the base price (sell side reversed)Stop on the wrong side or within a centMove stop at least $0.01 away
invalid limit_price precisionToo many decimalsround(price, 2), or 4 under $1
insufficient buying powerParent plus margin requirement exceeds buying powerReduce qty or check account.buying_power
asset is not shortable / not tradableShort entry on a hard-to-borrow or inactive assetCheck get_asset(symbol).shortable and .tradable
potential wash trade detectedOpposite-side open order on the same symbolCancel conflicting orders first
insufficient qty available / held_for_ordersOpen legs reserve the shares you try to sellCancel the legs, then sell
time_in_force not supportedIOC, FOK, OPG or CLS usedUse day or gtc

What is a safe bracket helper with client-side validation?

The helper below rejects bad input before a network call and converts APIError into a readable result. It uses Decimal so rounding artifacts never create a 422 on decimal places.

PDT rules apply to margin accounts under the pattern day trader threshold. That rejection arrives from the server, so the helper just surfaces it.

from decimal import Decimal, ROUND_HALF_UP
from alpaca.common.exceptions import APIError
from alpaca.trading.requests import (
    LimitOrderRequest, MarketOrderRequest,
    TakeProfitRequest, StopLossRequest)
from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass

CENT = Decimal('0.01')

def _px(x):
    d = Decimal(str(x))
    places = Decimal('0.01') if d >= 1 else Decimal('0.0001')
    return d.quantize(places, rounding=ROUND_HALF_UP)

def submit_bracket(client, symbol, qty, side, take_profit, stop,
                   base_price, entry_limit=None, stop_limit=None,
                   tif=TimeInForce.GTC):
    if tif not in (TimeInForce.DAY, TimeInForce.GTC):
        raise ValueError('bracket TIF must be day or gtc')
    if int(qty) != qty or qty <= 0:
        raise ValueError('qty must be a whole number of shares')
    tp, sl, base = _px(take_profit), _px(stop), _px(entry_limit or base_price)
    if side == OrderSide.BUY:
        ok = tp >= base + CENT and sl <= base - CENT
    else:
        ok = tp <= base - CENT and sl >= base + CENT
    if not ok:
        raise ValueError(f'levels invalid for {side}: tp={tp} sl={sl} base={base}')
    common = dict(symbol=symbol, qty=int(qty), side=side, time_in_force=tif,
                  order_class=OrderClass.BRACKET,
                  take_profit=TakeProfitRequest(limit_price=float(tp)),
                  stop_loss=StopLossRequest(
                      stop_price=float(sl),
                      limit_price=float(_px(stop_limit)) if stop_limit else None))
    req = (LimitOrderRequest(limit_price=float(base), **common)
           if entry_limit else MarketOrderRequest(**common))
    try:
        return client.submit_order(req)
    except APIError as e:
        print('rejected', e.status_code, e.message)
        raise

How do I read leg status, modify legs and follow fills?

Fetch one order with client.get_order_by_id(id) and read order.legs, or list with GetOrdersRequest(nested=True) so children appear under their parent. Without nested, legs show up as separate rows and are easy to double count. After an exit, read filled_avg_price and filled_at on the filled leg, and check the other leg for canceled.

To change a level, call client.replace_order_by_id(leg_id, ReplaceOrderRequest(stop_price=...)) or limit_price for the take-profit leg. You cannot change the parent's order class, and leg quantity is not replaceable independently. Replacing creates a new order id, so store the new id and follow replaced_by.

If you cancel one leg manually, do not assume the sibling was cancelled too. Re-read the order and the open orders for the symbol, then cancel or recreate as needed.

Polling works but is slow and counts against rate limits (about 200 requests per minute on standard accounts). The trade_updates websocket delivers events as they happen, and reconnect logic is handled by the SDK stream, though you should reconcile with a REST read after any reconnect.

from alpaca.trading.stream import TradingStream
from alpaca.trading.requests import GetOrdersRequest
from alpaca.trading.enums import QueryOrderStatus

stream = TradingStream(API_KEY, SECRET_KEY, paper=True)

async def on_update(data):
    o = data.order
    print(data.event, o.symbol, o.order_type, o.status,
          'parent:', o.parent_order_id, 'avg:', o.filled_avg_price)
    # events: new, fill, partial_fill, canceled, expired, replaced, rejected

stream.subscribe_trade_updates(on_update)
stream.run()

# Reconcile on startup or reconnect
open_orders = client.get_orders(GetOrdersRequest(
    status=QueryOrderStatus.OPEN, nested=True))

What can bracket legs not protect against, and what is unsupported?

A stop leg becomes a market order when triggered, so the fill can be worse than the stop price in a gap or fast market. A stop-limit leg avoids that slippage but may not fill at all if price moves through the limit, leaving the position open. Neither is guaranteed protection, so design the bot to detect an unfilled stop and escalate.

Bracket class is for equities only. Crypto does not accept bracket orders, and options use different handling, such as multi-leg orders, so verify against current Alpaca documentation before building on it.

Test on paper first. Paper fills are simulated, so slippage and partial fill behavior will be more optimistic than live.

Common questions

How do I place an OCO order in alpaca-py?

Use order_class=OrderClass.OCO with a LimitOrderRequest for an existing position, passing take_profit and stop_loss. It has no entry leg, so it only makes sense when you already hold the shares. When one side fills, the other is cancelled.

Can I use extended hours with a bracket order?

No. Bracket orders do not support extended_hours, so the legs only work in regular sessions. If you need extended-hours exits, manage them with separate orders and your own monitoring.

Why can't I sell shares that have an open bracket?

The open exit legs reserve the shares, so the account shows them as held_for_orders and a manual sell is refused for insufficient qty available. Cancel the legs first, verify the cancels, then submit your sell.

Do bracket orders work with fractional or notional quantities?

No. Brackets require a whole-share qty, and notional or fractional values are rejected. Round your sizing down to an integer before building the request.

Can I use a bracket order for short selling?

Yes, on shortable assets: set side to SELL and reverse the price logic, with take-profit below the base and stop above it. The asset must be shortable and easy to borrow, or the entry will be rejected.

Related topics:alpacaalpaca-pybracket orderpythontrading api