Building an End-to-End Trading Bot using Alpaca’s API, CircleCI, and Slack

June Rodriguez
6 min readMar 30, 2023

A comprehensive guide on building a trading bot, along with a ready to deploy GitHub repo 🤖

Written by: June Rodriguez

Get ready to make (or lose) a fortune! 😂

I n this article I’ll explore the inner workings of a trading bot that uses the Alpaca API, CircleCI, and Slack for trade notifications. In summary, the bot scans for trading opportunities based on the top losing stocks and popular crypto assets from YahooFinance! It then utilizes the Alpaca API to execute buy & sell orders and sends notifications via Slack about the trades it has made. Here’s an example of a notification the bot sends me via Slack showing the trades it made in my paper trading Alpaca account:

Again, this is my paper trading account — I wouldn’t trust this much money to my algo (yet) 💰

Here’s the GitHub repo if you’d like to skip to the ReadMe and clone the project to make your own modifications.

Let’s dive deep into the logic of the scripts used in the project!

Assumed prerequisite understanding of the reader:

Firstly, what is Alpaca?

Alpaca trading is a commission-free API-first stock brokerage that offers users the ability to buy and sell stocks, exchange-traded funds (ETFs), and cryptocurrency through a single platform. The Alpaca platform provides users with access to real-time market data, account management, and trading functionalities through their REST API, which enables developers to build and integrate their own trading applications.

Additionally, Alpaca offers users the ability to automate their trading strategies through a Paper Trading account, which allows users to simulate trades without risking real money. If you’re looking to create very custom trading algorithms using your Python scripts, this is a solid option to go with!

Overview of the Project Structure

The project consists of several Python files, a config.yml file for CircleCI, and a creds.cfg configuration file containing Alpaca and Slack API keys. The main Python files are:

  1. trading_classes.py | Contains the TradingOpportunities and Alpaca classes, which handle the logic for identifying trading opportunities and executing trades using the Alpaca API, respectively.
  2. slack_app_notification.py | Contains the slack_app_notification function, which generates a formatted string with a summary of the trades made by the bot and sends it as a Slack notification to your desired channel.
  3. main.py | The entry point of the application, which brings together the functionality of the TradingOpportunities, Alpaca, and slack_app_notification classes and functions.

The TradingOpportunities Class

The TradingOpportunities class is responsible for scraping YahooFinance! to identify trading opportunities based on the top losing stocks and popular crypto assets. It does this using the get_trading_opportunities and get_asset_info methods.

get_trading_opportunities() Method

This method scrapes YahooFinance! using the yfinance package to obtain the top losing stocks of the day and most popular crypto assets. It first gets the top losing stocks by percentage change for the day using get_day_losers. Then, it obtains the top traded crypto assets by market cap using get_top_crypto.

get_asset_info() Method

This method filters the list of assets obtained from get_trading_opportunities by checking each asset's technical indicators and picking just the oversold assets as buying opportunities. I’ve used Bollinger Bands and RSI for this public repo, so feel free to make tweaks to this part of the code. Lines 22–49 do all the magic here:

The Alpaca Class

The Alpaca class is responsible for executing buy and sell orders using the Alpaca API. It contains the sell_orders and buy_orders methods to handle these actions.

sell_orders() Method

This method iterates through the assets in the user’s Alpaca account and checks if they meet the selling criteria based on technical indicators that signal they’re overbought. If they do, it generates a sell order for the asset. This is probably the most complex part of the project since we need to free up cash if no existing positions are overbought (and subsequently sold) so the algorithm can continue with buying oversold assets. I’ve incorporated logic that checks if cash is < 10% of the total portfolio and if so, sells an equal amount of the top 25% of performing assets in the portfolio to fill that gap. Line 61 of the snippet below is where this logic is captured.

buy_orders() Method

This method takes a list of tickers that meet the buying criteria based on YahooFinance! stocks and crypto assets and creates buy orders for each of them using the Alpaca API. It calculates the amount to buy based on the user’s available buying power and the current price of the asset.

slack_app_notification() Function

The slack_app_notification function generates a formatted summary of the bot's trades and sends it as a Slack notification. It first retrieves the trade history from the Alpaca API using the get_activities method, then it parses the trade information and formats it into a human-readable message. Finally, it sends the message to a specified Slack channel using the Slack API. You can make tweaks in the main() function (covered next) for when you’d like the bot to send notifications in the channel you’ve enabled your Slack app in.

main.py — Bringing It All Together

main.py is the entry point of the application and brings together the functionality of the TradingOpportunities, Alpaca, and slack_app_notification classes and functions. It gathers all user configuration details stored in the creds.cfg file to authenticate all the API connections.

Pushing it to production via CircleCI

CircleCI is a continuous integration and delivery platform that automates the build, test, and deployment of applications. It allows developers to focus on writing code and ensures that the code they write is properly tested and deployed to production. I’ve very easily deployed this bot through the platform with its quick connectivity to GitHub.

CircleCI gives a bunch of free credits monthly, so you can use their servers to run this algorithm many times over. It’s currently set to run 6 times daily in the repo (see the config.yml file) for example, but I think the free credits are enough to run it tens of times daily.

Closing remarks

Give the repo a try and I’m curious to read your thoughts on what changes you’d make to the trading logic or the pipelines.

Please note that the trading bot shared in this article and associated GitHub repository is for educational and informational purposes only. I am not a financial advisor and I do not make any representations or warranties as to the accuracy, completeness, or timeliness of any of the information provided. The use of this bot and any trading strategies discussed or shared is at your own risk. I am not responsible for any financial outcomes resulting from the use of this bot, and any investment decisions you make are solely your own. Before using this bot or making any investment decisions, please consult with a licensed financial advisor.

--

--