I tried coding a LLM Crypto Trading Bot (to retire early $$$)

Nicholas RenotteAbout 6 min readMay 27, 2025Watch original
THE SUMMARYAI-generated

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 (from Lumiot.strategies.strategy): Forms the basis for the trading algorithm.
      • datetime: Manages dates.
      • Colorama: Terminal formatting.
      • random: Generates random choices.
      • asset and CCXT back testing class: Used for crypto pair definition and backtesting.
    • Trading Algorithm (ML Trader Class):
      • initialize method:
        • Sets up the trading environment.
        • Takes cash at risk (amount of money to risk) and coin as input.
        • Sets market to 24/7, sleep time to 1 day (trades once a day), and initializes last trade.
      • position sizing method:
        • 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 and get last price to get the last crypto price.
        • Calculates quantity: (cash * cash at risk) / last crypto price.
      • on trading method:
        • Incorporates the trading logic.
        • Gets cash, last price, and quantity using the position sizing method.
        • 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 all method to close existing sell orders.
        • Uses create order method to place new orders, specifying the asset, quantity, buy/sell, type (market trade), and quote type (USD).
    • Backtesting:
      • Specifies a start date and end date.
      • Configures the exchange (e.g., Kraken) and sets the minimum time step (e.g., 1 day).
      • Uses run back test method, passing the CCXT back testing object, start/end dates, benchmark asset, quote asset, and trading bot parameters.
  • 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:
    1. Get News Data:
      • Import necessary libraries: time delta, Olama LLM, JSON, get web deets utility, and prompt template.
      • Set up the LLM (e.g., Open Hermes).
      • Use get datetime and time delta to 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.
    2. 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.
    3. 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.
  • 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 deets method 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 API and the estimate sentiment function.
    • Set up Alpaca API details (API key, API secret, base URL).
    • Update the get dates method to bring back 3 days' worth of news data.
    • Send news requests to the Alpaca News API.
    • Pass each headline to the estimate sentiment function 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.
  • 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.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.