
Artificial intelligence, particularly large language model(LLM) tools like ChatGPT, Claude, or Gemini, is increasingly impacting traders. Individual traders are utilizing these platforms throughout their trading processes, including strategy development, market research, and code creation.
The popularity of AI-driven trading solutions is evident in the growing number of projects and discussions within the developer community. For instance, there is research showing GitHub hosts over 71,000 ChatGPT-related projects, many of which are focused on trading. This surge reflects a significant interest in leveraging AI for trading purposes.
In this guide, we highlight how traders can use ChatGPT to create and automate a Python trading bot with Alpaca's Trading API. From learning how to develop a strategy using Relative Strength Index (RSI) and Moving Average Convergence Divergence (MACD) indicators to coding it and deploying on AWS EC2 for scheduled execution with cron jobs, this tutorial provides the necessary tools to integrate AI into your trading. It’s suitable for individual traders who want to explore more advanced trading approaches and build a trading bot.
While the aim for this tutorial is to be as detailed as possible, we are aware that including every piece of information is not possible. This guide should be seen as a starting point for how you can use tools like ChatGPT to build and deploy trading strategies.
Before diving into the guide, make sure you’ve completed the following:
How to Build an RSI and MACD Algorithmic Trading Bot with ChatGPT and Alpaca
In this tutorial, we’ll walk you through how to build a trading bot using ChatGPT, Alpaca’s Trading API, and some other tools.
This tutorial outlines:
- How to follow a trading strategy from idea to implementation
- How to interpret ChatGPT’s responses and tailor them for your use case
- How to deploy the trading strategy as a trading bot to AWS EC2
Important Notes:
- Using a premium AI model (e.g., ChatGPT o4-mini-high, Claude 3.7 Sonnet, or Gemini 2.5 Pro) may be recommended, as these models offer better accuracy and depth for financial tasks.
- Strong prompt engineering makes a big difference, as shown in “Claude Code: Best practices for agentic coding”
- Please note that we use “TQQQ” as an example throughout the tutorial. This is for demonstration only and not investment advice.
Step 1: Define Your Objective for the Trading Bot with Help from ChatGPT
Before writing code, we want to clearly define what the bot should do. A well-defined objective helps ChatGPT generate useful and focused responses.
In this tutorial, we define the goals of this step:
- Use ChatGPT to outline the full workflow. We can start small and expand the scope as needed.
- Make the bot run independently—no manual commands once deployed.
- Build a strategy using common indicators, including entry and exit logic, with Alpaca’s Trading API.
- Write Python code based on the strategy with ChatGPT’s help.
- Set up automation using AWS to keep the bot running reliably.
- Periodically monitor and evaluate performance.
To grasp the general design and development process for an algorithmic trading bot, the following prompt can be used. While the resulting output might appear extensive, remember that incorporating every element isn't necessary.
Example Prompt to ChatGPT:
You are an expert trader and Python developer. Your task is to teach a beginner how to build, test, deploy, and run an automated trading bot using alpaca-py and AWS EC2. I will ask you a few questions separately, so please walk through each one accordingly. Keep your responses as simple and concise as possible.
- Define what an "algorithmic trading bot" is.
- To help with starting, provide a high-level overview of its architecture and the development steps involved.
- Identify and explain the essential components, tools, and files (python scripts) required for each stage of the process, including development, testing, deployment, and maintenance.
- Discuss how these components interact within the system and the considerations for selecting appropriate technologies for each part.
Step 2: Choose Essential Tech Stacks for the Trading Bot
Before engaging with ChatGPT or any large language model for algorithmic trading bot development, it is recommended to conduct some initial research. In this tutorial, we aim to start small by using only the most fundamental technologies.
Basic Tech Stack:
- macOS: The system used for local development. Most tools covered in this guide are optimized for macOS but are portable to Linux or Windows with minor changes.
- Terminal (macOS): Used to run scripts, install dependencies, and interact with remote servers via SSH.
- ChatGPT (o4-mini or advanced model): Helps write, debug, and refactor code. Advanced models are often recommended for interpreting trading logic and financial data structures.
- GitHub: For storing, versioning, and collaborating on the codebase.
- Python IDE: Any editor such as VS Code, PyCharm, or Cursor can be used to write and test bot logic in Python.
Cloud (AWS EC2): Used to host and automate the bot so it runs even when our local machine is off.

