← Back to Dashboard

Sentinel AI Trading System — How It Works

An autonomous multi-agent trading signal system. Data flows from Yahoo Finance through 7 AI agents, an ensemble scorer, and a paper trading engine — all connected via RabbitMQ.

System Architecture

📡Yahoo Finance
🗄️TimescaleDB
🧠7 AI Agents
⚖️Ensemble Scorer
📬RabbitMQ
🤖Telegram Bot
📱You

Every 5 minutes, the data-pipeline fetches new 1h candles from Yahoo Finance for all watchlist symbols, stores them in TimescaleDB, then publishes a message to RabbitMQ. All agents consume that message, run their analysis, and publish results back. The orchestrator collects everything, runs the ensemble scorer, and paper-trades if conditions are met.

1. Data Pipeline

Role: Fetches market data from Yahoo Finance every 5 minutes and stores 1-hour candles in TimescaleDB.

ParameterValueRole
Fetch interval5 minutesHow often new data is pulled
Candle interval1hBar size for all analysis
Min rows per symbol50Minimum rows before agents analyze
Backfill days90Historical data fetched when adding a symbol

2. AI Agents

Each agent analyzes the same data from a different angle. They run in parallel and publish their findings to RabbitMQ.

TECHNICAL Technical Analysis Agent

What it does: Computes classic technical indicators — RSI, MACD, EMA crossovers — and generates buy/sell signals at extreme readings.

ParameterOldNewRole
RSI Oversold Tuned< 30< 25Only signal BUY when RSI is deeply oversold
RSI Overbought Tuned> 70> 75Only signal SELL when RSI is deeply overbought
MACD Strength Tuned0.70 fixed0.40 + hist%Scales with crossover magnitude (capped at 0.90)
EMA Cross Strength0.800.80Confidence for golden/death cross (rare event)
RSI Period1414Standard lookback for RSI calculation
MACD Parameters12/26/912/26/9Standard MACD fast/slow/signal EMAs

RSI formula: strength = (threshold - rsi) / threshold. At RSI=10: old strength=0.67, new=0.60. MACD strength now rewards larger crossovers.

RISK Risk Management Agent

What it does: Measures volatility via ATR (Average True Range), sets dynamic stop-loss and take-profit levels, and follows the SMA(50) trend direction.

ParameterOldNewRole
SL Multiple Tuned2.0× ATR2.0× ATRStop-loss = price ∓ 2 × ATR (unchanged)
TP Multiple Tuned3.0× ATR2.0× ATRTake-profit tightened from 3× to 2× ATR for more achievable targets on 1h candles
Volatility Warn4%4%Warns when ATR exceeds 4% of price
Trend FilterSMA(50)SMA(50)Direction follows 50-period moving average trend

Why TP was tightened: At 3× ATR on 1h candles, take-profits were 2-4% away — rarely hit before 2× ATR stop-losses. Now risk:reward is 1:1, more achievable.

ML Prediction Agent (XGBoost)

What it does: Trains an XGBoost classifier on 14 technical features (returns, volatility, volume ratios, RSI, MACD) to predict whether price will go up or down in the next 5 bars. Retrains automatically on each cycle.

ParameterValueRole
Features14Technical indicators used for training
Prediction horizon5 bars (5h)How far ahead the model predicts
Min samples100Minimum rows before training
Auto-retrainEvery cycleModel retrains on latest data each run

ML_PREDICTION weight in ensemble: 0.17 (was 0.15 — increased now that XGBoost crash is fixed).

NEWS News Sentiment Agent

What it does: Fetches latest news headlines from Yahoo Finance, scores them with VADER sentiment analysis, and signals when sentiment is strongly positive or negative.

ParameterOldNewRole
Sentiment Threshold Tuned±0.35±0.40Stricter threshold reduces VADER noise
Max Articles1010Number of headlines analyzed
Strength Cap0.950.95Max confidence for news signals

VADER scores range from -1 (very negative) to +1 (very positive). Threshold ±0.35 previously caught borderline sentiment.

VOLUME Volume Anomaly Agent

What it does: Detects abnormal volume spikes (>2 standard deviations from the 20-bar mean), which often precede significant price moves.

ParameterValueRole
Spike threshold> 2.0σStandard anomaly detection (95th percentile)
Lookback period20 barsWindow for mean/std calculation
Min rows30Minimum data required

MULTI-TF Multi-Timeframe Agent

What it does: Checks trend alignment across short (12h), medium (3 day), and long (10 day) timeframes. All 3 agreeing = high confidence signal.

ParameterValueRole
SHORT period12 bars~12 hours of 1h candles
MEDIUM period72 bars~3 days
LONG period240 bars~10 days
All-agree strength0.75Confidence when all 3 align
Majority strength0.45Confidence when 2/3 agree

S/R Support & Resistance Agent

What it does: Identifies swing highs/lows from the last 60 bars, then signals when price approaches these levels (potential bounce/rejection) or breaks through them (trend continuation).

