This article outlines the process of building an AI-powered crypto trading bot, exploring various strategies and the challenges encountered along the way. The aim is to potentially automate trading decisions using Large Language Model (LLM) agents.
The Allure of Crypto Trading
Crypto trading offers several advantages for algorithmic approaches:
-
24/7 Markets: Unlike traditional stock markets, crypto markets are always open.
-
Exponential Growth Potential: Cryptocurrencies can experience significant price increases.
-
Coin Variety: A wide range of cryptocurrencies offer diverse trading opportunities.
Challenges in Crypto Algorithmic Trading
Several hurdles were encountered during the bot development:
-
Poor Documentation: Crypto trading API documentation can be lacking.
-
Coding Rustiness: Existing coding skills may require refreshing.
-
Crypto Knowledge Gap: A limited understanding of the crypto market can be a significant obstacle.
Phase 1: Building a Random Bot
What is a Random Bot?
A random bot serves as a template trading algorithm. It makes random trading decisions, providing a foundation for integrating AI later.
Key Components of a Random Bot
- Importing Dependencies: Essential libraries are imported.
- Trading Algorithm: The core logic for making trading decisions is implemented.
- Backtesting: The algorithm is tested on historical data to evaluate its performance.
Dependencies
The following dependencies are imported:
-
strategy wrapper
(from Lumiot): Provides the base for the trading algorithm. -
datetime
: Manages dates for trading logic. -
Colorama
: Formats terminal output for readability. -
random
: Generates random choices for trading decisions. -
asset and CCXT back testing class
: Used for crypto pair definitions and backtesting.
Trading Algorithm Implementation
A new class, MLTrader
, is created, inheriting from the Lumiot strategy wrapper. This class contains three main methods:
-
initialize
: Sets up initial parameters like cash at risk and the coin to trade. It also sets the market to 24/7 and defines a sleep time (1 day) to limit trading frequency. -
position sizing
: Determines how much of a specific crypto asset to buy or sell. It calculates the quantity based on cash at risk and the current crypto price. It retrieves cash usingself.getcash
and the last price usingget last price
. -
on trading iteration
: Incorporates the trading logic. It gets the cash, last price, and quantity from the position sizing method. Then, it makes a random choice (hold, buy, or sell) usingrandom.choice
. This random choice will be replaced with AI later.
Trade Anatomy
The following steps are part of a trade:
- The market opens, providing new crypto prices.
- Any existing orders in the opposite direction are closed. For example, if placing a buy order, any sell orders are closed.
- A new order is created, specifying the crypto pair, price, quantity, and any take-profit or stop-loss levels.
- The order is submitted, and confirmation is received. The trade is also logged.
Backtesting Setup
To set up backtesting, specify a start and end date, then configure the exchange (e.g., Kraken). The minimum time step is set to one day, meaning trades are executed daily. The backtest is then run using the run back test
method, passing in the CCXT backtesting object, start and end dates, benchmark asset, quote asset, and trading bot parameters.
Addressing Errors
Initial runs may encounter errors due to missing price data. Adding a condition to check for price data and setting quantity to zero when data is unavailable can resolve this.
Initial Results
The initial random bot yielded negative returns, highlighting the need for intelligent trading logic.
Phase 2: Using Serper for Sentiment Analysis
Goal
The objective is to leverage sentiment analysis to inform trading decisions. The process involves:
- Using a tool to retrieve news articles related to a specific coin on a particular date.
- Feeding the news to an LLM agent to determine the sentiment (positive or negative).
- Using the sentiment to decide whether to buy or sell.
Implementation
- Importing Dependencies: Additional libraries are imported.
- Setting up LLM: The LLM (Open Hermes) is configured.
- Getting Dates: A method (
get dates
) is created to retrieve the current date and the previous day. - Getting Web Details: A
get web deets
method (web search tool) is used to retrieve news articles related to the specified coin and dates. - Prompt Template: A prompt template is used to instruct the LLM to analyze the news and provide a sentiment score.
- Integrating Sentiment: The sentiment information is integrated into the trading loop, replacing the random choice logic.
- Trading Logic: If the news sentiment is positive and the probability is above 70%, a buy order is placed. If the sentiment is negative, a sell order is placed.
Addressing API Issues
An error occurred due to depleted Serper API credits, which was resolved by purchasing more credits.
Unexpected Behavior
The bot initially generated significant profits, but closer inspection revealed an issue with position sizing calculations, leading to a negative cash balance.
Fixing Position Sizing
The position sizing was modified to be based on portfolio value rather than cash. This change, however, resulted in significant losses.
Phase 3: Agent Recommendations
Direct Recommendation Strategy
Instead of calculating sentiment, the agent is asked to directly provide a buy, sell, or hold recommendation based on the news.
Prompt Template
A new prompt template is created to instruct the LLM to generate a trading signal. The agent now has control over trading decisions.
Results
This strategy also resulted in negative returns, prompting a change in approach.
Phase 4: Exploring Different Coins
Trading Solana
The bot was switched to trading Solana to see if a different coin would yield better results. The necessary parameters were updated. The results remained negative.
Phase 5: Finnbert ML Strategy
Reintroducing an Old Strategy
The Finnbert ML strategy, previously used in a previous AI trading bot video, was reintroduced.
Alpaca Integration
The Alpaca Trade API was integrated to retrieve news data. The code for estimating sentiment from news articles was copied over.
Code Modifications
-
The
get dates
method was updated to retrieve three days of news data. -
The sentiment code was integrated into the trading loop.
-
The trading logic was adjusted to use the sentiment returned by Finnbert.
Long-Only Strategy
A long-only strategy was implemented, removing all shorting logic. Takeprofit and stop-loss orders were introduced.
Contrarian Strategy
The strategy was then flipped to be contrarian: buying when sentiment is negative and prices are low.
Final Results
The contrarian strategy, combined with a slightly more aggressive approach (lower probability threshold and higher cash at risk), yielded positive returns.