Step 3: Understand Popular Technical Indicators for Trading
To build a strategy-driven trading bot, we first want to understand the common technical indicators used by traders. These indicators help define our entry and exit rules, which we will later translate into Python code with ChatGPT.
In this step, we prompt ChatGPT to identify popular indicators and patterns based on community data and usage insights, especially from platforms like TradingView.
Example Prompt to ChatGPT:
You are a technical researcher in the field of trading.
List the most popular analytical chart indicators and patterns used for trading equities.
Most Commonly Used Indicators
According to Chat GPT, the following six indicators are among the most frequently used:
- Moving Averages (Simple Moving Average (SMA) and Exponential Moving Average (EMA)): Used to smooth price data and identify trend direction
- RSI: Measures momentum and identifies overbought or oversold conditions
- Stochastic Oscillator: Compares a stock’s closing price to its recent price range to detect reversals
- Bollinger Bands: Measures volatility and potential breakout ranges
- Moving Average Convergence Divergence (MACD): Tracks trend momentum using two EMA lines and a signal line
- Ichimoku Cloud: Offers a holistic view of trend, momentum, and support/resistance zones
Step 4: Understand and Design the Entry and Exit Strategies Using RSI and MACD Indicators
To automate a trading bot that makes decisions based on price momentum, we need to define clear entry and exit rules using technical indicators. For this tutorial, we focus on two popular tools: RSI and MACD.
ChatGPT can assist in designing rules using commonly accepted indicator settings and signal logic. In this section, we use prompts to define standard configurations and gather common signal patterns.
Prompt - Choosing RSI and MACD Settings and Signal Logic:
You are a financial educator.
I want you to show me the most commonly used combinations of periods for calculating the Relative Strength Index (RSI) and MACD signal.
ChatGPT would generate the output as shown below:
1. RSI period combinations
- 14 period only
- 7 period and 14 period together
- 9 period and 21 period together
2. MACD period combinations
- fast 12 slow 26 signal 9
- fast 5 slow 35 signal 5
- fast 8 slow 17 signal 9
- fast 12 slow 50 signal 9
To better understand the MACD output of (12, 26, 9), we’ve provided a brief explanation below:
- 12: This represents the short-term Exponential Moving Average (EMA), typically calculated over 12 periods. It reacts quickly to recent price changes.
- 26: This denotes the long-term EMA, usually over 26 periods, providing a smoother view of the price trend.
- 9: This is the signal line, a 9-period EMA of the MACD line itself, used to generate buy or sell signals.
Prompt - RSI Entry and Exit Signals:
Based on what ChatGPT suggests, we can write a prompt to ask for popular entry and exit signals for RSI indicators that we may want to use for our trading bot.
You are a financial educator. I want you to list popular RSI entry and exit signals for mid term trading in the following format:
- First, provide one concise paragraph that summarizes the key findings.
- After that, produce two main sections:
- Listing popular RSI entry signals
- Entry signal name
- Brief description
- Citation
- Listing popular RSI exit signals
- Exit signal name
- Brief description
- Citation
Prompt - MACD Entry and Exit Signals:
We can use a similar prompt to Chat GPT to identify widely recognized MACD entry and exit strategies used by traders with the standard 12-26-9 settings.
Now, do the same thing to list popular MACD entry and exit signals (12, 26, 9 settings) for mid term trading in the same format.
Insights from These PromptsBased on the outputs from ChatGPT, the following indicator settings and signal definitions can be applied to build a trading bot strategy.
Indicator Settings (Baseline Configuration)
- Standard RSI settings: The default number of periods (14) is used when calculating the RSI.
- Standard MACD settings: Fast EMA 12, Slow EMA 26, Signal line EMA 9.
Buy Signals (Entry Conditions)
- Oversold Bounce Entry: RSI drops below 30 and then rises back above 30, suggesting a potential bullish reversal.
- MACD Line / Signal Line Bullish Crossover: When the MACD line crosses above the signal line, indicating growing upward momentum.
- Zero Line (MACD Centerline) Crossover (Bullish): When the MACD line crosses from below to above the zero line, confirming a shift toward a bullish trend.
Sell Signals (Exit Conditions)
- Overbought Reversal Exit: RSI rises above 70 and then dips below 70, signaling possible exhaustion of upward momentum.
- MACD Line / Signal Line Bearish Crossover: When the MACD line crosses below the signal line, indicating a possible downtrend.
- Zero Line (MACD Centerline) Crossover (Bearish): When the MACD line crosses from above to below the zero line, signaling a shift back to bearish momentum.
Step 5: Write Pseudocode for Algorithmic Trading Using RSI and MACD
Building on insights from earlier ChatGPT outputs, we refine our trading strategy and craft a prompt to generate pseudocode. The purpose of writing pseudocode is to outline the logic in a way that’s easy to understand before translating it into actual Python code. Pseudocode uses semi-natural language instead of strict Python syntax, helping us visualize the structure and logic of the strategy. From there, we can implement the final version in code more confidently.
Example Prompt to ChatGPT:
Write clear commented pseudocode for a trend following strategy using
- RSI 14-period for medium term trend filtering
- MACD 12-period EMA minus 26-period EMA with a 9-period EMA signal line
Entry Conditions
- 1. RSI falls below 30 then rises back above 30 before reaching 50
- 2. MACD line crosses above its 9-period signal line golden cross
- 3. MACD line is above zero at the time of crossover
Exit Conditions
- 1. RSI rises above 70 then drops below 60 toward 50
- 2. MACD line crosses below its 9-period signal line death cross
- 3. MACD line falls below zero
Additional requirements
- Define a big trend on a higher timeframe using three moving averages compared against each other
- Cap position size at one to three percent of account value
- Define stop loss and take profit as simple fixed percentages of entry price
We then receive pseudocode like the example below. It is illustrative and incomplete, so we need to convert it into working code.
# Entry: both signals within WINDOW_SIZE bars
if not position_open and in_uptrend and market_trend_ok:
if rsi_bounce_bar and macd_cross_bar and abs(rsi_bounce_bar - macd_cross_bar) <= WINDOW_SIZE:
size = calculate_position_size(account_value, MAX_RISK_PCT)
client.submit_order("TQQQ", qty=size, side="buy", type="market")
set_stops_using_atr(df_main) # ATR‑based stops :contentReference[oaicite:13]{index=13}
rsi_bounce_bar = None
macd_cross_bar = None
If you want a sneak peek at the completed Python code that actually runs on AWS EC2, you can check out Alpaca’s GitHub repository.
Step 6: Converting Pseudocode to Functional Code
This is the stage where we translate the pseudocode into working Python code using alpaca-py.
To make this process more effective, consider switching to a more advanced LLM model, and structure your prompts with the following approach:
Key Guidelines:
- Include reference links (Alpaca-py’s SDK, GitHub, and documentation)
- Clearly indicate what you want the model to review (e.g., entry/exit rules)
- Stay focused on your core goals:
- Define entry and exit logic using RSI and MACD
- Automate trading actions
- Log trades and bot behavior
- Keep the initial code as simple as possible for testing
- Ask the model follow-up questions for any part you don’t fully understand
You are an expert Python developer and algorithmic trading specialist. Convert the following pseudocode into a single complete Python file that uses Alpaca‑py for data and trading. Output only valid Python code in one uninterrupted code block from imports through helper functions through the main execution loop and scheduling.
Most API calls should be based on Alpaca-py. Refer to the following Alpaca-py resources for guidance:
- https://alpaca.markets/sdks/python/
- https://alpaca.markets/learn
- https://github.com/alpacahq/alpaca-py
Template variables to replace exactly once each
- API_KEY_VAR: name of the variable holding the Alpaca API key
- API_SECRET_VAR: name of the variable holding the Alpaca secret key
- PAPER_FLAG_VAR: name of the variable indicating paper trading mode
- TRADE_API_URL_VAR: name of the variable for the custom trading API URL
- UNDERLYING_SYMBOL: ticker symbol string
- RSI_PERIOD: integer lookback for RSI
- MACD_FAST_EMA: integer for MACD fast EMA
- MACD_SLOW_EMA: integer for MACD slow EMA
- MACD_SIGNAL_EMA: integer for MACD signal EMA
- BIG_TREND_FAST_MA: integer period for fast moving average on higher timeframe
- BIG_TREND_SLOW_MA: integer period for slow moving average on higher timeframe
- MAX_RISK_PERCENT: float maximum risk fraction of account value
- STOP_LOSS_PERCENT: float percent below entry for stop loss
- TAKE_PROFIT_PERCENT: float percent above entry for take profit
- TIMEFRAME_MAIN: TimeFrameUnit enum for medium timeframe
- TIMEFRAME_TREND: TimeFrameUnit enum for higher timeframe
- WINDOW_SIZE: integer lookback window for signal alignment
Here is the pseudocode to convert
pseudo code
To achieve our objectives, we may need to further adjust some code and create additional files.
- Remove any extra logic generated by ChatGPT—such as the ADX filtering—that overcomplicates this tutorial.
- Develop and test the code in a Jupyter notebook, then save the final version to a Python file (for example, strategy.py).
- Store your API key in “secret.py” and list required packages in “requirements.txt”.
- Update each helper function and the entry and exit logic so they produce the expected output.
- Add logic to pause the bot when the market is closed so it fetches data only during trading hours and respects the free tier’s per‑minute API limit by running the strategy once per hour (or every thirty minutes) instead of every second.
- Modify the code to accept various input values (e.g., NA or 0).
- Implement logging functionality (we can request ChatGPT to add it via prompt).
I want to create a log whenever an action is performed.
Step 7: Identify How to Automate Trading Strategy on AWS EC2
After designing the algorithmic trading strategy (including entry and exit logic) in strategy.py, we prepare the other essential files— ‘requirements.txt’ and ‘secret.py’. Unless you plan to leave your personal machine running around the clock, you would likely want to use a cloud-based computer like AWS EC2 to automate your trading bot.
IAM account over root user
In AWS, there are two main types of accounts: the root user and IAM user. The root user has full access to everything and is created when you first set up your AWS account. IAM users are added later and can be given limited access to specific services. For better security, It is strongly recommended creating an IAM user and using it to set up your EC2 instance.
Use ‘Cron’ to automate trading bot on AWS EC2
To enable your trading script to resume automatically when the market opens the next day, even if it stopped running after the close, we may have a couple approaches to use. Here, we schedule the script to start each market open via cron job on EC2.
Below is a prompt that generates step-by-step instructions for setting up automation on EC2 using the terminal.
You are an expert Linux systems engineer. Provide a step‑by‑step guide for scheduling a Python trading bot (strategy.py) on an EC2 Ubuntu instance using cron so it runs at [CRON_TIME] in [TIME_ZONE]. The bot’s files live under [SCRIPT_DIR], the main script is [SCRIPT_NAME], and logs go to [LOG_FILE]. Include:
- How to activate the virtual environment in [SCRIPT_DIR]/venv
- Exact crontab lines (with
CRON_TZ=[TIME_ZONE]
and[CRON_TIME]
)- Keystrokes to edit, save, and exit the crontab
- How to verify cron is active and the job entry (
crontab -l
,systemctl status cron
)- How to manually start the bot now (activating venv and running
python [SCRIPT_NAME]
)- How to monitor progress
Use only absolute paths and minimal commentary so a beginner can follow it exactly.
You would probably see the command as below. These commands run your bot every weekday at 9:30 AM Eastern Time and also redirect output and errors to a log file named log.txt.
CRON_TZ=America/New_York
30 9 * * * /home/ubuntu/alpaca-trading-bot-with-chatgpt/venv/bin/python /home/ubuntu/alpaca-trading-bot-with-chatgpt/strategy.py >> /home/ubuntu/alpaca-trading-bot-with-chatgpt/trade_log.txt 2>&1
After saving and closing the crontab, you can either wait for the next trading day's market open or manually run the cron command to ensure it works. The command below is a single line, not two separate commands.
/home/ubuntu/alpaca-trading-bot-with-chatgpt/venv/bin/python /home/ubuntu/alpaca-trading-bot-with-chatgpt/strategy.py
After running this command, the terminal does not display any output, but the trading bot is active.
Step 8: Monitor the Automate Trading Bot
We can check and monitor activity on the AWS EC2 dashboard,
Once the trading bot is up and running, monitoring becomes essential to ensure it behaves as expected and performs consistently. There are two primary ways we can track its activity:
AWS EC2 Monitoring Dashboard
- Use the EC2 instance’s CloudWatch metrics to observe system performance indicators such as CPU usage and network traffic. These metrics help confirm whether the bot is active, responsive, and within resource limits.

