Skip to content

Event-driven Python trading engine implementing EMA-based signal generation and risk-controlled execution.

Notifications You must be signed in to change notification settings

hahnaughton/EMA_TradingEngine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Algorithmic Trading Bot

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.

⚠️ Important: Data Fetching Logic

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.


Project Structure

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

Setup

  1. Install dependencies:

    pip install -r requirements.txt
  2. Create .env file: Create a .env file 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
  3. Test your connection:

    python3 -m src.engine.test_connection

    This should display your account status and equity.

  4. Test indicators:

    python3 -m src.engine.test_indicators

    This will fetch real market data and calculate indicators to verify everything works.

  5. Configure trading parameters: Edit src/config.py to adjust:

    • Watchlist symbols
    • Timeframe
    • Risk parameters (position size, stop loss, etc.)
    • Strategy parameters (RSI periods, SMA periods, etc.)

Usage

Live Trading

⚠️ IMPORTANT: The bot starts in DRY-RUN mode by default!

Before running, check src/config.py:

EXECUTE_TRADES = False  # Set to True to enable actual trading

Dry-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.py

The 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.log and console

Backtesting

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']}")

Features

  • 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_TRADES flag to prevent accidental trading

Configuration

Key settings in src/config.py:

  • WATCHLIST: Symbols to monitor
  • TIMEFRAME: Bar timeframe (1Hour, 1Day, etc.)
  • MAX_POSITION_SIZE: Maximum position size as % of portfolio
  • MAX_PORTFOLIO_RISK: Maximum risk per trade as % of portfolio
  • STOP_LOSS_PCT: Stop loss percentage
  • TAKE_PROFIT_PCT: Take profit percentage
  • MAX_DAILY_LOSS: Daily loss limit before stopping

Strategy

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

Risk Management

  • Position sizing based on stop loss distance
  • Maximum position size limits
  • Portfolio exposure limits
  • Daily loss limits
  • Automatic stop loss and take profit orders

Logging

All trading activity is logged to:

  • Console (stdout)
  • trading_bot.log file

Disclaimer

This is for educational purposes only. Trading involves risk. Always test strategies thoroughly before using real money.

About

Event-driven Python trading engine implementing EMA-based signal generation and risk-controlled execution.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages