Welcome to TradeBot
TradeBot is an automated algorithmic trading platform that connects to your broker accounts, runs 13 built-in strategies on a 60-second engine tick, enforces multi-layer risk controls, explains every trade with AI, and supports both stocks and crypto — all from one dashboard.
13 Built-in Strategies
7 stock strategies + 4 crypto strategies (Grid, RSI Bounce, Trend, Mean Reversion). Plus EMA Confluence and Classic Chart Patterns, which run on both stocks and crypto.
10-Layer Risk Engine
Kill switch, daily/weekly loss limits, PDT protection, max positions, symbol exposure, blacklist, consecutive losses, and per-account controls.
Stocks & Crypto
Alpaca for US stocks and Tradier for equities. Binance (paper & live) for 24/7 crypto spot trading with USDT pairs.
AI-Powered
Every trade gets a plain-English AI explanation. Weekly auto-tuner adjusts strategy parameters based on live performance using Claude or Ollama.
Backtesting Studio
Test any strategy against historical data with slippage, commission, and capital controls. Save and compare runs. Strategy health tracks live vs. backtest drift.
Webhook & Alerts
Receive signals from TradingView or any external tool via webhook. Set price alerts that notify you via Slack, Discord, Telegram, or email.
Start in Paper Trading mode. TradeBot defaults to paper trading. No real money is at risk until you explicitly add a live account and enable a strategy on it.
First-time Setup
Get TradeBot running in under 5 minutes.
Prerequisites
RequirementDetails
Python 3.11+Check with python --version.
Broker accountAlpaca (free, paper auto-created) for stocks, or Binance/Binance Demo for crypto.
API keysGenerated from your broker dashboard. You need both the key ID and the secret.
Installation & Launch
1
Run setup
Double-click setup.bat (Windows) or run pip install -r requirements.txt in a terminal.
2
Create your .env file
Copy .env.example to .env. The app auto-generates DB_SECRET_KEY on first launch — you don't fill it in manually. Once it's generated, back it up somewhere safe: it encrypts your broker keys and cannot be recovered if lost.
3
Start the server
Double-click start.bat or run uvicorn server.main:app --port 8000. The dashboard opens at http://localhost:8000.
4
Set your password
On first launch you'll be prompted to create a password. This protects all API endpoints and the dashboard.
5
Add a broker account & enable a strategy
Go to Broker Accounts, click Add Account, pick your broker, enter API keys. Then go to Bots & Strategies and enable a strategy for that account.
Keep your .env file private — it contains your encryption key and API credentials. Never commit it to version control.
Broker Accounts
TradeBot supports multiple broker accounts simultaneously. Each account has its own type (Paper or Live), credentials, and strategy assignments — managed independently.
Supported Brokers
BrokerAsset ClassPaper Trading
AlpacaUS Stocks & ETFsYes — separate paper API keys (start with PK)
TradierUS Stocks & ETFsYes — sandbox API at sandbox.tradier.com
BinanceCrypto Spot (USDT pairs)Yes — demo keys from demo.binance.com (separate from live)
Adding an Account
1
Click "Add Account"
On the Broker Accounts page, click the button and choose your broker from the tabbed picker (Stocks, Crypto, Forex, Futures).
2
Select Paper or Live
Choose the account type. For Binance paper trading, use demo keys from demo.binance.com — these are separate from your live Binance keys.
3
Enter API credentials
Paste your API Key and Secret. Keys are encrypted immediately with AES-256 before being saved — the secret is never stored in plaintext.
4
Test & assign strategies
Click Test on the account card to verify connectivity. Then go to Bots & Strategies to assign strategies to this account.
If you lose your DB_SECRET_KEY from .env, stored broker credentials cannot be decrypted. Back up your .env file securely.
Strategies & Bots
TradeBot comes with 13 automated strategies across stocks and crypto. The engine evaluates all enabled strategies every 60 seconds.
Stock Strategies
StrategyHow it worksBest for
MomentumScans top actives/gainers. Enters when price is above 20-day SMA and RSI is 40–70.Trending markets, high-volume days
RSI Mean ReversionBuys when RSI drops below 30 (oversold). Exits when RSI crosses 50.Range-bound stocks, post-selloff rebounds
MACD + VolumeEnters on bullish MACD crossover confirmed by above-average volume.Momentum with volume confirmation
Bollinger BandsBuys when price touches lower band with oversold RSI; exits at middle band.Mean-reverting, low-volatility stocks
Golden CrossEnters when 50-day SMA crosses above 200-day SMA.Long-term trend following
SMA CrossoverFast SMA crosses above slow SMA. Configurable fast/slow periods.Short-term trend detection
52-Week BreakoutBuys when price closes above its 52-week high on strong volume surge.Breakout trading, momentum stocks
EMA Confluence stocks + cryptoRequires multiple EMAs (8/21/50/200) to be aligned in the same direction. Scaled sizing by confluence count.High-conviction trend entries
Classic Chart Patterns stocks + cryptoDetects candlestick, reversal, and continuation patterns. EMA-200 trend filter guards entries; bear patterns trigger exits.Pattern-based swing trading
EMA Confluence and Classic Chart Patterns work on both stock and crypto accounts — they appear in the strategy list for whichever account type you select.
Enabling a Strategy
1
Open Bots & Strategies
Select a broker account in the left panel. Strategies available for that account's broker type appear on the right.
2
Toggle a strategy on
Flip the toggle next to a strategy. The engine picks it up on the next 60-second tick.
3
Adjust parameters
Expand a strategy to edit notional size, indicator periods, symbol lists, and more. Changes take effect immediately.
Stock strategies only run during US market hours (9:30 AM – 4:00 PM ET). Crypto strategies run 24/7. You can trigger a manual engine tick from the Dashboard at any time.
Crypto Trading
TradeBot connects to Binance for 24/7 crypto spot trading. All pairs trade against USDT (e.g., BTC/USDT, ETH/USDT). Paper and live accounts use separate API keys.
Crypto Strategies
StrategyHow it works
Crypto TrendEMA crossover (fast vs. slow). Buys on bullish crossover, sells on bearish crossover. Configurable fast/slow EMA periods.
Crypto RSI BounceBuys when RSI drops below the oversold threshold. Sells when RSI rises above the overbought threshold. Good for ranging crypto markets.
Crypto Mean ReversionBuys when price touches the lower Bollinger Band with oversold RSI (< 35). Exits when price returns to the SMA (middle band), or cuts the loss if price falls past the stop.
Crypto GridDivides a price range into levels. Buys near band bottoms, sells near band tops. Auto-detects range from recent price history. Trend SMA filter prevents buying in downtrends.
Getting Binance API Keys
1
Paper trading — Binance Demo
Go to demo.binance.com, create an account, and generate API keys under API Management. Demo keys only work with the demo exchange.
2
Live trading — Binance.com
Go to binance.com → API Management. Create a key with Spot & Margin Trading enabled. Disable withdrawals for safety.
3
Add the account in TradeBot
Go to Broker Accounts → Add Account → pick Binance from the Crypto tab → select Paper or Live → paste your keys.
Binance has a minimum order size of ~$10 USDT. TradeBot enforces this automatically — orders below $10 are skipped with a log entry explaining why.
Manual Orders
Place trades directly from the Positions & Orders page without waiting for a strategy signal.
Using the Order Ticket
1
Select an account
Use the account dropdown inside the order ticket to pick which broker account to trade on.
2
Choose Buy or Sell and enter a symbol
Type a ticker (e.g., AAPL or BTC/USDT) and click Quote to see the live bid/ask price.
3
Set quantity or dollar amount
Switch between Shares and Dollars. Enter your amount and click Place Order. A market order executes immediately.
Manual orders bypass the strategy engine and risk guards. They execute immediately as market orders.
Positions & Orders
Monitor all open holdings and order history. Use the account dropdown to switch between broker accounts.
Reading the Positions Table
ColumnWhat it means
SymbolTicker of the asset. Crypto shows the full pair (e.g., BTC/USDT).
SideLong = you own it. Short positions shown as negative qty.
QtyShares or crypto units held (can be fractional).
Avg EntryYour average purchase price.
Market ValueCurrent worth: Qty × Current Price.
P&LUnrealized profit or loss. Green = gain, red = loss.
Order Status Reference
StatusMeaning
FilledOrder fully executed.
OpenSubmitted but not yet filled.
PartialPartially filled; remainder still working.
CancelledCancelled by you or expired.
BlockedSignal generated but blocked by a risk guard.
Webhook Signals
TradeBot can receive trade signals from external tools like TradingView, custom scripts, or any HTTP client. Incoming signals go through the full risk engine before execution.
Setup
1
Get your webhook URL and token
Go to Settings → Webhook section. Copy your unique URL and secret token. Rotate the token anytime to invalidate old integrations.
2
Send a POST request
POST to /api/webhook/signal with header X-Webhook-Token: <token> and a JSON body.
Signal Format
FieldTypeDescription
symbolstringTicker symbol (e.g., AAPL or BTC/USDT)
sidestringbuy or sell
qtynumberShares or units (use this OR notional)
notionalnumberDollar amount to trade (use this OR qty)
account_idintegerOptional. Target a specific broker account by ID.
Webhook signals pass through all risk guards (kill switch, daily loss limit, PDT, etc.) before execution — exactly the same as strategy signals.
Risk Controls
Every signal — from strategies or webhooks — passes through 10 configurable risk guards before an order is placed. The first failing guard blocks the trade.
Guard Reference
GuardWhat it does
Kill SwitchMaster emergency stop. All automated trading halts immediately. Manual orders still work.
Daily Loss LimitHalts trading when today's P&L drops below N% of starting equity.
Weekly Loss LimitSame as daily but over a rolling 7-day window.
Consecutive LossesBlocks new trades after N losses in a row. Reset manually or automatically when a trade wins.
PDT ProtectionPrevents a 4th day-trade in a 5-day rolling window on accounts under $25,000 (stocks only).
Max PositionsCaps total open positions. Separate limits for stocks and crypto.
Symbol ExposurePrevents allocating more than N% of portfolio to a single symbol.
Max Orders/DayLimits total orders submitted in one trading day.
Trading HoursOnly allows orders between configured start/end times (ET). Crypto strategies are exempt — they run 24/7.
No-Trade ListSymbols on the blacklist are never traded regardless of signals.
Recommended starting settings: Max daily loss 2%, max positions 5, trading hours 9:30–15:45 ET, PDT protection on. These prevent the most common beginner mistakes.
Kill Switch
The kill switch is your emergency stop. One click halts all automated trading instantly.
Global vs. Per-Account

The global kill switch on the Risk page stops all accounts at once. Each broker account card also has its own per-account kill switch — useful when you want to pause one account while others continue trading.

How to activate

The kill switch card is at the top of the Risk page. Click the red Activate Kill Switch button. A red banner appears across all pages. Click Deactivate to resume trading.

The kill switch does not close existing positions. It only stops new orders. To close all positions, use the close-all button on the Positions page.
Take-Profit
Automatically close positions when they reach a target gain percentage, without needing a sell signal from the strategy.
How it works

After every engine tick, TradeBot scans all open positions. Any position whose unrealized gain equals or exceeds the take-profit threshold triggers an immediate market sell. Stock and crypto accounts each have their own configurable take-profit percentage.

Configuring Take-Profit

Go to Risk → scroll to the Take-Profit section. Set Stock Take-Profit % and Crypto Take-Profit % separately. Set to 0 to disable.

Take-profit exits bypass the strategy kill switch and normal risk checks — they're designed to lock in gains even when the engine is otherwise paused.
Price Alerts
Set price thresholds on any symbol. When the price crosses your target, you receive an instant notification via your configured channels.
Creating an Alert
1
Go to Settings → Price Alerts
Enter a symbol, choose "Above" or "Below", and set your target price.
2
Save the alert
Active alerts are checked every engine tick (60 seconds) using live quotes from your connected broker accounts.
3
Get notified
When triggered, alerts fire to all configured notification channels — Slack, Discord, Telegram, or email. The alert is marked as triggered and won't re-fire.
Performance Analytics
Track your bot's trading history, per-strategy stats, per-account P&L, and equity curve over time.
What's on the Performance page
WidgetDescription
Equity CurvePortfolio value over time. Toggle between 1W, 1M, 3M, 1Y views.
Strategy StatsPer-strategy: total signals, fills, blocks, win rate, and Sharpe ratio.
Attribution by AccountBreakdown of signals and fills per strategy × account combination.
Top SymbolsMost-traded symbols by signal count and fill rate.
Daily ActivityBar chart of signals per day over the last 30 days.
Interpreting the fill rate

