img

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

img
valuezone 22 September 2022

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


Photo by Joakim Honkasalo

In this tutorial I would like to show you how to implement a crypto trading bot for the Alpaca Exchange with only 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, in 10 lines of code you 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 CryptoHistoricalDataClient
from alpaca.data.requests import CryptoLatestQuoteRequest
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:

  • Instantiate a client to get historical crypto data
  • Instantiate a client for trading
  • Start a while loop that keeps on running and every minute:
  • Retrieves the latest price for Bitcoin
  • In case the latest price is below the low threshold, execute a buy order
  • In case the latest price is above the high threshold, execute a sell order.

Note that you would have to adjust the low and high price thresholds and the quantity if you wanted to use it.

symbol = 'BTC/USD'data_client = CryptoHistoricalDataClient()
trading_client = TradingClient('<Your API key>', '<Your API secret>', paper=True)
while True:
latest_quote = data_client.get_crypto_latest_quote(CryptoLatestQuoteRequest(symbol_or_symbols=symbol))[symbol].ask_price
if latest_quote < 18520.0:
buy_order = trading_client.submit_order(order_data=MarketOrderRequest(symbol=symbol,qty=0.0001,side=OrderSide.BUY, time_in_force=TimeInForce.GTC))
elif latest_quote > 18540:
sell_order = trading_client.submit_order(order_data=MarketOrderRequest(symbol=symbol,qty=0.0001,side=OrderSide.SELL, time_in_force=TimeInForce.GTC))
time.sleep(60)

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

Wrapping Up

In this tutorial we discussed what the Alpaca Exchange is, what the advantages are of using it and how to implement a trading bot for Alpaca in 10 lines of Python code.