AI-Powered Crypto Trading Bot: A Deep Dive
Key Concepts: Algorithmic trading, LLM agents, Sentiment analysis, Contrarian trading, Backtesting, Position sizing, Risk management, Crypto trading strategies.
1. Phase One: Building a Rando Bot (Template Trading Algorithm)
- Goal: Create a basic trading algorithm that makes random trading decisions as a foundation for AI integration.
- Key Components:
- Dependencies:
strategy wrapper(fromLumiot.strategies.strategy): Forms the basis for the trading algorithm.datetime: Manages dates.Colorama: Terminal formatting.random: Generates random choices.assetandCCXT back testing class: Used for crypto pair definition and backtesting.
- Trading Algorithm (ML Trader Class):
initializemethod:- Sets up the trading environment.
- Takes
cash at risk(amount of money to risk) andcoinas input. - Sets
marketto 24/7,sleep timeto 1 day (trades once a day), and initializeslast trade.
position sizingmethod:- Implements a cash management framework.
- Calculates the number of stocks to purchase per trade based on available cash and risk tolerance.
- Uses
self.getcash(from Lumiot) to get current cash andget last priceto get the last crypto price. - Calculates quantity:
(cash * cash at risk) / last crypto price.
on tradingmethod:- Incorporates the trading logic.
- Gets
cash,last price, andquantityusing theposition sizingmethod. - Uses
random.choice([0, 1, 2])to make a random choice (0: hold, 1: buy, 2: sell). - Places trades based on the random choice.
- Trade Anatomy:
- Market provides new crypto prices (new data).
- Close out any old orders in the opposite direction (e.g., close sell orders before placing a buy order).
- Create the order: specify crypto pair, price, quantity, and any take-profit or stop-loss levels.
- Submit the order to the broker and receive confirmation.
- Log the trade.
- Uses
sell allmethod to close existing sell orders. - Uses
create ordermethod to place new orders, specifying theasset,quantity,buy/sell,type(market trade), andquote type(USD).
- Backtesting:
- Specifies a
start dateandend date. - Configures the exchange (e.g., Kraken) and sets the minimum time step (e.g., 1 day).
- Uses
run back testmethod, passing theCCXT back testingobject,start/end dates,benchmark asset,quote asset, and trading bot parameters.
- Specifies a
- Dependencies:
- Example: The bot initially made random choices to buy, sell, or hold Bitcoin.
- Result: The initial "rando bot" resulted in a negative annual return of -8.98%.
2. Part Two: Using Serper for Sentiment Analysis
- Goal: Integrate sentiment analysis into the trading bot using news data to make more informed trading decisions.
- Process:
- Get News Data:
- Import necessary libraries:
time delta,Olama LLM,JSON,get web deets utility, andprompt template. - Set up the LLM (e.g., Open Hermes).
- Use
get datetimeandtime deltato get the current date and the previous day. - Use
get web deets(a web search tool) to retrieve news articles for a specific coin (e.g., Bitcoin) and date range.
- Import necessary libraries:
- Sentiment Analysis:
- Pass the news data to a prompt template and send it to the LLM.
- The prompt instructs the LLM to analyze the news and determine if the sentiment is positive or negative, along with a score between 0 and 1.
- The LLM returns a JSON object with the sentiment and score.
- Trading Logic:
- Extract the sentiment and probability from the JSON object.
- If the sentiment is positive and the probability is over 70%, buy the coin.
- If the sentiment is negative, sell the coin.
- Get News Data:
- Technical Terms:
Olama LLM: Used for LLM capability and building the agent.get web deets: Utility for getting information from the web using LLM agents.prompt template: Defines the structure and instructions for the LLM.
- Example: The bot used news articles about Bitcoin to determine whether the sentiment was positive or negative and then made trading decisions accordingly.
- Issue: The bot started shorting a ton, which increased the amount of cash available. When a positive buy signal came in, it used that cash balance to calculate the trade size, which made it massive. After closing out all of the shorts and placing that massive trade, the bot ended up with a negative cash balance.
- Fix: Base the position sizing on the portfolio value instead of cash.
- Result: After the fix, the bot resulted in a -65.36% return.
3. Stage Three: Agent Recommendations
- Goal: Allow the LLM agent to directly provide trading recommendations (buy, sell, or hold) based on news data.
- Process:
- Use a new prompt template that instructs the LLM to generate a trading signal (buy, sell, or hold) and a confidence score.
- The agent now has control over the trading decision.
- Result: The bot resulted in a -450% return.
4. Trying a Different Coin (Solana)
- Goal: Test the agent recommendation strategy with a different cryptocurrency (Solana).
- Process:
- Update the coin parameter to Solana.
- Pass Solana to the
get web deetsmethod to get news about Solana. - Update the benchmark asset and trading asset in the backtest parameters.
- Result: The bot resulted in a -80.36% return.
5. Finnbert ML Strategy
- Goal: Revert to a previously successful AI trading strategy (Finnbert ML) used in a previous video.
- Process:
- Import the
alpaca trade APIand theestimate sentimentfunction. - Set up Alpaca API details (API key, API secret, base URL).
- Update the
get datesmethod to bring back 3 days' worth of news data. - Send news requests to the Alpaca News API.
- Pass each headline to the
estimate sentimentfunction to get probability and sentiment. - Reverse the trading logic to go from the direct recommendation back to sentiment.
- Bump up the probability to 0.999 to ensure a really strong signal.
- Change the coin to Ripple (XRP) for a more stable trading environment.
- Import the
- Technical Terms:
alpaca trade API: Used for accessing news data.estimate sentiment: Function for estimating the sentiment of news articles.
- Result: The bot was still not profitable.
6. Long Only Strategy
- Goal: Implement a long-only trading strategy, eliminating shorting.
- Process:
- Remove all shorting logic from the code.
- Implement take-profit (1.5% of purchase price) and stop-loss (70%) levels.
- Set the position sizing back to
get cash.
- Result: The bot resulted in a -6.5% return.
7. Going Contrarian
- Goal: Implement a contrarian trading strategy, buying when sentiment is negative and selling when sentiment is positive.
- Process:
- Change the trading logic to buy when sentiment is negative.
- Result: The bot produced a return of 8.85% and a total return of 14%.
- Optimization:
- Drop a 9 off the signal for the probability (making it less conservative).
- Put more cash at risk (50% of the portfolio).
- Result: The bot produced a 20.04% return and a total return of 32%.
Synthesis/Conclusion
The video documents the process of building an AI-powered crypto trading bot, highlighting the challenges and iterations involved. The journey starts with a simple random bot and progresses through various strategies, including sentiment analysis, agent recommendations, and contrarian trading. The final contrarian strategy, combined with optimized risk management, shows promising results, demonstrating the potential of AI in algorithmic crypto trading. The key takeaway is that a contrarian approach, buying when negative sentiment prevails, can be a viable strategy in the crypto market.
AI summaries can miss context or contain errors. Check important details against the original video.





