XAUUSD Pattern Scanner
Complete encyclopedia for the XAUUSD Pattern Scanner — a standalone 24/7 MT5-connected scanner covering 70+ pattern detectors, ICT killzones, Fibonacci OTE, HTF bias, confluence scoring, SQLite database, backtest engine, and scalping guide.
01 — Overview
The XAUUSD Pattern Scanner is a real-time technical analysis engine that connects to your MetaTrader 5 terminal and continuously scans XAUUSD (Gold) across four timeframes simultaneously. It detects over 70 patterns, calculates a multi-factor confluence score, grades setups A/B/C, and presents only the highest-probability opportunities — eliminating the noise of contradictory BUY/SELL signals.
What it does in one sentence
Every 8 seconds it scans M1, M5, M15, and H1, runs 15 different detection engines, scores the results with a 14-category confluence system, and shows you only the setups where enough independent evidence agrees — with entry, stop loss, take profit, R:R, and lot size already calculated.
Architecture summary
| Component | File | Purpose |
|---|---|---|
| Web Server | server.py | Flask server, scanner loop, all API endpoints |
| Pattern Engine | patterns.py | All 70+ detectors, confluence scorer, scan_all |
| MT5 Feed | mt5_feed.py | MT5 connection, OHLCV data, tick feed, account info |
| Database | database.py | SQLite storage, outcome tracking, JSON export |
| Backtest Engine | backtest.py | Walk-forward simulation, Monte Carlo, regime detection |
| Web Dashboard | dashboard.html | Main UI — chart, signals, setups, backtest tab |
| Backtest Page | backtest.html | Standalone backtest analytics page |
| GUI Dashboard | gui_dashboard.py | Tkinter desktop window (scanner.py mode) |
| Terminal Dashboard | dashboard.py | ANSI terminal display (scanner.py mode) |
| Alerts | alerts.py | Sound, desktop toast, console, log file |
| Scanner Loop | scanner.py | GUI mode entry point |
02 — Quick Start
Prerequisites
- Windows PC (MT5 is Windows-only)
- MetaTrader 5 installed and logged into your broker
- XAUUSD visible in MT5 Market Watch
- Python 3.10 or higher installed
Step-by-step setup
- 1Open MetaTrader 5 and log into your broker account
- 2Press Ctrl+M to open Market Watch. Right-click → Show All to find XAUUSD
- 3Go to Tools → Options → Expert Advisors → check Allow algorithmic trading
- 4Double-click START.bat in the scanner folder
- 5Browser opens automatically at
http://localhost:5000 - 6Wait 10–30 seconds for MT5 to connect and first scan to complete
"np2 is not defined" — Delete the
__pycache__ folder and restart."Could not select XAUUSD" — XAUUSD is not in Market Watch. Right-click MT5 Market Watch → Show All → find XAUUSD → double-click.
Wrong terminal connected — If you have multiple MT5 installations, the scanner auto-detects your broker terminal. Make sure only your broker's MT5 is open.
Two modes available
| Mode | How to start | Best for |
|---|---|---|
| Web Dashboard | START.bat | Main use — full UI in browser |
| GUI Window | START_SCANNER.bat | Desktop tkinter window |
03 — File Structure
xauusd_scanner/
├── server.py ← Main entry point — run this
├── patterns.py ← All 70+ pattern detectors (1895 lines)
├── database.py ← SQLite storage engine
├── mt5_feed.py ← MT5 connection and data feed
├── backtest.py ← Historical backtest engine
├── alerts.py ← Sound, desktop, log alerts
├── scanner.py ← GUI mode entry point
├── dashboard.py ← Terminal (ANSI) dashboard
├── gui_dashboard.py ← Tkinter GUI dashboard
├── dashboard.html ← Web UI (main interface)
├── backtest.html ← Standalone backtest analytics
├── DOCS.html ← This documentation file
├── requirements.txt ← Python dependencies
├── START.bat ← Web mode launcher
├── START_SCANNER.bat ← GUI mode launcher
├── data/ ← Auto-created
│ ├── scanner.db ← SQLite database
│ ├── setups_export.json ← Auto-exported setups
│ ├── signals_export.json← Auto-exported signals
│ └── analytics_export.json
└── logs/ ← Auto-created
└── signals_YYYYMMDD.log
04 — Requirements
| Package | Version | Purpose |
|---|---|---|
| MetaTrader5 | ≥5.0.45 | MT5 Python bridge — data feed and account info |
| pandas | ≥2.0.0 | OHLCV DataFrame manipulation |
| numpy | ≥1.24.0 | Numerical calculations in all detectors |
| scipy | ≥1.10.0 | argrelextrema for swing high/low detection |
| flask | ≥3.0.0 | Web server for dashboard |
| flask-cors | ≥4.0.0 | Cross-origin headers |
| win10toast | ≥0.9 | Windows desktop notifications (optional) |
Install all at once: pip install -r requirements.txt
05 — Dashboard Layout
The web dashboard at http://localhost:5000 is divided into three columns plus a top bar.
| Zone | Location | Contents |
|---|---|---|
| Top Bar | Full width | Live price, bid/ask, spread, session, killzone timer, scan count, connection status |
| Strategy Filter Bar | Below top bar | Filter buttons: All Signals, S/R Flip, Breakout, EMA Cont., Stop-Hunt, SMC/ICT, BW, Volume Intel, Killzones, Fibonacci, Win Probability |
| Left Column | 286px wide | Market Bias, TF grid, Best Trade card, signal tabs, signal list |
| Centre Column | Flexible | Candlestick chart with EMA 21/50/100 and volume, pattern type pills at bottom |
| Right Column | 340px wide | Account info, Position Size Calculator, 4 tabs: ⚡ Setups / 📊 Backtest / Active / History |
| Status Bar | Bottom | Connection status, bias, day/time, log file path |
Killzone Timer (top bar)
Shows the countdown to the next ICT Killzone. 🟢 LON 45m 12s = London Killzone active with 45 minutes remaining. ⏳ NY 22m = NY Killzone opens in 22 minutes. 🔴 London in 3h40m = no active killzone.
06 — Signal List (Left Column)
The signal list shows all patterns detected in the current scan, filtered by your selected timeframe tab and strategy filter.
Reading a signal card
┌─ BUY ─── M1 ─── Triple Bottom ──────────────── 86% ─┐ │ E:$4835.20 SL:$4830.10 TP:$4852.80 1:3.5 R:R │ └─────────────────────────────────────────────────────┘
| Field | Meaning |
|---|---|
| BUY / SELL / WATCH | Direction. WATCH = neutral / informational pattern |
| M1 / M5 / M15 / H1 | Timeframe where the pattern was detected |
| Pattern name | Exact pattern. ★ prefix = Playbook Strategy (higher priority) |
| Confidence % | 0–100%. Green ≥80%, Gold ≥70%, Red <70% |
| E: (Entry) | Suggested entry price (current close at time of detection) |
| SL: (Stop Loss) | ATR-based stop loss (1.5× ATR from entry) |
| TP: (Take Profit) | ATR-based target (3.0× ATR minimum) |
| R:R | Reward-to-risk ratio. Minimum 1.5, best setups ≥1:3 |
server.py.
07 — Best Setups Panel (⚡ Tab)
The Best Setups panel is the core feature that solves the "contradictory signals" problem. Instead of showing every BUY and SELL simultaneously, it uses a 14-category confluence engine to find setups where multiple independent signal types agree on one direction.
How a setup qualifies
- One timeframe has >57% of confidence mass pointing one direction
- At least 3 independent confluence categories agree
- Best signal has R:R ≥ 1.5 (filter adjustable)
- Setup is not expired (adjustable timer, default 30 min)
Setup card anatomy
┌── BUY London KZ — Swept Asian Low M5 H1✓ Grade A 2m ──┐ │ ⚠ Wednesday — FOMC risk. Reduce size. │ │ Confluence: ●●●●●●○○○○ 6/14 78% bull │ │ Strategy · Killzone · Fibonacci 📍 At Support (3 pip) │ │ E: $4835.20 SL: $4830.10 TP: $4852.80 1:3.5 R:R │ │ 📊 Similar: 62% WR · 18 trades · +12.4R total │ └─────────────────────────────────────────────────────────────┘
| Element | Meaning |
|---|---|
| H1 ✓ | H1 timeframe bias matches this setup's direction |
| H1 ✗ | H1 bias opposes this setup — trade with caution |
| Grade A | Score ≥6/14 AND confidence ≥82% — highest probability |
| Grade B | Score ≥4/14 AND confidence ≥75% — good setup |
| Grade C | Score ≥3/14 — valid but lower conviction |
| 2m ago / NEW | Expiry timer — how long ago this setup first fired |
| ⚠ News warning | Major economic event within 30 minutes |
| 📍 At S/R | Entry price is within 8 pips of a key level |
| 📊 Replay stats | Historical performance of this strategy from your backtest DB |
Filter controls
| Control | Default | Effect |
|---|---|---|
| R:R ≥ 1:3 pill | ON | Only show setups with reward:risk ≥ 1:3 |
| Conf ≥ 75% pill | ON | Only show setups with confidence ≥ 75% |
| Session pill | ON | Hide setups in Asian / dead zone sessions |
| Hide after slider | 30 min | Auto-expire setups older than N minutes |
| H1→M5 confirm | OFF | When ON: blocks M1/M5 setups that contradict H1 bias |
08 — Backtest Tab (📊)
The Backtest tab shows real performance data from YOUR live trading sessions. Unlike the standalone /backtest page which runs a simulation on MT5 history, this tab reads from the local SQLite database where every Best Setup is automatically saved and its outcome tracked.
How outcomes are determined
- MT5 bars (primary): After a setup fires, the scanner checks subsequent OHLCV bars on that timeframe. If the High hits TP or Low hits SL → resolved as win/loss
- Live ticks (fallback): If MT5 data isn't available, live price ticks are used instead
- Expired (24h): Setups that hit neither TP nor SL within 24 hours are marked expired
What the tab shows
| Section | Contents |
|---|---|
| DB Status Pills | Total setups stored, wins, losses, pending, all signals count |
| Summary Cards | Win Rate, Net R, Profit Factor, Expectancy, Max Drawdown |
| Equity Curve | Cumulative R earned over time from resolved setups |
| By Grade | Win rate breakdown for Grade A, B, C separately |
| By Timeframe | Win rate for M1, M5, M15, H1 |
| Strategy Breakdown | Each strategy with win rate bar, total R, EDGE/NEUTRAL/AVOID verdict |
| Recent Trades | Last 15 resolved setups with direction, grade, outcome, P&L in R |
Use the ↺ Refresh button to update. Use ⬇ JSON to export all data to data/ folder. Use 🗑 to clear history and start fresh.
09 — Position Size Calculator
Located in the right panel above the tabs. Click any signal in the signal list or setup panel to auto-fill entry and SL.
Formula used
Risk Amount ($) = Account Balance × Risk % SL Distance (pips) = |Entry - Stop Loss| Lot Size = Risk Amount ÷ (SL Pips × Pip Value per Lot)
| Input | Default | Notes |
|---|---|---|
| Risk % | 1.0% | Percentage of account balance to risk on one trade |
| Pip Value ($) | $10 | Dollar value per pip per standard lot. Check with your broker — MavenTrade is typically $10 for XAUUSD |
10 — Killzone Timer
The live countdown in the top bar shows which ICT Killzone is active or approaching. Killzones are the specific hours of day when institutional order flow is highest and the highest-probability setups occur.
| Killzone | UTC Time | Timer Color | What to expect |
|---|---|---|---|
| London Killzone | 07:00–09:00 | Green | Asian range sweep + reversal. Best entry of the day. |
| NY Killzone | 12:00–14:00 | Green | London continuation or NY reversal. Second best window. |
| Pre-London Alert | 06:30–07:00 | Gold | Prepare: note Asian range high and low now |
| Pre-NY Alert | 11:30–12:00 | Gold | Assess London direction. Ready for NY continuation |
| Outside KZ | All other times | Red/Muted | Countdown to next killzone. Lower probability period. |
11 — Candlestick Patterns
Detected by detect_candles() in patterns.py. Applied to every timeframe on every scan. All use ATR-based SL/TP.
12 — Chart Patterns
Detected by detect_chart() using scipy.signal.argrelextrema to find swing highs and lows, then checking geometric relationships.
| Pattern | Direction | Confidence | Description |
|---|---|---|---|
| Head & Shoulders | Bearish | 82–87% | Three peaks, middle highest. Neckline break confirms. Classic reversal. |
| Inverse H&S | Bullish | 82–87% | Three troughs, middle lowest. Strongest bullish reversal chart pattern. |
| Double Top | Bearish | 83% | Two equal peaks within 0.5% tolerance. Bearish reversal on neckline break. |
| Double Bottom | Bullish | 83% | Two equal troughs. Bullish reversal on neckline break above. |
| Triple Top | Bearish | 86% | Three equal peaks. Very strong resistance. Highest chart pattern confidence. |
| Triple Bottom | Bullish | 86% | Three equal troughs. Very strong support. Breakout imminent. |
| Ascending Triangle | Bullish | 77% | Flat resistance + rising support. Bullish breakout probable. |
| Descending Triangle | Bearish | 77% | Falling resistance + flat support. Bearish breakdown probable. |
| Symmetrical Triangle | Neutral | 70% | Converging trendlines. Big move imminent — direction needs volume confirmation. |
| Rising Wedge | Bearish | 74% | Both lines rising but converging. Bearish reversal — sell break below lower line. |
| Falling Wedge | Bullish | 74% | Both lines falling but converging. Bullish reversal — buy break above upper line. |
| Bull Flag | Bullish | 77% | Strong bull pole + tight consolidation (<0.3% range). Continuation expected. |
| Bear Flag | Bearish | 77% | Strong bear pole + tight consolidation. Continuation expected. |
| Cup & Handle | Bullish | 80% | Rounded base + handle pullback. High win-rate bullish continuation. |
13 — SMC / ICT Concepts
Detected by detect_smc(). Smart Money Concepts and ICT methodology — the most powerful patterns in the scanner.
| Concept | Direction | Confidence | Description |
|---|---|---|---|
| CHoCH Bullish | Bullish | 87% | Change of Character — bearish structure broken. Highest conviction reversal signal. Wait for OB/FVG retest. |
| CHoCH Bearish | Bearish | 87% | Bullish structure broken → bearish reversal. Maximum conviction on H4. |
| BOS Bullish | Bullish | 78% | Break of Structure — price broke swing high. Wait for 61.8–79% OTE pullback to enter long. |
| BOS Bearish | Bearish | 78% | Price broke swing low. Watch for OTE pullback to enter short. |
| Bullish Market Structure | Bullish | 72% | Higher Highs + Higher Lows confirmed. Only buy dips to OB/FVG/OTE zones. |
| Bearish Market Structure | Bearish | 72% | Lower Highs + Lower Lows. Only sell rallies to OB/FVG/OTE zones. |
| Bullish Order Block | Bullish | 59–83% | Last bearish candle before bull displacement. FRESH = 83%, tested once = 71%, twice = 59%. |
| Bearish Order Block | Bearish | 59–83% | Last bullish candle before bear displacement. Confidence degrades with each retest. |
| Bull FVG | Bullish | 66–81% | Fair Value Gap — price imbalance that acts as magnet. Unfilled = 81%, partial = 66%. |
| Bear FVG | Bearish | 66–81% | Bearish imbalance. Price returns to fill the gap. |
| In Bull OTE Zone | Bullish | 84% | Optimal Trade Entry — price at 61.8–79% Fibonacci of swing. Prime long entry after BOS. |
| In Bear OTE Zone | Bearish | 84% | Price at 61.8–79% retracement of bearish swing. Prime short entry after BOS. |
| BSL Sweep Confirmed | Bearish | 89% | Wick above equal highs, body closed below. Stop hunt complete. Highest confidence signal. |
| SSL Sweep Confirmed | Bullish | 89% | Wick below equal lows, body closed above. Stop hunt complete. Enter immediately. |
| Premium Zone | Bearish | 68% | Price above 50% equilibrium. Institutional sell bias. |
| Discount Zone | Bullish | 68% | Price below 50% equilibrium. Institutional buy bias. |
14 — Technical Indicators
Detected by detect_indicators(). All calculated on the raw OHLCV data — no external libraries needed.
| Indicator | Signal | Confidence | Logic |
|---|---|---|---|
| EMA Bullish Stack | Bullish | 77% | EMA8 > EMA21 > EMA50 > EMA200. Perfect uptrend alignment. |
| EMA Bearish Stack | Bearish | 77% | EMA8 < EMA21 < EMA50 < EMA200. Perfect downtrend alignment. |
| EMA 8/21 Golden Cross | Bullish | 78% | EMA8 crossed above EMA21. Short-term bullish momentum. |
| EMA 8/21 Death Cross | Bearish | 78% | EMA8 crossed below EMA21. Short-term bearish momentum. |
| RSI Oversold (<30) | Bullish | 72% | RSI below 30. Statistically oversold. Bounce likely. |
| RSI Overbought (>70) | Bearish | 72% | RSI above 70. Statistically overbought. Pullback likely. |
| RSI Bullish Divergence | Bullish | 81% | Price lower low but RSI higher low. Hidden buying pressure. |
| RSI Bearish Divergence | Bearish | 81% | Price higher high but RSI lower high. Hidden selling pressure. |
| MACD Bullish Crossover | Bullish | 75% | MACD histogram crossed above zero. Upward momentum confirmed. |
| MACD Bearish Crossover | Bearish | 75% | MACD histogram crossed below zero. Downward momentum confirmed. |
| BB Lower Band Touch | Bullish | 69% | Price below lower Bollinger Band. Statistically oversold. |
| BB Upper Band Touch | Bearish | 69% | Price above upper Bollinger Band. Statistically overbought. |
| BB Squeeze | Neutral | 67% | Bandwidth <1.5%. Extreme compression — big move imminent. |
| Stoch Bullish Cross | Bullish | 76% | %K crossed above %D in oversold zone (<20). Strong buy confirmation. |
| Stoch Bearish Cross | Bearish | 76% | %K crossed below %D in overbought zone (>80). Strong sell confirmation. |
| CCI Oversold | Bullish | 68% | CCI <-100. Commodity Channel Index oversold zone. |
| CCI Overbought | Bearish | 68% | CCI >100. Overbought reversal zone. |
| ADX Strong Trend | Bull/Bear | 73% | ADX >25. Confirmed trend. +DI vs -DI determines direction. |
| Ichimoku TK Cross Bull | Bullish | 79% | Tenkan crossed above Kijun. Bullish. Stronger above cloud. |
| Ichimoku TK Cross Bear | Bearish | 79% | Tenkan crossed below Kijun. Bearish. Stronger below cloud. |
| Parabolic SAR | Bull/Bear | 67% | SAR below price = uptrend. Use as trailing stop reference. |
15 — Support & Resistance
Detected by detect_sr(). Automatically finds and merges swing highs/lows, plus gold-specific psychological round numbers.
| Type | Logic | Confidence |
|---|---|---|
| Resistance levels | Swing highs within 5% of current price, merged within 0.2% tolerance | 60–85% (closer = higher) |
| Support levels | Swing lows within 5% of current price, merged within 0.2% tolerance | 60–85% (closer = higher) |
| Round Number $100 | Within 1.5% of $100 increments ($4800, $4900…) | 72% |
| Round Number $50 | Within 1.5% of $50 increments ($4850, $4950…) | 72% |
| Round Number $25 | Within 1.5% of $25 increments ($4875, $4825…) | 72% |
16 — Volume Intelligence
Detected by detect_volume(). MT5 provides tick volume which correlates well with real volume for direction confirmation.
| Signal | Direction | Confidence | Logic |
|---|---|---|---|
| OBV Bullish Divergence | Bullish | 83% | Price falling but OBV rising. Institutional accumulation — smart money buying the dip. |
| OBV Bearish Divergence | Bearish | 83% | Price rising but OBV falling. Institutional distribution — smart money selling into rally. |
| Volume Spike (≥2σ) | Bull/Bear | 60–89% | Volume ≥2 standard deviations above 20-bar average. Direction from price move at time of spike. |
| VWAP Position | Bull/Bear | 67% | Price above VWAP = institutional long bias. Below = institutional short bias. |
| VWAP Extended | Reversal | 68% | Price >1% from VWAP — mean reversion likely. VWAP acts as magnet. |
| MFI Oversold (<20) | Bullish | 75% | Money Flow Index oversold. Volume-weighted — stronger signal than RSI alone. |
| MFI Overbought (>80) | Bearish | 75% | Volume-weighted overbought. High probability pullback. |
| MFI Bullish Divergence | Bullish | 80% | Price down but MFI rising. Volume not confirming drop. |
| MFI Bearish Divergence | Bearish | 80% | Price up but MFI falling. Volume not confirming rally. |
17 — Bill Williams Indicators
Detected by detect_bill_williams(). Bill Williams' market structure theory — Alligator, Awesome Oscillator, Fractals, Market Facilitation Index.
| Signal | Confidence | Meaning |
|---|---|---|
| Alligator EATING UP | 82% | Lips > Teeth > Jaw and price above Lips. Strong uptrend. Enter longs on pullbacks to Lips. |
| Alligator EATING DOWN | 82% | Lips < Teeth < Jaw and price below Lips. Strong downtrend. Enter shorts on rallies to Lips. |
| Alligator SLEEPING | 60% | Lines intertwined. Ranging market — no edge. Wait for separation. |
| AO Zero Line Cross UP | 77% | Awesome Oscillator crossed above zero. Bullish momentum confirmed. |
| AO Zero Line Cross DOWN | 77% | AO crossed below zero. Bearish momentum confirmed. |
| BW MFI Squat | 75% | Volume rising but range falling. Battle at key level — BREAKOUT IMMINENT. |
| Bear/Bull Fractal | 63% | Swing high/low fractal. Marks nearest liquidity target above/below price. |
18 — ICT Killzones
Detected by detect_killzones(). The most important concept from ICT (Inner Circle Trader) methodology — specific time windows when institutional order flow dominates and the highest-probability setups occur.
London Killzone (07:00–09:00 UTC)
| Signal | Direction | Confidence | Trigger |
|---|---|---|---|
| London KZ — Swept Asian High | Bearish | 88% | Price swept Asian session high, body closed back below. Reversal down expected. |
| London KZ — Swept Asian Low | Bullish | 88% | Price swept Asian session low, body closed back above. Reversal up expected. |
| London KZ — Watch for BSL Sweep | Bearish | 72% | Price in upper half of Asian range. London will likely sweep the high first. |
| London KZ — Watch for SSL Sweep | Bullish | 72% | Price in lower half. London likely sweeps the low first, then reverses up. |
New York Killzone (12:00–14:00 UTC)
| Signal | Direction | Confidence | Trigger |
|---|---|---|---|
| NY KZ — London Continuation Long | Bullish | 80% | London was bullish. NY open continuing same direction. Buy dips to London midpoint. |
| NY KZ — London Continuation Short | Bearish | 80% | London was bearish. NY continuing downward. Sell rallies to London midpoint. |
| NY KZ — Potential London Reversal | Neutral | 68% | Price moving against London direction. Wait for strong confirmation before entry. |
19 — Fibonacci OTE (Optimal Trade Entry)
Detected by detect_fibonacci(). ICT's most precise entry technique — enter at the 61.8%–78.6% retracement of a clear impulse move.
Why 61.8%–78.6% is special
The golden ratio (61.8%) is where institutional orders are placed for pullback entries. 78.6% is the deepest acceptable retracement before the move is considered failed. Between these levels: highest probability, best R:R, tightest SL.
| Zone | Direction | Confidence | When to use |
|---|---|---|---|
| Golden Zone (61.8–78.6%) | Bull/Bear | 87% | After any clear impulse move ≥15 pips. ICT's OTE — highest-probability entry on gold. |
| 38.2–61.8% Zone | Bull/Bear | 74% | Shallow pullback in strong trend. Enter here if momentum is very strong. |
| Deep Retracement (>78.6%) | Bull/Bear | 65% | Last-chance entry zone before swing low/high. Must have OB or CHoCH confirmation. |
20 — HTF Daily Bias
Detected by detect_htf_bias() on H1, H4, and D1 only. Reads higher timeframe direction before you trade lower timeframes. ICT's #1 rule: trade WITH the higher timeframe bias, never against it.
| Signal | Confidence | Logic |
|---|---|---|
| HTF Bias: BULLISH [H1] | 74–85% | EMA alignment bullish AND/OR swing structure shows HH+HL. Only take BUY setups on M1/M5/M15. |
| HTF Bias: BEARISH [H1] | 74–85% | EMA alignment bearish AND/OR LH+LL structure. Only take SELL setups on lower TFs. |
| HTF Bias: MIXED [H1] | 50% | No clear direction. Use tight SL or wait for clearer bias. |
Strong bias (85%) = both EMA alignment AND swing structure agree. Moderate (74%) = only one confirms. Use the H1→M5 confirm toggle in the Setups panel to automatically block any setup that contradicts the H1 bias.
21 — Win Probability Score
Detected by detect_probability_score(). Aggregates all available factors into a single composite score and grade.
Scoring factors
| Factor | Points | Condition |
|---|---|---|
| In Killzone | +2 | Current time is in London KZ or NY KZ |
| Day of week — Tuesday | +3 | Best delivery day (Judas Swing day) |
| Day of week — Thursday | +2 | Second best delivery day |
| Day of week — Wednesday | +1 | News risk but still tradeable |
| High-confidence pattern ≥85% | +2 each | Counts each qualifying pattern |
| Good-confidence pattern ≥75% | +1 each | Counts each qualifying pattern |
| EMA bullish alignment | +2 | Price > EMA21 > EMA50 |
| EMA bearish alignment | +2 | Price < EMA21 < EMA50 |
| RSI oversold (<40) | +2 | Favours bullish setups |
| RSI overbought (>60) | +2 | Favours bearish setups |
| Score | Grade | Action |
|---|---|---|
| ≥10 (bull > bear +3) | A | HIGH PROBABILITY — trade at full size in killzone |
| 6–9 (bull > bear +3) | B | GOOD PROBABILITY — trade at normal size |
| Bull ≈ Bear | — | NEUTRAL — wait for more confluence |
22 — S/R Flip Retest (Playbook Strategy 1)
Entry rules
- Level must have been tested ≥2 times before the break
- Break must be confirmed with 15+ pip expansion
- Enter on rejection candle (long wick back at the level) — NOT on the break
- SL: 3–5 pips beyond the level
- Target: R:R 1:3 minimum
23 — Consolidation Breakout (Playbook Strategy 2)
Target calculation
Project the range height from the breakout level. If range was 30 pips and broke upward at $4850, target = $4850 + $30 = $4880.
24 — EMA Trend Pullback (Playbook Strategy 3)
| EMA Touched | Confidence | R:R | Notes |
|---|---|---|---|
| 100 EMA | 83% | 1:3.6 | Deep pullback — best R:R, highest conviction entry |
| 50 EMA | 81% | 1:3.1 | Primary entry zone — most common setup |
| 21 EMA | 76% | 1:2.5 | Minor pullback — only in very strong trends |
25 — Stop-Hunt Reversal (Playbook Strategy 4)
Identification rules
- Must have ≥2 equal highs (Buy-Side Liquidity) or equal lows (Sell-Side Liquidity)
- Spike must be 5–50 pips beyond the pool level (not too small, not news-driven)
- Wick above/below but body closed back inside the range
- Enter on close of first reversal candle after the spike — act within 1–3 minutes
- SL above wick extreme + 3–5 pips (very tight)
26 — Scalping with the Scanner
The scalper's daily routine with this scanner
- 6:30 AM UTC — Open scanner. Note Asian range H/L shown in Killzone signals. This is today's liquidity map.
- 6:55 AM UTC — Check H1 HTF Bias. If bullish → only take BUY setups today. If bearish → only SELL.
- 7:00–7:20 AM UTC — London KZ opens. WATCH for the Asian range sweep signal (88% confidence). This is your best trade of the day.
- 7:20–9:00 AM UTC — If sweep happened, trade continuation. Enable H1→M5 confirm toggle. Look for Grade A on M5.
- 9:00–12:00 AM UTC — Avoid. Low-probability window. Review signals, check backtest tab.
- 11:30 AM UTC — Pre-NY alert fires. Check London direction. Decide: continuation or reversal?
- 12:00–14:00 UTC — NY KZ. Second opportunity. If London was strong, continuation trade. If London stalled, reversal.
- After 14:00 UTC — Done for the day. No more entries.
27 — Scalp Setup A: Killzone Asian Sweep
Best setup in the scanner. Fires at 07:00–08:30 UTC. Win rate in ideal conditions: ~65–72%.
- 1Wait for London KZ to open (07:00 UTC). KZ timer turns green. Pre-London signal fires at 06:30.
- 2Watch for the sweep signal. Scanner fires "London KZ — Swept Asian High" (Bearish 88%) or "Swept Asian Low" (Bullish 88%). Do NOT enter yet.
- 3Confirm the reversal candle on M5. You need a strong candle closing back inside the Asian range — bullish engulfing / pin bar / marubozu in the reversal direction.
- 4Check confluence. Scanner should show ≥3 categories agreeing. Look for Grade A or B in the Setups panel. H1 ✓ badge is ideal.
- 5Enter at close of confirmation candle. Use Position Size Calculator: 1% risk. SL = beyond the sweep wick + 5 pips.
- 6TP1 = 50% at 1:1.5 R:R. Remove half position. Move SL to breakeven. Let TP2 run to 1:3.
28 — Scalp Setup B: Fibonacci Golden Zone Bounce
Works all day but best in killzones. Fires after any clean impulse move. Win rate: ~60–68%.
- 1Wait for a clear impulse move — at least 20–30 pips in one direction with strong candles. This is the "swing" that Fibonacci is measured from.
- 2Scanner fires Fib Golden Zone signal (87% confidence) when price retraces to the 61.8–78.6% zone. This is the entry window — price is in the right area but do not enter yet.
- 3Look for an Order Block or FVG in the same zone. If the scanner shows "Bullish Order Block" + "Fib Golden Zone BUY" on the same M5 candle area — this is ICT's triple confluence entry.
- 4Enter on confirmation candle. Long lower wick closing bullish (for buys). Enter at close. SL: 5 pips below the Fib 78.6% level.
- 5Target: Return to swing high (1:2.5–1:4 R:R). Trail with EMA21.
29 — Scalp Setup C: Order Block Retest
High-precision entry. Fires throughout the day. Win rate when fresh OB: ~63–70%.
- 1HTF Bias must be clear. H1 or H4 showing "HTF Bias: BULLISH" (for buy OBs) or "HTF Bias: BEARISH" (for sell OBs).
- 2Scanner fires "Bullish Order Block — FRESH" (83% confidence). "Fresh" means the OB zone has NOT been retested since the displacement candle.
- 3Wait for price to pull back INTO the OB zone. The OB zone is printed as a price range in the signal notes (e.g. OB zone $4830–$4835).
- 4Enter on first bullish candle inside the OB zone. This can be a pin bar, engulfing, or simple close above the OB low.
- 5SL: 3–5 pips below the OB zone low. TP: previous swing high or equal distance. Trail SL to break-even after 1:1.
30 — Scalp Setup D: Stop-Hunt Reversal
Fastest R:R setup. Must act within 1–3 minutes of signal. Win rate when confirmed: ~60–65%.
- 1Scanner fires "BSL Sweep Confirmed" (89%) or "SSL Sweep Confirmed" (89%). This is the highest-confidence single signal in the scanner.
- 2Verify the candle pattern. The sweep candle must have: wick beyond the equal highs/lows level AND body closed back inside the range.
- 3Enter immediately on close of the first reversal candle after the sweep. This setup degrades rapidly — do not wait more than 2–3 minutes.
- 4SL: beyond the wick extreme + 3–5 pips. This is a very tight SL which gives excellent R:R.
- 5Target: opposite liquidity pool (the equal lows/highs on the other side of the range). Typical R:R is 1:3.5–1:5.
31 — Pre-Trade Checklist
Run through this before every trade. If any RED item fails, do not enter.
| Check | Required | Where to look |
|---|---|---|
| ✅ HTF Bias confirmed | H1 bias matches trade direction | H1✓ badge on setup card |
| ✅ In or near killzone | Green or gold KZ timer preferred | Top bar |
| ✅ Grade A or B | Confluence score ≥4/14 | Setup card grade badge |
| ✅ No news warning | No ⚠ badge on setup card | Setup card |
| ✅ R:R ≥ 1:2 | Minimum 1:2, prefer 1:3 | Setup card bottom row |
| ✅ Setup not expired | Under 15 minutes old for scalps | Expiry badge (green/gold) |
| ✅ Spread acceptable | Below 0.8 pips for M1/M5 | Top bar spread field |
| ✅ Position size calculated | Max 1% risk per trade | Position size calculator |
| ✅ Not Asian session | Session filter ON or manually verified | SESSION label on setup |
| ✅ Not Friday afternoon | After 16:00 UTC Friday = avoid | Day profile signal |
32 — Best Trading Times (UTC)
| Time (UTC) | Session | Quality | What to do |
|---|---|---|---|
| 06:30–07:00 | Pre-London | Prepare | Note Asian range H/L. Check H1 bias. Get ready. |
| 07:00–07:30 | London Open | ⭐ Best | Highest probability. Watch for Asian sweep signal. Act immediately on Grade A. |
| 07:30–09:00 | London Active | Good | Continuation setups. FIB + OB entries work well. Enable H1→M5 confirm. |
| 09:00–11:30 | Mid-session | Low | Avoid new entries. Review results. Prepare for NY. |
| 11:30–12:00 | Pre-NY | Prepare | Assess London direction. Pre-NY alert fires at 11:30. |
| 12:00–13:00 | NY Open | ⭐ Good | Second-best window. London continuation or NY reversal. Full size allowed. |
| 13:00–14:00 | NY Active | Good | Continuation of NY direction. Watch for reversal signals. |
| 14:00–17:00 | NY Afternoon | Low | Reduced size only. Setups exist but lower reliability. |
| 17:00+ | NY Close | Avoid | No new entries after 17:00 UTC. Close profitable positions. |
Day of week quality
| Day | Quality | Notes |
|---|---|---|
| Monday | Weak | Accumulation day. Range. Wait for Tuesday direction. |
| Tuesday | ⭐ Best | Judas Swing day. Sweeps Monday range then establishes weekly trend. Full size. |
| Wednesday | Caution | FOMC/news risk. Continues Tuesday OR reverses. Reduce size to 50%. |
| Thursday | Good | Delivery day. Second strongest. Continuation of weekly direction. |
| Friday | Avoid | Trap and reverse. Weekly highs/lows swept. Lock profits, no new entries after 13:00 UTC. |
33 — Hard Rules for Profitable Scalping
- Maximum 1% account risk per trade. Use the position size calculator every time.
- Never enter during Asian session (22:00–07:00 UTC). Wait for London.
- Never enter if spread is above 0.8 pips. Check the spread in the top bar.
- Never fight the H1 HTF Bias. If H1 is bearish, only take SELL setups on M1/M5.
- Never chase a move that's already run 30+ pips. Wait for the next setup.
- Always set SL before entering. No "I'll set it after." The scanner shows the SL for every signal.
- Maximum 2 trades per session (London = 1 session, NY = 1 session). Quality over quantity.
- If first trade is a loss, reduce next trade size to 0.5% risk. Never revenge trade.
- Take TP1 at 1:1.5 (half position). Move SL to breakeven. Let the rest run free.
- Check the Setup Replay stats in every setup card — if a strategy shows <45% WR in YOUR database, avoid it.
- Best trades fire within the first 20 minutes of a Killzone. If nothing by 30 min — wait for the next session.
- When Grade A fires with the KZ timer green AND H1 ✓ badge — this is maximum conviction. Enter at full 1% risk.
- Keep the backtest tab open and check win rate by timeframe weekly. If M1 shows <45% — stop trading M1.
34 — Confluence Engine
The 14-category confluence engine is the core of the Best Setups panel. It prevents double-counting by allowing each category to contribute at most 1 point, regardless of how many signals of that type fire.
| # | Category | What counts |
|---|---|---|
| 1 | strategy | Any of the 4 playbook strategies (S/R Flip, Breakout, EMA Pullback, Stop-Hunt) |
| 2 | trend_ema | EMA Stack, EMA Cross, Price above/below EMA200 |
| 3 | momentum | RSI, MACD, Stochastic, CCI, ADX, Parabolic SAR |
| 4 | structure | CHoCH, BOS, Market Structure (HH/HL or LH/LL) |
| 5 | candle | Any CANDLE type pattern (Engulfing, Pin Bar, Hammer, etc.) |
| 6 | sr_level | Support/Resistance or Round Number proximity |
| 7 | volume | OBV, VWAP, Volume Spike, MFI signals |
| 8 | session | Active non-Asian session signal |
| 9 | ote_fvg_ob | OTE Zone, Order Block, Fair Value Gap, FVG |
| 10 | bill_williams | Alligator EATING (not sleeping), AO Zero Line Cross |
| 11 | killzone | London KZ or NY KZ signal active |
| 12 | fibonacci | Fibonacci Golden Zone or 38.2–61.8% zone |
| 13 | htf_bias | HTF Bias signal on H1/H4/D1 |
| 14 | probability | Win Probability Score signal |
Minimum to show setup: 3/14. Grade A: ≥6/14 AND confidence ≥82%. Grade B: ≥4/14 AND confidence ≥75%.
35 — Database & Storage
The database.py module manages a local SQLite database at data/scanner.db.
Tables
| Table | Records | Purpose |
|---|---|---|
| setups | Every Best Setup (Grade A/B/C) detected | Outcome tracking, backtest analytics |
| all_signals | Every signal above 68% confidence | Full signal history, JSON export |
| price_ticks | Every live price tick (24h rolling) | Outcome resolution for pending setups |
JSON exports (auto-generated hourly)
| File | Contents |
|---|---|
data/setups_export.json | All Best Setups with outcomes, grades, confluence cats |
data/signals_export.json | Last 10,000 raw signals |
data/analytics_export.json | Full backtest analytics snapshot |
Click ⬇ JSON in the Backtest tab to trigger an immediate export. Exports update automatically every hour while the scanner is running.
36 — API Reference
All endpoints served by server.py on port 5000.
Pages
Live Scanner
Position Sizing
Database / Setup Backtest
MT5 Backtest Engine
37 — Alerts System
| Alert type | Trigger | How |
|---|---|---|
| Grade A Browser Notification | New Grade A setup detected | Browser native notification popup (requires Allow permission) |
| Grade A In-App Toast | New Grade A setup detected | Gold-bordered overlay top-right, auto-dismisses after 15 seconds |
| Grade A Audio Beep | New Grade A setup detected | Two-tone via AudioContext API: high pitch = BUY, low pitch = SELL |
| Console alert (scanner.py mode) | Any alert above minconf | ANSI-colored box printed to terminal |
| Windows toast notification | Any alert above minconf (scanner.py mode) | win10toast library popup |
| Sound beep (scanner.py mode) | Any alert above minconf | winsound.Beep() — 880/1100 Hz for BUY, 440/330 Hz for SELL |
| Log file | Every signal above minconf | Written to logs/signals_YYYYMMDD.log |
Deduplication
The same pattern + direction + timeframe will not alert again within 15 minutes (configurable via --cooldown flag). This prevents alert spam when the same pattern fires repeatedly.
38 — Configuration
server.py defaults
TIMEFRAMES = ["M1", "M5", "M15", "H1"] # Timeframes to scan SCAN_INTERVAL = 8 # Seconds between scans MIN_CONFIDENCE = 68.0 # Minimum confidence to include signal
scanner.py command-line flags (GUI mode)
| Flag | Default | Effect |
|---|---|---|
--symbol | XAUUSD | Symbol to scan |
--tfs | M1,M5,M15,H1 | Timeframes (comma-separated) |
--interval | 10 | Scan interval in seconds |
--minconf | 68 | Minimum confidence threshold |
--cooldown | 15 | Minutes between re-alerts of same pattern |
--bars | 500 | History bars to load per timeframe |
--no-sound | off | Disable audio alerts |
--no-desktop | off | Disable Windows toast notifications |
Scalping configuration (recommended)
python scanner.py --tfs M1,M5 --interval 5 --minconf 72
Scans M1 and M5 every 5 seconds with a higher minimum confidence, giving you only the cleanest scalp signals.
39 — Troubleshooting
| Problem | Cause | Fix |
|---|---|---|
| Dashboard blank / "Connecting to MT5..." | MT5 not connected or algo trading disabled | Open MT5, log in, Tools→Options→Expert Advisors→Allow algorithmic trading ✓ |
name 'np2' is not defined | Stale Python cache | Delete __pycache__ folder, restart scanner |
| Could not select XAUUSD | XAUUSD not in Market Watch | MT5 → Market Watch (Ctrl+M) → right-click → Show All → find XAUUSD → double-click |
| Connected to wrong MT5 terminal | Multiple MT5 installations | Close MetaQuotes demo terminal, keep only your broker's MT5 open |
| No signals appearing | All signals contradictory / Asian session | Turn off filter pills (R:R, Conf, Session) temporarily. Check if it's Asian session. |
| Best Setups panel empty | Filters too strict or mixed market | Disable R:R ≥ 1:3 or Conf ≥ 75% pills. Increase expiry slider. |
| Port 5000 already in use | Previous scanner instance still running | Close all CMD windows, open Task Manager → find python.exe → End Task |
| Grade A notification not showing | Browser permission not granted | Click the lock icon in browser URL bar → Allow notifications for localhost |
| Database not saving setups | data/ folder permission issue | Run CMD as Administrator, or manually create the data/ folder |
| Backtest tab shows "No data" | Scanner hasn't run long enough | Leave the scanner running. Best Setups auto-save. Check after 1–2 hours of scanning. |
40 — Changelog
v3.2.1 (Current — Hotfix)
- Fixed:
np2 is not definedcrash indetect_htf_bias - Fixed: Scanner connecting to MetaQuotes demo terminal instead of broker terminal on reconnect
v3.2
- Multi-TF confirmation toggle (H1→M5 confirm)
- Setup expiry timer (5–60 min slider)
- Grade A browser notification + audio beep + in-app toast
- Key level proximity detection on every setup card
- News risk filter (CPI/NFP/FOMC/ECB time windows)
- Setup replay stats from DB backtest on every card
- H1 ✓/✗ HTF match badge on setup cards
v3.1
- London & NY Killzone detector with Asian sweep logic
- Fibonacci Golden Zone (61.8–78.6%) OTE detector
- HTF Daily Bias (H1/H4/D1)
- Win Probability composite score
- Position Size Calculator
- Killzone countdown timer in top bar
- New filter tabs: Killzones, Fibonacci, Win Probability
v3.0
- Auto-retry MT5 connection every 15s (never exits on failure)
- SQLite database for setup tracking and outcome resolution
- All signals saved to
all_signalstable - Outcome resolution via MT5 bars + live tick fallback
- JSON auto-export (hourly) to data/ folder
- Backtest tab in right panel (DB-backed, no MT5 needed)
- Diagnostics panel (4-step fix guide when MT5 disconnects)
- Error recovery: auto-reconnect after 5 consecutive errors
v2.2 and earlier
- Best Setups panel with 14-category confluence engine
- Smart noise filter (contradictory BUY+SELL eliminated)
- 4 playbook strategies: S/R Flip, Breakout, EMA Pullback, Stop-Hunt
- scan_all double-override fix
- Alerts dedup direction fix
- R:R ≥ 1.5 minimum filter
- Flask server with web dashboard
- MT5 backtest engine with Monte Carlo and regime detection