A fully automated, risk-managed trading bot for the NYSE (via Interactive Brokers) and multiple crypto exchanges, with paper-trading support, real-time alerts, a modular strategy engine, and an interactive dashboard. Built from scratch in Python.
π‘ Found a bug? Have an idea? Open an issue β every suggestion helps this project grow!
- Multi-strategy engine β runs Trend-Following (Long/Short), Trend-Following (Long Only), Mean-Reversion, Opening Range Breakout, and VWAP Reversion simultaneously.
- Position-aware signal resolver β merges signals from all active strategies and resolves conflicts based on your current position, preventing accidental naked short selling and handling reversals safely.
- Long/Short capability β enters both long and short positions with hard bracket stops (IBKR) or market orders (crypto). Short selling is automatically disabled on cash accounts and on crypto exchanges that don't support it.
- Multi-platform trading β supports Interactive Brokers (IBKR), Binance, OKX, Coinbase, Kraken, KuCoin, and a ready-to-use stub for the Nairobi Securities Exchange (NSE).
- Full risk management β ATR-based stops, Kelly-dynamic position sizing, max portfolio heat, gross/net exposure limits, daily loss limits, drawdown protection, single-name limits, and an earnings blackout filter. Risk limits can be configured per broker (e.g., looser limits for a small crypto account, tight limits for a large equity account).
- Trailing stops & partial exits β automatically tightens stop orders and scales out of positions on exit signals.
- Hybrid data pipeline β Yahoo Finance for US stocks; ccxt (direct exchange API) for crypto pairs, both with local Parquet caching.
- Real-time dashboard β FastAPI dashboard showing NAV, daily P&L, unrealised P&L, equity curve, open positions, and trade history.
- Realistic paper-trading simulation β simulated slippage, commissions, partial fills, and short-availability checks make the paper account behave exactly like a live account.
- Position synchronisation β internal positions are reconciled with IBKRβs reported positions every iteration.
- Custom API β REST endpoints for signals, positions, and performance (
/api/signals,/api/positions,/api/performance). - Notifications β real-time alerts to Discord (embeds), Telegram, and Email (Brevo API or SMTP).
- Backtesting β a custom loop-based backtester that runs the exact same strategy classes and signal resolver as the live engine, supporting multi-strategy, position-aware simulations.
- Headless operation β runs 24/7 on a VPS or local machine.
- Modular design β easy to swap data providers, brokers, or strategies.
- Dependency injection β all major components can be injected for easy unit testing.
- Onboarding wizard β a browser-based setup tool that writes your
.envandsettings.yamlwithout manual editing.
trading_bot/
βββ config/
β βββ settings.yaml # Main runtime configuration
β βββ setup.html # Onboarding wizard UI
βββ data/
β βββ manager.py # Data fetching & caching
β βββ provider.py # Abstract data provider
β βββ yahoo_provider.py # Yahoo Finance implementation
βββ strategies/
β βββ signals.py # Signal enum
β βββ base.py # Base strategy class
β βββ trend_following_ls.py # Long/Short trend following (50/200 SMA + RSI)
β βββ trend_following_long_only.py
β βββ mean_revisions.py # Bollinger Bands + RSI
β βββ orb.py # Opening Range Breakout
β βββ vwap_revisions.py # VWAP mean reversion
βββ backtest/
β βββ engine.py # Loop-based backtester (uses live resolver)
β βββ backtest_multi.py # Multi-symbol backtest runner
βββ execution/
β βββ broker.py # Abstract broker interface
β βββ ib_broker.py # Interactive Brokers (bracket orders, margin detection)
β βββ binance_broker.py # ccxt
β βββ okx_broker.py
β βββ coinbase_broker.py
β βββ kraken_broker.py
β βββ kucoin_broker.py
β βββ nse_broker.py # NSE stub (placeholder)
β βββ deriv_broker.py
β βββ olymprade_broker.py
β βββ oneinch_broker.py
β βββ web3_dex_broker.py
β βββ broker_manager.py # Dynamically loads enabled brokers
βββ risk/
β βββ manager.py # Risk rules & exposure calculation (per-broker profiles)
β βββ position_manager.py # Per-broker position tracking
βββ monitoring/
β βββ api.py # FastAPI dashboard & REST API
β βββ discord_alerter.py
β βββ telegram_alerter.py
β βββ email_alerter.py # Brevo + SMTP
βββ live/
β βββ engine.py # Main orchestrator β multi-broker loop
βββ utils/
β βββ config.py # YAML loader with env var override
β βββ logger.py # Loguru configuration
β βββ security.py # Encryption/decryption helpers
βββ logs/ # Runtime logs & trade journal
βββ tests/ # Unit & integration tests
βββ requirements.txt
βββ README.md
- Python 3.11+
- Interactive Brokers Gateway (or TWS) with paper trading account (for IBKR trading)
- (Optional) API keys for crypto exchanges
- (Optional) Discord webhook, Telegram bot, or email account for alerts
git clone https://github.com/Native-254/trading-bot.git
cd trading-bot
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txtCopy the settings template and edit it:
cp config/settings.yaml.template config/settings.yaml
nano config/settings.yamlCreate a .env file for secrets (never commit):
echo "IB_ACCOUNT_ID=DU123456" >> .env
echo "DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/..." >> .env
echo "TELEGRAM_BOT_TOKEN=..." >> .env
echo "TELEGRAM_CHAT_ID=..." >> .env
echo "EMAIL_SENDER=your-email@gmail.com" >> .env
echo "EMAIL_RECIPIENT=recipient@email.com" >> .env
# For Brevo (primary email transport)
echo "EMAIL_BREVO_API_KEY=your_brevo_api_key" >> .env
# For Gmail SMTP (fallback)
echo "EMAIL_PASSWORD=your-16-char-app-password" >> .env
# Add any crypto exchange keys as needed (see docs)Once the bot is running, visit http://localhost:8000/setup to configure brokers and symbols through a web UI β no manual YAML editing required.
Start IB Gateway (paper trading) with API enabled (port 4002).
Set paper_trading: false in config/settings.yaml β the bot will send real bracket orders to the paper account.
Enable realistic simulations in the same config (slippage, commissions, partial fills, short checks β all on by default).
Launch the bot:
python live/engine.pyWatch the terminal logs and your Discord/Telegram for trade alerts.
Note: By default, the bot runs the main iteration every hour at :01 (1 minute after the hour). To change the schedule, edit
live/engine.py(look forschedule.every).
Once the bot is running, open http://localhost:8000/dashboard to see your current NAV, open positions, equity curve, and recent trades.
The bot supports multiple strategies simultaneously. Signals are collected from all active strategies and resolved through a central Signal Resolver that only generates trade actions consistent with your current positions.
TrendFollowingLSβ Long when 50-SMA > 200-SMA and RSI < 30; short when 50-SMA < 200-SMA and RSI > 70.TrendFollowingLongOnlyβ Same as above but only takes long entries (no short selling).MeanReversionβ Long when price is below the lower Bollinger Band and RSI < 30; exit long when above the upper band and RSI > 70.OpeningRangeBreakoutβ Long/short breakouts from the first 30 minutes with volume filter.VWAPReversionβ Anchored VWAP Β±2 SD bands with RSI confirmation; long at lower band (RSI<30), short at upper band (RSI>70).
- If already long:
EXIT_LONGβ sell to close.ENTER_SHORTβ sell to close first (reversal will be evaluated on the next bar). - If already short:
EXIT_SHORTβ buy to cover.ENTER_LONGβ buy to cover first. - If flat:
ENTER_LONGalone β buy.ENTER_SHORTalone β sell short. - Both
ENTER_LONGandENTER_SHORTβ no action (conflict).
This prevents naked shorts, double entries, and accidental reversals.
The bot enforces strict risk rules before every trade. All limits can be set per broker via the risk_by_broker section in settings.yaml, allowing different parameters for crypto vs. equities.
- Dynamic position sizing β risk per trade is determined by a half-Kelly criterion based on recent win/loss history (capped at 5% of equity).
- Max portfolio heat β total open risk cannot exceed a configurable fraction of equity (default 15%).
- Gross exposure limit β prevents total notional value of all positions from exceeding a safe multiple of equity (default 1.5x).
- Net exposure limit β caps the absolute difference between long and short notional.
- Single-name limit β no single position may exceed 20% of equity.
- Daily loss limit β stops trading if the dayβs P&L drops below a set threshold.
- Max drawdown β reduces position sizes after a configurable drawdown from peak equity.
- ATR-based stops β initial and trailing stop-losses are calculated using Average True Range.
- Bracket orders for longs and shorts β entries are protected with attached stop-loss and take-profit orders (IBKR only).
- Short-availability check β verifies that shares are available to short before placing a short order. On IBKR, the bot also detects the account type (margin vs. cash) and automatically blocks short selling on cash accounts.
- Earnings blackout filter β avoids opening new positions near earnings announcements.
All values can be adjusted in config/settings.yaml.
The bot connects to Interactive Brokers via ib_async. In paper mode, you can enable a set of realistic simulation features that make the paper account behave indistinguishably from a live account:
| Feature | Description | Config Key |
|---|---|---|
| Slippage | Adds a small adverse price movement (default 0.05%) to every trade | simulate_slippage, slippage_percent |
| Commissions | Charges realistic IBKR stock commissions ($0.005/share, min $1, max 1%) | simulate_commissions, commission_* |
| Partial fills | Randomly fills only 80-100% of your order to simulate real market behaviour | simulate_partial_fills, partial_fill_min_ratio |
| Short availability | Checks with IBKR that shares are available to short before sending a short order | short_availability_check |
These are enabled by default in paper mode. Disable them when you switch to a live account.
- Discord β Rich embeds with trade details (symbol, action, quantity, price) and error alerts. Set up via webhook URL in
.env. - Telegram β Plain text alerts. Requires a bot token and chat ID (obtain via @BotFather).
- Email β Trade alerts and critical error messages sent via Brevo API (primary) or Gmail SMTP (fallback).
Add the following to your .env:
EMAIL_SENDER=your-email@gmail.com
EMAIL_RECIPIENT=recipient@email.com
EMAIL_BREVO_API_KEY=your-brevo-api-key # for Brevo
EMAIL_PASSWORD=your-gmail-app-password # for SMTP fallbackAll three channels can be enabled/disabled independently.
The backtesting engine now mimics the live bot exactly. It re-uses the same strategy classes, signal resolver, and risk checks in a loop over historical data.
To backtest all symbols in your configuration:
python backtest_multi.pyOr programmatically:
from backtest.engine import BacktestEngine
from data.manager import DataManager
data_mgr = DataManager()
df = data_mgr.get_data("AAPL", start_date="2020-01-01", end_date="2024-01-01", interval="1d")
engine = BacktestEngine()
result = engine.run("AAPL", df, start_date="2020-01-01", end_date="2024-01-01")
print("Final capital:", result['final_capital'])
print("Number of trades:", result['total_trades'])
print("Equity curve:", result['equity_curve'])The engine simulates slippage, commissions, trailing stops, and the full position-aware resolver on each bar.
The bot can run unattended on a free-tier Oracle Cloud, Google Cloud, or AWS instance.
Recommended: Oracle Cloud Always Free (4 ARM cores, 24 GB RAM).
- Provision an Ubuntu VM.
- Clone the repo, install dependencies, add config files.
- Run as a systemd service for auto-start and crash recovery.
A sample service file is provided in the Wiki.
IrieTrade already supports multiple centralised exchanges through a unified Broker interface. Each broker is instantiated by the BrokerManager based on your platforms list in settings.yaml.
| Platform | Status |
|---|---|
| Interactive Brokers | Fully functional (paper & live bracket orders) |
| Binance | ccxt β market orders only |
| OKX | ccxt β market orders only |
| Coinbase | ccxt β market orders only |
| Kraken | ccxt β market orders only |
| KuCoin | ccxt β market orders only, live-tested |
| NSE (Nairobi) | Stub ready β no trading API yet, but infrastructure in place |
To add a new exchange, create a class implementing Broker, register it in broker_manager.py, and add its configuration.
MIT β use, modify, and distribute freely.
This bot is for educational purposes. Use at your own risk. Past performance does not guarantee future results. Always test thoroughly in paper trading before committing real capital.