Fill rate = filled signals ÷ total signals. Below 50% usually means risk guards are blocking most signals. Check Logs and filter by "Blocked" to see which guard triggers most.

Strategy Health
Strategy Health compares your live trading performance against your backtest benchmarks. It detects when a strategy is drifting from its expected behavior.
Drift Statuses
StatusMeaning
No DriftLive win rate is within normal range of the backtest benchmark.
Minor DriftLive performance is below backtest by a noticeable margin. Monitor closely.
Major DriftLive performance significantly underperforms the backtest. Consider pausing the strategy and re-tuning.
No BenchmarkNo backtest has been run for this strategy yet. Run one to enable drift monitoring.
Run a backtest for each strategy you enable. This establishes the benchmark used for drift detection and gives the AI Tuner a reference point for weekly optimization.
Backtesting
Test any of the 13 strategies against historical price data before risking real money. Saved runs persist for comparison.
Running a backtest
1
Choose a strategy and symbols
Select from the strategy dropdown. Enter ticker symbols separated by commas (e.g., AAPL, MSFT or BTC/USDT, ETH/USDT).
2
Set date range, capital, and costs
Set start/end dates (30 days minimum), initial capital, position size %, commission %, and slippage %.
3
Run and save
Click Run Backtest. Results show total return, win rate, max drawdown, Sharpe ratio, and a full trade log. Name the run to save it.
Key metrics explained
MetricMeaning
Total ReturnNet profit as a % of starting capital over the test period.
Win Rate% of trades that closed with a profit.
Max DrawdownLargest peak-to-trough decline. Over 20% is a warning sign.
Sharpe RatioRisk-adjusted return. Above 1.0 is acceptable; above 2.0 is excellent.
Avg Trade P&LAverage dollar profit/loss per completed trade.
Past performance does not predict future results. Backtests use daily bar data and assume unlimited liquidity. Real execution has wider spreads and slippage.
AI Tuning & Trade Explanations
TradeBot uses AI to explain every trade in plain English and to automatically tune strategy parameters based on live performance.
Trade Explanations

