sell
Sells the specified quantity of an asset. By default, it places a limit order 5% below the current price. This is a general function that can be used to sell any asset, including stocks, options, and cryptocurrencies.
Syntax
Fields
Description
symbol(str)
Symbol of the asset to sell.
quantity(float)
Quantity of asset to sell. If not specified, sells all quantity of the asset owned.
in_force(str)
Duration the order is in force. Choose from "gtc" (Good 'til canceled) or "gtd" (Good 'til date). Defaults to "gtc".
extended(bool)
Whether to trade in extended hours or not. Defaults to False
def sell(
self,
symbol: str = None,
quantity: int = None,
in_force: str = "gtc",
extended: bool = False,
):
The asset symbol should be formatted as follows:
- For stocks, use the stock symbol (e.g.
AAPL
). - For cryptocurrencies, use the symbol prepended with an ”@” (e.g.
@BTC
). - For options, use the OCC symbol (e.g.
AAPL_062522C135
). For details on this format, see the Wikipedia page on Option Symbols. You can also use thedata_to_occ helper
function to generate OCC symbols. If a symbol is not provided, the first symbol inself.watchlist
will be used.
in_force
can be set to either “gtc” (Good ‘til canceled) or “gtd” (Good ‘til date).
“gtd” will keep the sell order active until the current trading day ends.
“gtc” will keep the sell order active until it is filled or manually canceled.
A sell order with the provided parameters will only be processed if the broker supports it. For example, trying to sell an option on Alpaca will result in an error, as Alpaca does not support options trading.
Returns
Returns a pyhton dictionary with the following keys and values:
order_id
: str, ID of order. The ID is generated by whichever broker is being used.symbol
: str, symbol of asset bought.
Raises
- An
Exception
is raised if the broker fails to process the sell order for any reason. - If the broker does not support the type of the assert being sold, an
NotImplementedError
is raised.
Example
class Crossover(Algorithm):
def config(self):
self.watchlist = ["SPY"]
self.interval = "5MIN"
self.aggregations = []
def main(self):
sma_short = self.sma(period=20)
sma_long = self.sma(period=50)
if self.crossover(sma_long, sma_short):
self.buy(quantity=1)
elif self.crossover(sma_short, sma_long):
self.sell(quantity=1)