The Sell Flow
When SignalPipe receives a sell signal, it closes the entire position for the specified ticker.
Sell Execution Steps
- Read current price -- Before closing, SignalPipe reads the current market price from the Alpaca position. This must happen first because the position data is no longer available after the close.
- Close position on Alpaca -- Sends a close request to Alpaca, which sells all shares at market price. If the position was already closed (for example, by a TP fill), the error is logged but processing continues.
- Cancel all open orders -- Any pending orders for the symbol are cancelled, including the take-profit limit sell and any unfilled limit buys.
- Calculate realized P&L -- Profit or loss is calculated as:
(close_price * total_shares) - total_invested. - Mark deal as completed -- The deal status is updated to "completed" with the close timestamp and realized P&L.
- Log the closure -- A detailed log entry records the exit price, P&L, number of orders in the deal, and ladder depth.
Example: Sell Flow
- Active deal: AAPL, 25 shares, avg entry $144.00, total invested $3,600
- Current price at sell: $148.00
- Position closed: 25 shares sold at ~$148.00
- Realized P&L: (25 * $148.00) - $3,600 = $3,700 - $3,600 = +$100.00
- TP order cancelled
- Deal marked completed
Edge Cases
No Active Deal Found
If a sell signal arrives but there is no active deal in the database for that ticker, SignalPipe still attempts to close the position on Alpaca (in case a position exists outside the deal tracking system). A warning is logged noting that no matching deal was found. This can happen if:
- The deal was already completed by a take-profit fill
- The deal was closed manually on Alpaca
- The position was opened outside of SignalPipe
Position Already Closed
If the Alpaca position was already closed (for example, by a TP limit sell that filled), the close request may return an error. SignalPipe handles this gracefully -- it logs the situation and still proceeds to update the deal record in the database.