Every time a trade executes, TradeBot queues an AI explanation job. The AI reads the signal's reason (indicator values, crossover details, pattern names) and writes a 2–3 sentence explanation in plain English. Explanations appear in the Logs page next to each signal.

TradeBot supports two AI providers: Claude (Anthropic API) and Ollama (local, free, requires Ollama running on your machine). To use Claude, go to AI TuningAI Provider Settings, select the Claude (Anthropic) tab, and paste your API key (from console.anthropic.com) into the Anthropic API Key field. The key is encrypted and stored securely — you do not put it in .env.

Weekly Auto-Tuner

Every Sunday at 11 PM ET, the auto-tuner analyzes each strategy's live win rate and compares it to the backtest benchmark. It then proposes adjusted parameters (RSI thresholds, EMA periods, notional sizes, etc.) to improve performance. Results are logged in the AI Tuning page.

You can trigger a manual tuning run anytime from the AI Tuning page without waiting for Sunday. Reviewed suggestions can be applied with one click.
Logs & Signals
Every signal generated by every strategy is logged here with its outcome — filled, blocked, or errored.
Signal statuses
StatusMeaning
FilledOrder was submitted and executed by the broker.
BlockedA risk guard prevented the order. The reason column shows which guard triggered.
PendingSignal generated but order not yet confirmed. Usually resolves in seconds.
ErrorSomething went wrong placing the order. Check the reason column for details.
Filtering logs

