A Python algorithmic trading bot using Alpaca's paper trading API for stocks. The bot uses technical indicators (RSI, MACD, SMA) to generate trading signals and includes risk management features.
The core data fetching logic (get_latest_1min_bar() and check_1min_feed_health() in src/data/market_data_client.py) is finalized and should NOT be modified.
These methods have been carefully tested and verified to work correctly with Alpaca's API. Any modifications can break the bot's ability to detect fresh data.
See docs/DATA_FETCHING_LOGIC.md for complete documentation and guidelines.
algo-bot/
├── requirements.txt
├── .env # API keys, secrets (create from .env.example)
├── main.py # Entry point for live trading
└── src/
├── __init__.py
├── config.py # Configuration and environment variables
├── broker/
│ ├── __init__.py
│ └── alpaca_client.py # Alpaca broker client
├── data/
│ ├── __init__.py
│ └── market_data_client.py # Market data fetching
├── indicators/
│ ├── __init__.py
│ └── indicator_engine.py # Technical indicators (RSI, EMA, MACD, etc.)
├── strategy/
│ ├── __init__.py
│ ├── base_strategy.py # Base strategy class
│ └── rsi_macd_strategy.py # RSI + MACD + SMA strategy
├── risk/
│ ├── __init__.py
│ └── risk_manager.py # Position sizing, risk limits
├── engine/
│ ├── __init__.py
│ └── event_loop.py # Main trading loop
└── backtest/
├── __init__.py
└── backtester.py # Backtesting engine
-
Install dependencies:
pip install -r requirements.txt
-
Create
.envfile: Create a.envfile in the root directory with your Alpaca API credentials:ALPACA_API_KEY=your_real_key_here ALPACA_SECRET_KEY=your_real_secret_here ALPACA_PAPER=true ALPACA_BASE_URL=https://paper-api.alpaca.markets
Important: Make sure there are no extra quotes or spaces around the values.
To get API keys:
- Sign up at Alpaca Markets
- Go to your dashboard and generate paper trading API keys
-
Test your connection:
python3 -m src.engine.test_connection
This should display your account status and equity.
-
Test indicators:
python3 -m src.engine.test_indicators
This will fetch real market data and calculate indicators to verify everything works.
-
Configure trading parameters: Edit
src/config.pyto adjust:- Watchlist symbols
- Timeframe
- Risk parameters (position size, stop loss, etc.)
- Strategy parameters (RSI periods, SMA periods, etc.)
Before running, check src/config.py:
EXECUTE_TRADES = False # Set to True to enable actual tradingDry-Run Mode (EXECUTE_TRADES = False):
- The bot will analyze markets and generate signals
- It will log what trades it would make with
[DRY RUN]prefix - No actual orders will be placed
- Perfect for testing and validation
Live Trading Mode (EXECUTE_TRADES = True):
- The bot will execute real trades on your Alpaca paper trading account
- All orders will be placed with risk management
- Monitor closely, especially on first runs
Run the bot with:
python main.pyThe bot will:
- Monitor symbols in the watchlist
- Generate trading signals using the RSI + MACD + EMA strategy
- Execute trades with risk management (if EXECUTE_TRADES = True)
- Log all activity to
trading_bot.logand console
Create a backtest script (e.g., backtest_example.py):
from datetime import datetime, timedelta
from src.strategy import RsiMacdStrategy
from src.backtest import Backtester
if __name__ == "__main__":
strategy = RsiMacdStrategy()
backtester = Backtester(strategy, initial_capital=100000.0)
results = backtester.run(
symbol="AAPL",
start_date=datetime.now() - timedelta(days=365),
end_date=datetime.now(),
timeframe="1Day",
)
print(f"Total Return: {results['total_return_pct']:.2f}%")
print(f"Win Rate: {results['win_rate']:.2%}")
print(f"Max Drawdown: {results['max_drawdown']:.2%}")
print(f"Number of Trades: {results['num_trades']}")- Modular Architecture: Clean separation of concerns with dedicated modules
- Strategy Framework: Easy to create new strategies by extending
BaseStrategy - Risk Management: Position sizing, stop losses, daily loss limits
- Technical Indicators: RSI, MACD, EMA, ATR (pure pandas, no external libraries)
- Backtesting: Test strategies on historical data
- Paper Trading: Safe testing with Alpaca's paper trading API
- Dry-Run Mode: Test strategies without executing trades
- Safety Switch: Global
EXECUTE_TRADESflag to prevent accidental trading
Key settings in src/config.py:
WATCHLIST: Symbols to monitorTIMEFRAME: Bar timeframe (1Hour, 1Day, etc.)MAX_POSITION_SIZE: Maximum position size as % of portfolioMAX_PORTFOLIO_RISK: Maximum risk per trade as % of portfolioSTOP_LOSS_PCT: Stop loss percentageTAKE_PROFIT_PCT: Take profit percentageMAX_DAILY_LOSS: Daily loss limit before stopping
The default RsiMacdStrategy uses:
- RSI: Oversold/overbought conditions
- MACD: Trend confirmation
- SMA Crossover: Trend direction
Buy signals when:
- RSI recovering from oversold
- Fast SMA above slow SMA (or bullish crossover)
- MACD bullish
- Position sizing based on stop loss distance
- Maximum position size limits
- Portfolio exposure limits
- Daily loss limits
- Automatic stop loss and take profit orders
All trading activity is logged to:
- Console (stdout)
trading_bot.logfile
This is for educational purposes only. Trading involves risk. Always test strategies thoroughly before using real money.