Terminal Logs (trade_log)
- The bot generates log messages that include strategy start times, data fetch events, and other operational milestones. Viewing these logs via the terminal provides a direct look at what the bot is processing in real time.
Example Log Output on Terminal:
2025-05-15 12:43:09 INFO: === Strategy started ===
2025-05-15 12:43:12 INFO: Fetched 3299 main bars and 144 trend bars
2025-05-15 13:00:03 INFO: Fetched 3299 main bars and 144 trend bars
2025-05-15 14:00:03 INFO: Fetched 3300 main bars and 144 trend bars
What Are Algorithmic Trading Bots?
For readers new to algorithmic trading bots, these are software programs that place trades automatically based on predefined rules or algorithms. They can analyze, react, and make trades based on market signals like price movements, volume, timing or technical indicators such as RSI or MACD.
Benefits of Trading Bots
- Real Time Trading: Bots can analyze market data in real time and act when certain conditions are met. They can send orders through APIs, allowing traders to run strategies even when we’re not monitoring the market.
- Logging and Tracking: Traders can log trades, manage positions, and backtest strategies using historical data before going live.
- Speed and Efficiency: Bots can monitor multiple markets and execute trades much faster than a human trader could.
- Continual Operation: Bots can run continuously, which is practical for markets like crypto that never close, or equities during extended hours or 24/5 environments.
Risks of Trading Bots
- Backfiring Strategies: Traders who depend entirely on trading bots without regularly reviewing performance or adapting to changing market conditions risk seeing their own algorithms work against them and incur unexpected losses.
- Data Security: Many bots also rely on weak or absent encryption, leaving sensitive user data exposed to potential breaches.
- Technical Issues: Bugs, connectivity problems, or API failures can disrupt bot operations and result in missed trades or unintended actions.
How Alpaca's Trading API Can Be Integrated with Trading Bots
For readers new to Alpaca’s Trading API, it offers commission-free trading and an easy-to-use API, making it a great choice for building trading bots with LLMs like ChatGPT.
Key features of Alpaca:
- Commission-Free Trading: Alpaca offers commission-free trading for US-listed stocks, ETFs, and options to retail customers.
- Asset Access: Users have access to over 11,000 US stocks and ETFs.
- API Offerings: Alpaca provides REST and WebSocket APIs for trading stocks, ETFs, crypto, and options.
- Trading Environments: Both paper (simulated) and live trading environments are available, allowing for testing and production deployments.
- Authentication Methods: Authentication is facilitated via OAuth or API keys.
- SDK Support: Alpaca offers SDKs in multiple programming languages, including Python, .NET/C#, Go, and Node.js.
- Real-Time Market Data: Free plan includes 15-minute delayed IEX data . For full real-time market coverage, consider the Algo Trader Plus plan.
- Extended Hours Trading: Extended hours trading is supported, providing access beyond regular market hours.
- Dashboard Monitoring: A web dashboard is available for monitoring trades and account activity.
With Alpaca, even low-code traders may be able to automate their trades and experiment with AI-driven agents from testing to live execution.
Conclusion
Building a trading bot with RSI and MACD offers a structured way to explore momentum strategies in algorithmic trading. These indicators help define entry and exit rules based on shifts in trend strength. With help from ChatGPT, we outlined the strategy, wrote pseudocode, and implemented it using Alpaca's Trading API.
By combining tools like Alpaca's Trading API, Python, and AWS EC2, we can automate strategy execution and refine it over time. Starting simple makes it easier to test, adjust, and scale the system as needed.
Of course, all trading involves risk. Automation may help reduce manual errors but not uncertainty. Market conditions, assumptions, and data quality still affect outcomes. Regular backtesting and risk controls remain essential.
As we put these concepts into practice, feel free to share your feedback and experiences on our forum, Slack community, or subreddit! For those looking to algorithmic trading with Alpaca’s Trading API, here are some additional resources:
- Sign up for an Alpaca Trading API account
- How to connect to Alpaca’s Trading API
- How to start paper trading with Alpaca
FAQ
Which AI trading bot is best for beginners?
There is no single best option. Many beginners start with simple Python-based bots that use broker APIs. Alpaca's Trading API is often used because it supports paper trading, real-time data, and is easy to connect with basic scripts.
What is the best AI trading bot for beginners?
The best choice depends on personal goals and experience. Some prefer to build a bot using tools like ChatGPT and Alpaca's Trading API, which makes it easier to test ideas with real-time data in a simulated environment.
How do I build an algorithmic trading bot?
Start by defining a strategy using indicators like RSI or MACD. Then write the logic in Python and connect it to a trading API. Alpaca's Trading API provides tools for paper trading and accessing market data, which can help during testing. Be sure to review results carefully before considering any live trades.
Please note that this tutorial is for general informational purposes only and is believed to be accurate as of the posting date but may be subject to change. The examples above are for illustrative purposes only.
Alpaca is not affiliated with ChatGPT or any of the companies or creators referenced in this article and is not responsible for the liabilities of the others.
Options trading is not suitable for all investors due to its inherent high risk, which can potentially result in significant losses. Please read Characteristics and Risks of Standardized Options before investing in options.
Past hypothetical backtest results do not guarantee future returns, and actual results may vary from the analysis.
Extended Hours trading has unique risks and is different from trading in the main trading session, for more information please visit our Alpaca Extended Hours Trading Risk Disclosure.
Orders placed outside regular trading hours (9:30 a.m. – 4:00 p.m. ET) may experience price fluctuations, partial executions, or delays due to lower liquidity and higher volatility.
Orders not designated for extended hours execution will be queued for the next trading session.
Additionally, fractional trading may be limited during extended hours. For more details, please review Alpaca Extended Hours & Overnight Trading Risk Disclosure.
All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not ensure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.
Cryptocurrency is highly speculative in nature, involves a high degree of risks, such as volatile market price swings, market manipulation, flash crashes, and cybersecurity risks. Cryptocurrency regulations are continuously evolving, and it is your responsibility to understand and abide by them. Cryptocurrency trading can lead to large, immediate and permanent loss of financial value. You should have appropriate knowledge and experience before engaging in cryptocurrency trading. For additional information, please click here.
The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.
Commission-free trading means that there are no commission charges for Alpaca self-directed individual cash brokerage accounts that trade U.S.-listed securities and options through an API. Relevant regulatory fees may apply. Commission-free trading is available to Alpaca's retail customers. Alpaca reserves the right to charge additional fees if it is determined that order flow is non-retail in nature.
Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
Cryptocurrency services are made available by Alpaca Crypto LLC ("Alpaca Crypto"), a FinCEN registered money services business (NMLS # 2160858), and a wholly-owned subsidiary of AlpacaDB, Inc. Alpaca Crypto is not a member of SIPC or FINRA. Cryptocurrencies are not stocks and your cryptocurrency investments are not protected by either FDIC or SIPC. Please see the Disclosure Library for more information.
This is not an offer, solicitation of an offer, or advice to buy or sell securities or cryptocurrencies or open a brokerage account or cryptocurrency account in any jurisdiction where Alpaca Securities or Alpaca Crypto, respectively, are not registered or licensed, as applicable.