Alpaca-py APIError: insufficient qty available for order,

Hi,

I’m using alpaca-py Python API. I’m trying to submit a market order, and try to protect it with a stop-loss and a limit-order as a profit-target. Since quantities are different (limit-order is only taking a fraction of the position), I can’t use the bracket market order.

Submitting the market order works:

req = MarketOrderRequest(
symbol = ‘AAPL’,
qty    = 10,
side   = OrderSide.BUY,
type   = OrderType.MARKET,
time_in_force = TimeInForce.DAY
)
order = self.trade_client.submit_order(req)

Submitting the stop-loss order works (waited until market order is filled):

req = StopOrderRequest(
symbol       = ‘AAPL’,
qty          = 10,
side         = OrderSide.SELL,
stop_price   = <any price below market price>,
time_in_force= TimeInForce.DAY
)
order = self.trade_client.submit_order(order_data=req)

Submitting a limit-oder fails with the following error:

req = LimitOrderRequest(
    symbol       = 'AAPL',
    qty          = 5,
    side         = OrderSide.SELL,
    limit_price   = <any price above current price>,
    time_in_force= TimeInForce.DAY
)
order = self.trade_client.submit_order(order_data=req)

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://paper-api.alpaca.markets/v2/orders
alpaca.common.exceptions.APIError: {"available":"0","code":40310000,"existing_qty":"10","held_for_orders":"10","message":"insufficient qty available for order (requested: 5, available: 0)","symbol":"AAPL"}

How can I submit a stop-loss and limit-oder, which seems pretty straight forward, but Alpaca is rejecting?

@TradeFab The clue is in the error message you are getting

{"available":"0","code":40310000,"existing_qty":"10","held_for_orders":"10","message":"insufficient qty available for order (requested: 5, available: 0)","symbol":"AAPL"}

That’s saying you requested to sell 5 shares of AAPL, there are 10 shares existing, but those 10 shares are being held for another sell order. You cannot have two orders selling the same shares.

As you noted, this is where bracket orders are used. To get around the issue of different quantities you can submit two bracket orders. Each order would be to buy and sell 5 (half your total desired). Set the first order limit at your desired price. Set the second order’s limit price higher if you don’t really want it to fill. Make sense?

Thanks Dan. Alpaca API is learning by doing, not everything is explained when reading the documentation. I can’t submit a standalone stop-loss and limit order for an existing position; instead I have to use one or multiple OCO orders, where overall quantity of all these orders never exceeds the position quantity.