How to Build a Free RSI and MACD Trading Bot with ChatGPT & Alpaca

·

Algorithmic trading is no longer exclusive to hedge funds and institutional investors. With the rise of AI tools like ChatGPT, accessible APIs such as Alpaca’s Trading API, and affordable cloud computing via AWS EC2, individual traders can now build, test, and deploy fully automated trading bots from their laptops.

This guide walks you through creating a free RSI and MACD-based trading bot using natural language prompts in ChatGPT, Python programming, and cloud automation—all without writing a single line of code from scratch. Whether you're a beginner exploring algorithmic trading or an experienced developer looking to streamline strategy creation, this step-by-step tutorial provides a practical foundation.


Understanding Algorithmic Trading Bots

An algorithmic trading bot is a software program that automatically executes buy and sell orders based on predefined rules. These rules are typically derived from technical indicators, price action, volume patterns, or timing triggers.

Unlike manual trading, bots operate 24/7, react instantly to market signals, and eliminate emotional decision-making—making them ideal for strategies relying on precision and consistency.

Key Benefits of Using Trading Bots

Risks to Consider

Always start with paper trading (simulated accounts) and conduct rigorous testing before going live.

👉 Generate your free API key and start paper trading today.


Core Tools You’ll Need

To build a functional trading bot, you’ll combine several powerful tools:

These tools form the backbone of modern DIY algorithmic trading systems—and they’re all accessible for free or at low cost.


Choosing Technical Indicators: RSI and MACD

The success of any trading bot hinges on its underlying strategy. In this guide, we use two widely adopted technical indicators:

Relative Strength Index (RSI)

RSI measures the speed and change of price movements on a scale from 0 to 100. It helps identify overbought (>70) and oversold (<30) conditions—ideal for momentum reversals.

Moving Average Convergence Divergence (MACD)

MACD tracks trend momentum by calculating the difference between two exponential moving averages (EMAs). The standard configuration uses:

Crossovers between the MACD line and signal line generate strong entry and exit signals.

Together, RSI and MACD provide a balanced approach—filtering noise while capturing high-probability trend shifts.


Designing Your Entry & Exit Strategy

Before coding, define clear rules for when your bot should enter or exit trades.

Buy Signals (Entry Conditions)

Sell Signals (Exit Conditions)

These conditions ensure trades align with both momentum and trend direction—reducing false signals.


Writing Pseudocode with ChatGPT

Rather than jumping straight into Python, use ChatGPT to generate pseudocode—a human-readable outline of your strategy logic.

Example Prompt:

You are an expert Python developer and algorithmic trading specialist. Write commented pseudocode for a trend-following strategy using:

  • RSI (14-period)
  • MACD (12, 26, 9)

Include entry conditions (oversold bounce + bullish crossover + MACD > 0), exit conditions (overbought reversal + bearish crossover + MACD < 0), position sizing (1–3% of account), and stop-loss/take-profit logic.

ChatGPT will return structured logic you can later convert into executable code. This step ensures clarity before implementation.


Converting Pseudocode to Python

Now, refine your prompt to generate actual Python code using Alpaca’s alpaca-py SDK.

Key Tips:

👉 Access Alpaca’s SDK documentation and start building securely.

Here’s a simplified version of what your final code might look like:

import alpaca_trade_api as tradeapi
import pandas as pd
from talib import RSI, MACD

# Load API keys from .env
api = tradeapi.REST('API_KEY', 'SECRET_KEY', base_url='https://paper-api.alpaca.markets')

def get_data(symbol):
    bars = api.get_bars(symbol, timeframe='1Hour', limit=300).df
    return bars

def generate_signals(df):
    df['rsi'] = RSI(df['close'], timeperiod=14)
    macd, signal, _ = MACD(df['close'], fastperiod=12, slowperiod=26, signalperiod=9)
    df['macd'] = macd
    df['signal'] = signal
    # Add buy/sell logic here
    return df

Test this locally in a Jupyter notebook first, then deploy.


Automating the Bot on AWS EC2

Running your bot on your personal computer isn’t reliable. Instead, deploy it on an AWS EC2 instance for 24/7 uptime.

Steps:

  1. Launch an Ubuntu EC2 instance.
  2. Install Python, pip, and required packages (alpaca-py, python-dotenv, tqdm).
  3. Upload your code via Git or SCP.
  4. Set up a virtual environment.
  5. Use cron to schedule execution every hour during market days.

Cron Job Example (runs Mon–Fri at 9:30 AM ET):

CRON_TZ=America/New_York
30 9 * * 1-5 /home/ubuntu/venv/bin/python /home/ubuntu/bot/strategy.py >> /home/ubuntu/bot/trade_log.txt 2>&1

Use crontab -e to edit and crontab -l to verify. Monitor logs in real time with tail -f trade_log.txt.


Monitoring Performance

After deployment, monitor two key areas:

1. System Health (via AWS CloudWatch)

Track CPU usage, memory, and network activity to ensure stability.

2. Trade Logs

Review log outputs like:

2025-05-15 12:43:09 INFO: === Strategy started ===
2025-05-15 12:43:12 INFO: Fetched 3299 bars
2025-05-15 13:00:03 INFO: BUY signal triggered for TQQQ

Logs help debug issues and validate strategy performance over time.


Frequently Asked Questions

What are RSI and MACD used for in trading bots?

RSI identifies overbought or oversold market conditions, while MACD detects changes in trend momentum. Together, they help bots make informed decisions about when to enter or exit positions based on price strength and direction.

Can I build a trading bot without coding experience?

Yes—using AI tools like ChatGPT, you can describe your strategy in plain English and let the model generate the code. However, basic understanding of Python and APIs improves accuracy and customization.

Is Alpaca’s API really free?

Alpaca offers a free tier with commission-free trading for U.S. stocks and ETFs. Paper trading is fully free, allowing unlimited testing without risk. Real-time data requires an Algo Trader Plus subscription.

How do I keep my API keys secure?

Never hardcode keys in your scripts. Use a .env file excluded from version control (add it to .gitignore). On AWS, consider using IAM roles or AWS Secrets Manager for enhanced security.

Can this bot work with cryptocurrencies?

While this guide focuses on equities via Alpaca, similar logic applies to crypto markets. Platforms like OKX offer advanced APIs for building crypto-focused bots using the same RSI/MACD strategies.

👉 Start building crypto trading bots with real-time data access.

How often should I review my bot’s performance?

Review logs weekly and conduct formal backtests monthly. Markets evolve—your strategy should too. Adjust parameters like RSI thresholds or position sizing based on performance trends.


Final Thoughts

Building an RSI and MACD trading bot with ChatGPT and Alpaca empowers traders to automate sophisticated strategies without deep coding expertise. By leveraging AI for logic generation, cloud computing for reliability, and robust APIs for execution, you can create a scalable system that operates around the clock.

Remember: automation doesn’t eliminate risk—it amplifies both gains and losses if not properly managed. Always test thoroughly in a paper environment, monitor performance closely, and maintain strict risk controls.

With the right tools and disciplined approach, anyone can enter the world of algorithmic trading—starting today.