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:

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:

Raises

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)