ParameterValueRole
Lookback60 barsHow far back to find S/R levels
Proximity threshold1.5%How close price must be to a level before signaling
Breakout threshold0.5%Minimum breakthrough to classify as breakout

3. Ensemble Scorer

Role: Collects all agent signals and consolidates them into a single buy/sell/hold decision per symbol. Uses weighted voting with normalization.

Signal Weights

Signal TypeOld WeightNew WeightChangeWhy
RSI0.200.20Most influential technical indicator
MACD0.150.15Momentum confirmation
EMA_CROSS0.150.15Major trend change signal
ML_PREDICTION Tuned0.150.17+0.02XGBoost works now; more weight for ML
RISK Tuned0.050.12+0.07Best SL/TP provider deserves more voice
MULTI_TF0.150.15Trend confirmation across timeframes
VOLUME_ANOMALY0.100.10Volume spikes are reliable signals
S_R_LEVEL0.100.10Support/resistance proximity
NEWS_SENTIMENT Tuned0.100.08-0.02VADER can be noisy; reduced weight slightly

Scoring Parameters

ParameterOldNewRole
CONFIDENCE_THRESHOLD0.250.25Minimum score to emit a consolidated signal
CONFLICT_MARGIN Tuned0.100.15Tighter — need stronger consensus before signaling

The scorer normalizes by the sum of weights that actually fired, so only the relative proportions matter. Increasing RISK from 0.05→0.12 makes it 2.4× more influential when it fires.

4. Paper Trading Engine

Role: Manages a virtual $100K portfolio. Opens LONG positions on BUY consolidated signals, closes them on SELL signals. Uses risk-based position sizing.

Portfolio Parameters

ParameterValueRole
Initial Capital$100,000Starting portfolio value
Max Concurrent5Maximum open positions at once
Max Drawdown15%Circuit breaker — stops trading if P&L drops this much
Risk Per Trade1% of equityRisk-based sizing: loss if stopped out = 1% of portfolio
Fallback Notional$1,000Used when no stop-loss is available for sizing

Position Sizing Logic

When a BUY signal arrives with a stop-loss level, the engine calculates:

quantity = (equity × risk_per_trade_pct) / |entry - stop_loss|

This means every trade risks exactly 1% of current equity. If equity = $100K and SL is $5 away, position = $1,000 / $5 = 200 shares ($20,000 notional).

5. Telegram Notifications

Role: Listens to RabbitMQ for consolidated signals and sends formatted Telegram messages. Also handles user commands.

CommandAction
/signalsShow latest signals for all symbols
/watchlistShow current watchlist
/pnlShow portfolio P&L and open positions
/add SYMBOLAdd a symbol to watchlist
/remove SYMBOLRemove a symbol from watchlist
/backtest SYMBOLRun a backtest for a symbol

Duplicate signals are suppressed for 60 minutes via fingerprint-based deduplication to avoid message spam.

6. Data Flow Summary

Every 5 minutes:
  1. Data Pipeline fetches 1h candles from Yahoo Finance
  2. Writes to TimescaleDB (stock_data table)
  3. Publishes "data.raw" message to RabbitMQ
  4. All 7 agents consume the message in parallel:
     ┌─ Technical (RSI, MACD, EMA)
     ├─ Risk (ATR, SL/TP, SMA trend)
     ├─ Prediction (XGBoost — 14 features)
     ├─ News (VADER sentiment)
     ├─ Volume (z-score anomaly)
     ├─ Multi-TF (3 timeframes)
     └─ S/R Level (support/resistance)
  5. Each agent publishes signals to RabbitMQ
  6. Orchestrator collects all signals
  7. Ensemble Scorer consolidates into buy/sell/hold
  8. Paper Trader executes (opens/closes positions)
  9. Telegram Bot sends notification (if not duplicate)

7. Summary of All Tuning Changes

#FileChangeImpact
1technical_agent.pyRSI thresholds: 30→25 (oversold), 70→75 (overbought)Fewer but more extreme RSI signals — less noise, higher quality
2technical_agent.pyMACD strength: fixed 0.7 → 0.4 + hist% (capped 0.9)Rewards genuine large crossovers; weak crossovers get lower confidence
3risk_agent.pyTP_ATR_MULTIPLE: 3.0 → 2.0Tighter take-profits — more achievable on 1h candles, better risk:reward
4signal_scorer.pyRISK weight: 0.05 → 0.12Risk agent's trend filter + ATR levels now have more ensemble influence
5signal_scorer.pyML_PREDICTION weight: 0.15 → 0.17XGBoost is fixed, deserves slightly more weight
6signal_scorer.pyNEWS_SENTIMENT weight: 0.10 → 0.08VADER can be noisy, reduced slightly
7signal_scorer.pyCONFLICT_MARGIN: 0.10 → 0.15Stronger consensus needed — reduces weak conflicting signals
8news_agent.pySentiment threshold: ±0.35 → ±0.40Fewer but more reliable news signals

After this page was created, run docker compose up -d --build ai-agents to deploy the tuned parameters.

8. Key Metrics to Watch

After tuning, monitor these metrics to evaluate whether the changes helped:

← Back to Dashboard