Use the filter tabs to show All, Filled, Blocked, or Error signals. A strategy producing signals that are all "Blocked" indicates a risk configuration issue. A strategy producing no signals at all means the market conditions don't match the strategy criteria.

Notifications
Get alerted on trades, risk blocks, price alerts, and daily summaries via email, Telegram, Slack, or Discord.
Email (Gmail / SMTP)
1
Generate a Gmail App Password
Google Account → Security → 2-Step Verification → App passwords. Generate one for "TradeBot".
2
Fill in SMTP settings
Host: smtp.gmail.com  |  Port: 587  |  Username: your Gmail  |  Password: the App Password.
Telegram
1
Create a bot via BotFather
Message @BotFather in Telegram and run /newbot. Copy the token you receive.
2
Get your Chat ID and configure
Start a chat with your bot, then visit api.telegram.org/bot<TOKEN>/getUpdates to find your chat ID. Paste both into Settings.
Slack & Discord

Both use incoming webhooks. In Slack: Apps → Incoming Webhooks → Add to Slack → copy the webhook URL. In Discord: Server Settings → Integrations → Webhooks → New Webhook → copy URL. Paste into Settings → Notifications.

Frequently Asked Questions
Common questions and their answers.
Why is my strategy not placing any orders?

Check these in order: (1) Is the strategy enabled for a broker account on the Bots page? (2) Is a risk guard blocking it? Check Logs for "blocked" signals. (3) For stock strategies — is the market open? (4) For crypto strategies — is the Binance account decrypting correctly? Make sure your .env file has DB_SECRET_KEY set. (5) Does the symbol meet the strategy criteria? Use backtesting to verify.

Why is Binance not trading?

The most common causes: (1) DB_SECRET_KEY not loaded — the app couldn't decrypt your stored API keys. Make sure the key is in your .env file. (2) Demo vs. live key mismatch — paper accounts need keys from demo.binance.com, not live keys. (3) Insufficient balance — Binance requires a minimum of $10 per order. (4) Price in neutral zone — check Logs to confirm the strategy is actually generating signals.

What is PDT and how does it affect me?

The Pattern Day Trader (PDT) rule limits accounts under $25,000 to 3 day-trades in any rolling 5-business-day period. TradeBot's PDT guard blocks a 4th day-trade automatically. PDT does not apply to crypto (Binance) accounts.

Can I run TradeBot 24/7?

Yes — the server runs continuously. Stock strategies skip order placement outside configured trading hours. Crypto strategies run 24/7 with no market hours restriction.

Where is my data stored?

All data is stored locally in trading.db (SQLite). Nothing is sent to external servers except to your configured broker APIs. Backtest history, signals, settings, and encrypted credentials all live in this single file. Never delete or overwrite this file.

How do I reset consecutive losses?

Go to Risk and click Reset next to the Consecutive Losses field. This manually clears the counter so strategies can trade again.

Is my API key safe?

Yes — keys are encrypted with AES-256 (Fernet) before storage. The secret is never returned by any API endpoint. Use Alpaca's "Trading only" scope and disable Binance withdrawal permissions for added safety.

My broker keys suddenly show as "invalid" — what happened?

Your API keys are encrypted with the DB_SECRET_KEY stored in your .env file. If that key changes — for example, if .env is replaced, regenerated, or you re-run setup — the app can no longer decrypt your saved credentials, and they show as invalid even though the broker side is fine.

The fix depends on whether you still have the original key:

If you backed up the original DB_SECRET_KEY: restore that exact value into .env and restart. Your keys decrypt instantly — nothing to re-enter.

If the original key is lost: go to Broker Accounts and re-enter your API key/secret for each account. They re-encrypt under the current key and work again. Your accounts, settings, and history are all preserved — only the key/secret fields need re-pasting.

Back up your DB_SECRET_KEY the moment you finish setup (copy it somewhere safe, like a password manager). It is the one value that cannot be recovered if lost — and never re-run setup on a working install, as that can regenerate it.
Still stuck? Check the server console output for detailed error messages. The engine logs every skip, block, and error with a reason.