img

How to create an Alpaca Stock Trading Bot with only 10 Lines of Code (Python Tutorial)

img
valuezone 22 September 2022

How to create an Alpaca Stock Trading Bot with only 10 Lines of Code (Python Tutorial)

In this tutorial I would like to show you how to implement a stock trading bot for the Alpaca Exchange with 10 lines of Python code. I guess I could have done it in 9 lines of code but it would have been ugly. ;)

If you want to know how to pull off this little hat trick, read on below!

This story is solely for general information purposes, and should not be relied upon for trading recommendations or financial advice. Source code and information is provided for educational purposes only, and should not be relied upon to make an investment decision. Please review my full cautionary guidance before continuing.

What is Alpaca?

Alpaca is an exchange for stock- and crypto trading founded in 2015 and headquartered in Silicon Valley, US.

According to their website their vision is:

“To allow the 7 billion people on the planet to access financial markets. We are committed to providing a secure, reliable and compliant platform for anyone who wants to build their own trading strategies, asset management automation, trading and robo-advisor apps, new brokerage services, investment advisory services and investment products.”

The company currently provides commission-free trading for stocks and ETFs and trading for cryptocurrencies.

In the future, the company also plans to offer other instruments such as options, futures, FX, private equities, and international equities.

Trade Ideas provides AI stock suggestions, AI alerts, scanning, automated trading, real-time stock market data, charting, educational resources, and more. Get a 15% discount with promo code ‘BOTRADING15’.

Why use Alpaca?

A compelling reason for using Alpaca is that they offer commission-free trading for stock trading. Sweet!

Here are a couple of other reasons:

  • Convenient API access and ‘developer first’ mindset
  • Offers crypto trading of more than 52 currency pairs.
    (Not commission free)
  • ETF trading
  • Market Data access for stock prices, crypto prices and news
  • Margin- and short selling
  • Paper trading environment
  • Two-factor authentication.

How does the Bot work?

Well, with only 10 lines of code we can’t really implement some fancy trading strategy but you can still implement one that is potentially profitable.

In this tutorial we will use a Spot Grid strategy like it is used by some of the Kucoin bots. This strategy is used best in ranging markets when the price fluctuates between stable values — not the volatile craziness that is currently going on.

Here the strategy:

  • Buy when the price falls below a low threshold
  • Sell when the price rises above a high threshold.

Note that the thresholds are currently hardcoded and need to be adjusted to the current market price range.

Implementation

I do not recommend using this bot for live trading. Use for paper trading only.

There are two Alpaca Python SDK’s available: alpaca-trade-api, which is deprecated and alpaca-py, which is the new official Alpaca Python SDK. In this tutorial we will use alpaca-py.

You can install the Alpaca Python SDK using this statement:

pip install alpaca-py

Sign Up

In order to use some of the Alpaca APIs, you need to first sign up and get your API keys here.

Then create a python file and import the necessary Python packages:

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
import time

Below is the main bot implementation. Here the steps the bot executes:

  1. Instantiate a client to get historical stock data
  2. Instantiate a client for trading
  3. Start a while loop that keeps on running and every minute:
  4. Retrieves the latest price for the stock
  5. In case the latest price is below the low threshold, execute a buy order
  6. In case the latest price is above the high threshold, execute a sell order.

Note that you would have to adjust the symbol, low and high price thresholds and the quantity if you wanted to use it. Also note the flag for paper trading mode.

symbol = 'TSLA'data_client = StockHistoricalDataClient('<Your API Key>', '<Your API Secret>')
trading_client = TradingClient('<Your API Key>', '<Your API Secret>', paper=True)
while True:
request_params = StockLatestQuoteRequest(symbol_or_symbols=symbol)
latest_quote = data_client.get_stock_latest_quote(request_params)[symbol].ask_price
if latest_quote < 300.0:
buy_order = trading_client.submit_order(order_data=MarketOrderRequest(symbol=symbol, qty=1, side=OrderSide.BUY, time_in_force=TimeInForce.DAY))
elif latest_quote > 320.0:
sell_order = trading_client.close_position(symbol)
time.sleep(60)

And that’s it. Now you should be able to run the bot in paper trading mode.