buy
Buys the specified quantity of the specified asset. By default, it places a limit order 5% above the current market price. This is a general function that can be used to buy any asset, including stocks, options, and cryptocurrencies.
Syntax
Fields
Description
symbol(str)
Symbol of the asset to buy.
quantity(float)
Quantity of asset to buy. If not specified, it will buy as many as possible given the current buying power.
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 buy(
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 buy order active until the current trading day ends.
“gtc” will keep the buy order active until it is filled or manually canceled.
A buy order with the provided parameters will only be processed if the broker supports it. For example, trying to buy 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 buy order for any reason. - If the broker does not support the type of the assert being bought, 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)