Unable to close positions

Hello,

During paper trading today I have been unable to close positions on my paper trading account for over 9 positions

The error I get when trying to trigger a sell in python is as follows:

However, when I look at the Alpaca paper trading dashboard I can see that I still have 100 shares of that particular stock:

I am using the following code:

Screen Shot 2021-06-22 at 12.58.59 PM

Is there specific python code I need to use to reverse a position?

Thank you

Iā€™ve also been struggling with this issue. Itā€™s stopping me from trusting the site enough to actually use it with real trades via the API.

The usual cause of the insufficient qty available error is there are existing open orders. When selling (from a long position) the Alpaca systems look at the currently held quantity, minus any outstanding sell orders, to determine the available to sell quantity. If there isnā€™t enough available quantity to sell then one will get this error.

In general, before closing a position, cancel any outstanding orders (both buy and sell).

Could that be/have been the issue?

Hell Dan, Thank you for responding!

There are sell orders open but those are the result of sending in a bracket order. Would I have to cancel all corresponding bracket orders relating to that particular stock before I can issue a sell order?

In my case, I get the error when attempting to cancel a stop loss sell and the launch a market sell. Iā€™m not sure what to wait for other than a successful cancel on the first order which Iā€™m already doing. It seems as though the shares from cancelled orders donā€™t become ā€œavailableā€ for another order for quite a while sometimes.

@Aky All outstanding sell orders are considered when checking if there are shares available. This includes bracket orders. The logic however is smart enough that the two legs of a bracket order arenā€™t counted twice. You would need to cancel those orders before closing a position.

@Joel_Neuendorf After requesting an order to be cancelled, one should wait for a confirmation. This can take tens of seconds during live trading. There isnā€™t a good way to ā€˜cancelā€™ a stop order other than cancelling it. However, one approach I use for limit orders is to simply replace the limit price so the order becomes marketable. This effectively cancels the limit order and then submits a market order in one step. No need to wait for a ā€˜cancelledā€™ update.

1 Like

@Dan_Whitnable_Alpaca Could you share how one would replace the limit price using the api?

The mobile app and api has an amazing feature to close all open orders as well as liquidate all positions IE api to cancel all orders using api.cancel_all_orders(). However, if you use this liquidate all positions and there are already limit sale orders in place you get an error saying that you donā€™t have available shares to liquidate.

Is there a good way to cancel only the open sale orders before liquidating? Reason being I have lots of buy orders I donā€™t want to cancel when trying to liquidate, I want to just cancel the current sell orders and then liquidate all the shares I have. Same argument for the buy orders, perhaps I want to keep my current limit orders to sell the shares I have but I want to cancel all my open buy orders so I dont buy any more.

Not sure if this is just a feature request to add a cancel all buy and cancel all sell orders fuction or if there is already a way to address this issue?

bumpā€¦ anyone? there has to be others with this concern.

Hi I am having a similar problem.

I am unable to close any positions via the API or the UI.

I currently have short position against TSLA and whether I try to close via the API, or on the UI via the ā€œLiquidate all posittionsā€ button, or simply buy back the number of shares I originally sold short. None of it works, the orders donā€™t fill.

I will have to change broker if I canā€™t fix it on my paper trading account.

Thanks
Josh

Hi @joshuaseetanah ,

Is this still the case? Could you send an email to support@alpaca.markets with your account information?
Or you could join our slack community.

Apparently closing your position on a ā€œShortā€ is handled the same as buying the stock, so:

    # Get a list of all of our positions.
    portfolio = api.get_all_positions()

    # Loop through the portfolio and close all positions
    for position in portfolio:
        symbol = position.symbol
        qty = position.qty
        print('symbol: ' + symbol)
        print('qty: ' + str(qty))

        # Convert qty from string to int
        qty = int(qty)

        side = ''
        if qty < 0:
            side = OrderSide.BUY
        else:
            side = OrderSide.SELL

        # Convert qty to a positive number
        qty = abs(qty)

        # Close postition
        market_order_data = MarketOrderRequest(
            symbol=symbol,
            qty=qty,
            side=side,
            time_in_force=TimeInForce.OPG
        )

@Luis_Felix Correct. Thanks!

i use market orders to close, just an idea

So, this looks like a bracket order.
Iā€™ve spent countless hours trying to find a way to stop the bracket order - and just finally managed to successfully cancel one.

Also - donā€™t be lazy and use help(TradingClient) - the second method is the one that helps.

Using alpaca-py==0.30.1 pypi package

Code:

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetOrdersRequest, ClosePositionRequest
from alpaca.trading.enums import QueryOrderStatus
import time

# NOTE: For security, use environment variables, don't just put it in your script
API_KEY = 'Your-api-key'
API_SECRET = 'Your-api-secret'

trading_client = TradingClient(API_KEY, API_SECRET, paper=True)
ticker = 'YETI'

position = trading_client.get_open_position(ticker)

req = GetOrdersRequest(
    status = QueryOrderStatus.ALL, # may need other order statuses
    symbols = [position.symbol]
)

orders = trading_client.get_orders(req) # Returns a list, each list member will be a dictionary
print (orders.symbol, orders.id)

order_id = orders.id

# Start order cancellation
cancel_order = trading_client.cancel_order_by_id(
    order_id = order_id
)

# add sleep time to ensure that cancellation is processed
time.sleep(1) # Can be reduced once you know the average response time

# Now you must close the position, because your position won't be liquidated when you cancel your bracket order
trading_client.close_position(
    symbol_or_asset_id = position.symbol,
    close_options = ClosePositionRequest(
        qty = position.qty
        #percentage = '100'
    )
)

Hope this helps others from spending a ton of time trying to find a solution.