v3.2.1 — Complete Documentation

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.

Python 3.13 MetaTrader 5 Flask Web Server SQLite Database 70+ Patterns ICT/SMC

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.

⚡ Core Philosophy
The scanner does NOT predict the future. It identifies when multiple independent technical factors align on the same direction — which statistically produces higher win-rate entries. The more categories that agree (EMA trend + volume + structure + Fibonacci + killzone), the higher the probability of the move continuing.

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

ComponentFilePurpose
Web Serverserver.pyFlask server, scanner loop, all API endpoints
Pattern Enginepatterns.pyAll 70+ detectors, confluence scorer, scan_all
MT5 Feedmt5_feed.pyMT5 connection, OHLCV data, tick feed, account info
Databasedatabase.pySQLite storage, outcome tracking, JSON export
Backtest Enginebacktest.pyWalk-forward simulation, Monte Carlo, regime detection
Web Dashboarddashboard.htmlMain UI — chart, signals, setups, backtest tab
Backtest Pagebacktest.htmlStandalone backtest analytics page
GUI Dashboardgui_dashboard.pyTkinter desktop window (scanner.py mode)
Terminal Dashboarddashboard.pyANSI terminal display (scanner.py mode)
Alertsalerts.pySound, desktop toast, console, log file
Scanner Loopscanner.pyGUI mode entry point

02 — Quick Start

Prerequisites

Step-by-step setup

  • 1
    Open MetaTrader 5 and log into your broker account
  • 2
    Press Ctrl+M to open Market Watch. Right-click → Show All to find XAUUSD
  • 3
    Go to Tools → Options → Expert Advisors → check Allow algorithmic trading
  • 4
    Double-click START.bat in the scanner folder
  • 5
    Browser opens automatically at http://localhost:5000
  • 6
    Wait 10–30 seconds for MT5 to connect and first scan to complete
⚠ Common Startup Problems
Blank dashboard / "Connecting..." — MT5 is not connected. Check steps 1–3 above.
"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

ModeHow to startBest for
Web DashboardSTART.batMain use — full UI in browser
GUI WindowSTART_SCANNER.batDesktop 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

PackageVersionPurpose
MetaTrader5≥5.0.45MT5 Python bridge — data feed and account info
pandas≥2.0.0OHLCV DataFrame manipulation
numpy≥1.24.0Numerical calculations in all detectors
scipy≥1.10.0argrelextrema for swing high/low detection
flask≥3.0.0Web server for dashboard
flask-cors≥4.0.0Cross-origin headers
win10toast≥0.9Windows 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.

ZoneLocationContents
Top BarFull widthLive price, bid/ask, spread, session, killzone timer, scan count, connection status
Strategy Filter BarBelow top barFilter buttons: All Signals, S/R Flip, Breakout, EMA Cont., Stop-Hunt, SMC/ICT, BW, Volume Intel, Killzones, Fibonacci, Win Probability
Left Column286px wideMarket Bias, TF grid, Best Trade card, signal tabs, signal list
Centre ColumnFlexibleCandlestick chart with EMA 21/50/100 and volume, pattern type pills at bottom
Right Column340px wideAccount info, Position Size Calculator, 4 tabs: ⚡ Setups / 📊 Backtest / Active / History
Status BarBottomConnection 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  │
└─────────────────────────────────────────────────────┘
FieldMeaning
BUY / SELL / WATCHDirection. WATCH = neutral / informational pattern
M1 / M5 / M15 / H1Timeframe where the pattern was detected
Pattern nameExact 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:RReward-to-risk ratio. Minimum 1.5, best setups ≥1:3
Minimum Confidence for Alerts
Default is 68%. Only patterns above this threshold are displayed and alerted. Adjust in DEFAULT_CONFIG in 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

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             │
└─────────────────────────────────────────────────────────────┘
ElementMeaning
H1 ✓H1 timeframe bias matches this setup's direction
H1 ✗H1 bias opposes this setup — trade with caution
Grade AScore ≥6/14 AND confidence ≥82% — highest probability
Grade BScore ≥4/14 AND confidence ≥75% — good setup
Grade CScore ≥3/14 — valid but lower conviction
2m ago / NEWExpiry timer — how long ago this setup first fired
⚠ News warningMajor economic event within 30 minutes
📍 At S/REntry price is within 8 pips of a key level
📊 Replay statsHistorical performance of this strategy from your backtest DB

Filter controls

ControlDefaultEffect
R:R ≥ 1:3 pillONOnly show setups with reward:risk ≥ 1:3
Conf ≥ 75% pillONOnly show setups with confidence ≥ 75%
Session pillONHide setups in Asian / dead zone sessions
Hide after slider30 minAuto-expire setups older than N minutes
H1→M5 confirmOFFWhen ON: blocks M1/M5 setups that contradict H1 bias
Grade A Alerts
When a Grade A setup fires: (1) browser popup notification appears, (2) in-app gold-bordered toast shows for 15 seconds, (3) two-tone audio beep plays. Click "Allow" when the browser asks for notification permission.

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

  1. 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
  2. Live ticks (fallback): If MT5 data isn't available, live price ticks are used instead
  3. Expired (24h): Setups that hit neither TP nor SL within 24 hours are marked expired

What the tab shows

SectionContents
DB Status PillsTotal setups stored, wins, losses, pending, all signals count
Summary CardsWin Rate, Net R, Profit Factor, Expectancy, Max Drawdown
Equity CurveCumulative R earned over time from resolved setups
By GradeWin rate breakdown for Grade A, B, C separately
By TimeframeWin rate for M1, M5, M15, H1
Strategy BreakdownEach strategy with win rate bar, total R, EDGE/NEUTRAL/AVOID verdict
Recent TradesLast 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)
InputDefaultNotes
Risk %1.0%Percentage of account balance to risk on one trade
Pip Value ($)$10Dollar value per pip per standard lot. Check with your broker — MavenTrade is typically $10 for XAUUSD
Gold Pip Value Note
For XAUUSD on most brokers: 1 standard lot = 100 troy oz. 1 pip = $0.01 movement. Pip value = $1 per 0.01 move per lot = effectively $10 per pip per standard lot. If your broker shows different values, adjust the Pip Value input accordingly.

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.

KillzoneUTC TimeTimer ColorWhat to expect
London Killzone07:00–09:00GreenAsian range sweep + reversal. Best entry of the day.
NY Killzone12:00–14:00GreenLondon continuation or NY reversal. Second best window.
Pre-London Alert06:30–07:00GoldPrepare: note Asian range high and low now
Pre-NY Alert11:30–12:00GoldAssess London direction. Ready for NY continuation
Outside KZAll other timesRed/MutedCountdown 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.

Hammer
CANDLE · Bullish
Lower wick ≥2× body. After downtrend. Signals demand absorption.
73%
Hanging Man
CANDLE · Bearish
Lower wick ≥2× body. At top of uptrend. Reversal warning.
65%
Shooting Star
CANDLE · Bearish
Upper wick ≥2× body after uptrend. Institutional selling rejection.
71%
Inverted Hammer
CANDLE · Bullish
Upper wick ≥2× body after downtrend. Possible reversal.
63%
Bullish Engulfing
CANDLE · Bullish
Bull candle completely covers prior bear candle body. Strong reversal.
82%
Bearish Engulfing
CANDLE · Bearish
Bear candle completely covers prior bull candle body. Strong reversal.
82%
Morning Star
CANDLE · Bullish
3-candle: Bear → Doji → Bull closing above midpoint. High reliability.
84%
Evening Star
CANDLE · Bearish
3-candle: Bull → Doji → Bear closing below midpoint. High reliability.
84%
Doji
CANDLE · Neutral
Body <10% of range. Indecision. Watch next candle for direction break.
58%
Gravestone Doji
CANDLE · Bearish
Upper wick >60% of range, tiny body at bottom. Bears rejected highs.
74%
Dragonfly Doji
CANDLE · Bullish
Lower wick >60% of range, tiny body at top. Bulls reclaimed price.
74%
Pin Bar Bullish
CANDLE · Bullish
ICT style: Lower wick ≥45% of range, close in top 30%. Demand absorbed.
77%
Pin Bar Bearish
CANDLE · Bearish
ICT style: Upper wick ≥45% of range, close in bottom 30%. Supply rejected.
77%
Three White Soldiers
CANDLE · Bullish
3 consecutive bull candles each closing higher. Institutional buying.
79%
Three Black Crows
CANDLE · Bearish
3 consecutive bear candles each closing lower. Institutional selling.
79%
Bullish Marubozu
CANDLE · Bullish
No wicks, body ≥85% of range. Pure one-sided institutional buying.
76%
Bearish Marubozu
CANDLE · Bearish
No wicks, body ≥85% of range. Pure one-sided institutional selling.
76%
Piercing Line
CANDLE · Bullish
Opens below prior bear's low, closes above its midpoint.
73%
Dark Cloud Cover
CANDLE · Bearish
Opens above prior bull's high, closes below its midpoint.
73%
Inside Bar
CANDLE · Neutral
Candle range entirely inside prior candle. Compression before breakout.
62%

12 — Chart Patterns

Detected by detect_chart() using scipy.signal.argrelextrema to find swing highs and lows, then checking geometric relationships.

PatternDirectionConfidenceDescription
Head & ShouldersBearish82–87%Three peaks, middle highest. Neckline break confirms. Classic reversal.
Inverse H&SBullish82–87%Three troughs, middle lowest. Strongest bullish reversal chart pattern.
Double TopBearish83%Two equal peaks within 0.5% tolerance. Bearish reversal on neckline break.
Double BottomBullish83%Two equal troughs. Bullish reversal on neckline break above.
Triple TopBearish86%Three equal peaks. Very strong resistance. Highest chart pattern confidence.
Triple BottomBullish86%Three equal troughs. Very strong support. Breakout imminent.
Ascending TriangleBullish77%Flat resistance + rising support. Bullish breakout probable.
Descending TriangleBearish77%Falling resistance + flat support. Bearish breakdown probable.
Symmetrical TriangleNeutral70%Converging trendlines. Big move imminent — direction needs volume confirmation.
Rising WedgeBearish74%Both lines rising but converging. Bearish reversal — sell break below lower line.
Falling WedgeBullish74%Both lines falling but converging. Bullish reversal — buy break above upper line.
Bull FlagBullish77%Strong bull pole + tight consolidation (<0.3% range). Continuation expected.
Bear FlagBearish77%Strong bear pole + tight consolidation. Continuation expected.
Cup & HandleBullish80%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.

ConceptDirectionConfidenceDescription
CHoCH BullishBullish87%Change of Character — bearish structure broken. Highest conviction reversal signal. Wait for OB/FVG retest.
CHoCH BearishBearish87%Bullish structure broken → bearish reversal. Maximum conviction on H4.
BOS BullishBullish78%Break of Structure — price broke swing high. Wait for 61.8–79% OTE pullback to enter long.
BOS BearishBearish78%Price broke swing low. Watch for OTE pullback to enter short.
Bullish Market StructureBullish72%Higher Highs + Higher Lows confirmed. Only buy dips to OB/FVG/OTE zones.
Bearish Market StructureBearish72%Lower Highs + Lower Lows. Only sell rallies to OB/FVG/OTE zones.
Bullish Order BlockBullish59–83%Last bearish candle before bull displacement. FRESH = 83%, tested once = 71%, twice = 59%.
Bearish Order BlockBearish59–83%Last bullish candle before bear displacement. Confidence degrades with each retest.
Bull FVGBullish66–81%Fair Value Gap — price imbalance that acts as magnet. Unfilled = 81%, partial = 66%.
Bear FVGBearish66–81%Bearish imbalance. Price returns to fill the gap.
In Bull OTE ZoneBullish84%Optimal Trade Entry — price at 61.8–79% Fibonacci of swing. Prime long entry after BOS.
In Bear OTE ZoneBearish84%Price at 61.8–79% retracement of bearish swing. Prime short entry after BOS.
BSL Sweep ConfirmedBearish89%Wick above equal highs, body closed below. Stop hunt complete. Highest confidence signal.
SSL Sweep ConfirmedBullish89%Wick below equal lows, body closed above. Stop hunt complete. Enter immediately.
Premium ZoneBearish68%Price above 50% equilibrium. Institutional sell bias.
Discount ZoneBullish68%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.

IndicatorSignalConfidenceLogic
EMA Bullish StackBullish77%EMA8 > EMA21 > EMA50 > EMA200. Perfect uptrend alignment.
EMA Bearish StackBearish77%EMA8 < EMA21 < EMA50 < EMA200. Perfect downtrend alignment.
EMA 8/21 Golden CrossBullish78%EMA8 crossed above EMA21. Short-term bullish momentum.
EMA 8/21 Death CrossBearish78%EMA8 crossed below EMA21. Short-term bearish momentum.
RSI Oversold (<30)Bullish72%RSI below 30. Statistically oversold. Bounce likely.
RSI Overbought (>70)Bearish72%RSI above 70. Statistically overbought. Pullback likely.
RSI Bullish DivergenceBullish81%Price lower low but RSI higher low. Hidden buying pressure.
RSI Bearish DivergenceBearish81%Price higher high but RSI lower high. Hidden selling pressure.
MACD Bullish CrossoverBullish75%MACD histogram crossed above zero. Upward momentum confirmed.
MACD Bearish CrossoverBearish75%MACD histogram crossed below zero. Downward momentum confirmed.
BB Lower Band TouchBullish69%Price below lower Bollinger Band. Statistically oversold.
BB Upper Band TouchBearish69%Price above upper Bollinger Band. Statistically overbought.
BB SqueezeNeutral67%Bandwidth <1.5%. Extreme compression — big move imminent.
Stoch Bullish CrossBullish76%%K crossed above %D in oversold zone (<20). Strong buy confirmation.
Stoch Bearish CrossBearish76%%K crossed below %D in overbought zone (>80). Strong sell confirmation.
CCI OversoldBullish68%CCI <-100. Commodity Channel Index oversold zone.
CCI OverboughtBearish68%CCI >100. Overbought reversal zone.
ADX Strong TrendBull/Bear73%ADX >25. Confirmed trend. +DI vs -DI determines direction.
Ichimoku TK Cross BullBullish79%Tenkan crossed above Kijun. Bullish. Stronger above cloud.
Ichimoku TK Cross BearBearish79%Tenkan crossed below Kijun. Bearish. Stronger below cloud.
Parabolic SARBull/Bear67%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.

TypeLogicConfidence
Resistance levelsSwing highs within 5% of current price, merged within 0.2% tolerance60–85% (closer = higher)
Support levelsSwing lows within 5% of current price, merged within 0.2% tolerance60–85% (closer = higher)
Round Number $100Within 1.5% of $100 increments ($4800, $4900…)72%
Round Number $50Within 1.5% of $50 increments ($4850, $4950…)72%
Round Number $25Within 1.5% of $25 increments ($4875, $4825…)72%
Gold Round Numbers
Gold is heavily influenced by psychological levels at $100, $50, and $25 increments. These levels are hunted repeatedly by institutions for liquidity. A setup firing near $4900 or $5000 has extra conviction.

16 — Volume Intelligence

Detected by detect_volume(). MT5 provides tick volume which correlates well with real volume for direction confirmation.

SignalDirectionConfidenceLogic
OBV Bullish DivergenceBullish83%Price falling but OBV rising. Institutional accumulation — smart money buying the dip.
OBV Bearish DivergenceBearish83%Price rising but OBV falling. Institutional distribution — smart money selling into rally.
Volume Spike (≥2σ)Bull/Bear60–89%Volume ≥2 standard deviations above 20-bar average. Direction from price move at time of spike.
VWAP PositionBull/Bear67%Price above VWAP = institutional long bias. Below = institutional short bias.
VWAP ExtendedReversal68%Price >1% from VWAP — mean reversion likely. VWAP acts as magnet.
MFI Oversold (<20)Bullish75%Money Flow Index oversold. Volume-weighted — stronger signal than RSI alone.
MFI Overbought (>80)Bearish75%Volume-weighted overbought. High probability pullback.
MFI Bullish DivergenceBullish80%Price down but MFI rising. Volume not confirming drop.
MFI Bearish DivergenceBearish80%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.

SignalConfidenceMeaning
Alligator EATING UP82%Lips > Teeth > Jaw and price above Lips. Strong uptrend. Enter longs on pullbacks to Lips.
Alligator EATING DOWN82%Lips < Teeth < Jaw and price below Lips. Strong downtrend. Enter shorts on rallies to Lips.
Alligator SLEEPING60%Lines intertwined. Ranging market — no edge. Wait for separation.
AO Zero Line Cross UP77%Awesome Oscillator crossed above zero. Bullish momentum confirmed.
AO Zero Line Cross DOWN77%AO crossed below zero. Bearish momentum confirmed.
BW MFI Squat75%Volume rising but range falling. Battle at key level — BREAKOUT IMMINENT.
Bear/Bull Fractal63%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)

The #1 Trading Window for XAUUSD
London institutions arrive and immediately hunt the liquidity stored above/below the Asian session range. The sequence is almost always: (1) sweep Asian high or low, (2) sharp reversal, (3) trend for the day established. The scanner detects which side was swept and fires a directional signal.
SignalDirectionConfidenceTrigger
London KZ — Swept Asian HighBearish88%Price swept Asian session high, body closed back below. Reversal down expected.
London KZ — Swept Asian LowBullish88%Price swept Asian session low, body closed back above. Reversal up expected.
London KZ — Watch for BSL SweepBearish72%Price in upper half of Asian range. London will likely sweep the high first.
London KZ — Watch for SSL SweepBullish72%Price in lower half. London likely sweeps the low first, then reverses up.

New York Killzone (12:00–14:00 UTC)

SignalDirectionConfidenceTrigger
NY KZ — London Continuation LongBullish80%London was bullish. NY open continuing same direction. Buy dips to London midpoint.
NY KZ — London Continuation ShortBearish80%London was bearish. NY continuing downward. Sell rallies to London midpoint.
NY KZ — Potential London ReversalNeutral68%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.

ZoneDirectionConfidenceWhen to use
Golden Zone (61.8–78.6%)Bull/Bear87%After any clear impulse move ≥15 pips. ICT's OTE — highest-probability entry on gold.
38.2–61.8% ZoneBull/Bear74%Shallow pullback in strong trend. Enter here if momentum is very strong.
Deep Retracement (>78.6%)Bull/Bear65%Last-chance entry zone before swing low/high. Must have OB or CHoCH confirmation.
Best Fibonacci Combination
Fibonacci Golden Zone + Order Block + Killzone = ICT's "Triple Confluence" entry. When all three align on M5 or M15 in the correct HTF direction, this is the highest-probability trade setup in the entire scanner.

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.

SignalConfidenceLogic
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

FactorPointsCondition
In Killzone+2Current time is in London KZ or NY KZ
Day of week — Tuesday+3Best delivery day (Judas Swing day)
Day of week — Thursday+2Second best delivery day
Day of week — Wednesday+1News risk but still tradeable
High-confidence pattern ≥85%+2 eachCounts each qualifying pattern
Good-confidence pattern ≥75%+1 eachCounts each qualifying pattern
EMA bullish alignment+2Price > EMA21 > EMA50
EMA bearish alignment+2Price < EMA21 < EMA50
RSI oversold (<40)+2Favours bullish setups
RSI overbought (>60)+2Favours bearish setups
ScoreGradeAction
≥10 (bull > bear +3)AHIGH PROBABILITY — trade at full size in killzone
6–9 (bull > bear +3)BGOOD PROBABILITY — trade at normal size
Bull ≈ Bear—NEUTRAL — wait for more confluence

22 — S/R Flip Retest (Playbook Strategy 1)

Core Concept
When a key support or resistance level is broken decisively (15+ pip expansion), it flips roles. Old resistance becomes new support, old support becomes new resistance. Trade the RETEST of the flipped level, not the initial break. The crowd buys/sells the breakout — you enter the retest with a better price and tighter SL.

Entry rules

23 — Consolidation Breakout (Playbook Strategy 2)

Core Concept
Find a consolidation range (8–80 pips wide, ≥2 touches on each boundary). After a genuine breakout (15+ pip extension), wait for the retest of the broken boundary. The crowd enters on the breakout candle — you enter the retest with confirmation and much better R:R.

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)

Core Concept
When the 21/50/100 EMA stack is aligned (bull: 21>50>100, bear: 21<50<100), price pulling back to the EMA zone is the optimal trend continuation entry. The deeper the pullback (100 EMA) the better the R:R.
EMA TouchedConfidenceR:RNotes
100 EMA83%1:3.6Deep pullback — best R:R, highest conviction entry
50 EMA81%1:3.1Primary entry zone — most common setup
21 EMA76%1:2.5Minor pullback — only in very strong trends

25 — Stop-Hunt Reversal (Playbook Strategy 4)

Core Concept — Highest R:R Setup (1:3.5+)
Institutions hunt retail stop losses clustered above swing highs and below swing lows (equal highs/lows). The signature: fast spike through the level → candle CLOSES back inside → reversal. You are trading AGAINST the crowd who just got stopped out.

Identification rules

26 — Scalping with the Scanner

🎯 Core Scalping Philosophy
Scalping gold profitably is not about trading more — it's about waiting for the one or two high-probability setups per session and executing them with precision. The scanner shows you when conditions align. Your job is to wait for Grade A or B, enter clean, and exit at TP1 (50% off) then trail the rest.

The scalper's daily routine with this scanner

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%.

A
Killzone Asian Sweep + Reversal
London KZ · M5 entry · 1:3–1:5 R:R · Best trade of the day
  • 1
    Wait for London KZ to open (07:00 UTC). KZ timer turns green. Pre-London signal fires at 06:30.
  • 2
    Watch for the sweep signal. Scanner fires "London KZ — Swept Asian High" (Bearish 88%) or "Swept Asian Low" (Bullish 88%). Do NOT enter yet.
  • 3
    Confirm 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.
  • 4
    Check confluence. Scanner should show ≥3 categories agreeing. Look for Grade A or B in the Setups panel. H1 ✓ badge is ideal.
  • 5
    Enter at close of confirmation candle. Use Position Size Calculator: 1% risk. SL = beyond the sweep wick + 5 pips.
  • 6
    TP1 = 50% at 1:1.5 R:R. Remove half position. Move SL to breakeven. Let TP2 run to 1:3.
❌ Do NOT take this trade if:
Major news within 30 minutes (scanner shows ⚠ news badge) · H1 bias contradicts direction · Spread above 0.8 pips · Already 45+ minutes into KZ (sweep should happen early) · Second sweep in same direction (only the first sweep is valid)

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%.

B
Fibonacci 61.8–78.6% Golden Zone + OB/FVG Confirmation
All sessions · M5/M15 entry · 1:2.5–1:4 R:R · ICT Optimal Trade Entry
  • 1
    Wait 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.
  • 2
    Scanner 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.
  • 3
    Look 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.
  • 4
    Enter on confirmation candle. Long lower wick closing bullish (for buys). Enter at close. SL: 5 pips below the Fib 78.6% level.
  • 5
    Target: 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%.

B
Fresh Order Block Retest in HTF Direction
Any killzone session · M5 entry · 1:2–1:3 R:R
  • 1
    HTF Bias must be clear. H1 or H4 showing "HTF Bias: BULLISH" (for buy OBs) or "HTF Bias: BEARISH" (for sell OBs).
  • 2
    Scanner fires "Bullish Order Block — FRESH" (83% confidence). "Fresh" means the OB zone has NOT been retested since the displacement candle.
  • 3
    Wait 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).
  • 4
    Enter on first bullish candle inside the OB zone. This can be a pin bar, engulfing, or simple close above the OB low.
  • 5
    SL: 3–5 pips below the OB zone low. TP: previous swing high or equal distance. Trail SL to break-even after 1:1.
OB Confidence Grades
Fresh (never retested) = 83% · Tested once = 71% · Tested twice = 59% (avoid). The scanner automatically tracks this and shows the appropriate confidence level.

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%.

A
SSL/BSL Sweep Confirmed Reversal
Any time but best in KZ · M1/M5 entry · 1:3.5–1:5 R:R · Fastest entry
  • 1
    Scanner fires "BSL Sweep Confirmed" (89%) or "SSL Sweep Confirmed" (89%). This is the highest-confidence single signal in the scanner.
  • 2
    Verify the candle pattern. The sweep candle must have: wick beyond the equal highs/lows level AND body closed back inside the range.
  • 3
    Enter immediately on close of the first reversal candle after the sweep. This setup degrades rapidly — do not wait more than 2–3 minutes.
  • 4
    SL: beyond the wick extreme + 3–5 pips. This is a very tight SL which gives excellent R:R.
  • 5
    Target: 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.

CheckRequiredWhere to look
✅ HTF Bias confirmedH1 bias matches trade directionH1✓ badge on setup card
✅ In or near killzoneGreen or gold KZ timer preferredTop bar
✅ Grade A or BConfluence score ≥4/14Setup card grade badge
✅ No news warningNo ⚠ badge on setup cardSetup card
✅ R:R ≥ 1:2Minimum 1:2, prefer 1:3Setup card bottom row
✅ Setup not expiredUnder 15 minutes old for scalpsExpiry badge (green/gold)
✅ Spread acceptableBelow 0.8 pips for M1/M5Top bar spread field
✅ Position size calculatedMax 1% risk per tradePosition size calculator
✅ Not Asian sessionSession filter ON or manually verifiedSESSION label on setup
✅ Not Friday afternoonAfter 16:00 UTC Friday = avoidDay profile signal

32 — Best Trading Times (UTC)

Time (UTC)SessionQualityWhat to do
06:30–07:00Pre-LondonPrepareNote Asian range H/L. Check H1 bias. Get ready.
07:00–07:30London Open⭐ BestHighest probability. Watch for Asian sweep signal. Act immediately on Grade A.
07:30–09:00London ActiveGoodContinuation setups. FIB + OB entries work well. Enable H1→M5 confirm.
09:00–11:30Mid-sessionLowAvoid new entries. Review results. Prepare for NY.
11:30–12:00Pre-NYPrepareAssess London direction. Pre-NY alert fires at 11:30.
12:00–13:00NY Open⭐ GoodSecond-best window. London continuation or NY reversal. Full size allowed.
13:00–14:00NY ActiveGoodContinuation of NY direction. Watch for reversal signals.
14:00–17:00NY AfternoonLowReduced size only. Setups exist but lower reliability.
17:00+NY CloseAvoidNo new entries after 17:00 UTC. Close profitable positions.

Day of week quality

DayQualityNotes
MondayWeakAccumulation day. Range. Wait for Tuesday direction.
Tuesday⭐ BestJudas Swing day. Sweeps Monday range then establishes weekly trend. Full size.
WednesdayCautionFOMC/news risk. Continues Tuesday OR reverses. Reduce size to 50%.
ThursdayGoodDelivery day. Second strongest. Continuation of weekly direction.
FridayAvoidTrap and reverse. Weekly highs/lows swept. Lock profits, no new entries after 13:00 UTC.

33 — Hard Rules for Profitable Scalping

🔴 NEVER Break These Rules
  1. Maximum 1% account risk per trade. Use the position size calculator every time.
  2. Never enter during Asian session (22:00–07:00 UTC). Wait for London.
  3. Never enter if spread is above 0.8 pips. Check the spread in the top bar.
  4. Never fight the H1 HTF Bias. If H1 is bearish, only take SELL setups on M1/M5.
  5. Never chase a move that's already run 30+ pips. Wait for the next setup.
  6. Always set SL before entering. No "I'll set it after." The scanner shows the SL for every signal.
  7. Maximum 2 trades per session (London = 1 session, NY = 1 session). Quality over quantity.
  8. If first trade is a loss, reduce next trade size to 0.5% risk. Never revenge trade.
✅ Habits That Build Consistent Profit
  1. Take TP1 at 1:1.5 (half position). Move SL to breakeven. Let the rest run free.
  2. Check the Setup Replay stats in every setup card — if a strategy shows <45% WR in YOUR database, avoid it.
  3. Best trades fire within the first 20 minutes of a Killzone. If nothing by 30 min — wait for the next session.
  4. When Grade A fires with the KZ timer green AND H1 ✓ badge — this is maximum conviction. Enter at full 1% risk.
  5. 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.

#CategoryWhat counts
1strategyAny of the 4 playbook strategies (S/R Flip, Breakout, EMA Pullback, Stop-Hunt)
2trend_emaEMA Stack, EMA Cross, Price above/below EMA200
3momentumRSI, MACD, Stochastic, CCI, ADX, Parabolic SAR
4structureCHoCH, BOS, Market Structure (HH/HL or LH/LL)
5candleAny CANDLE type pattern (Engulfing, Pin Bar, Hammer, etc.)
6sr_levelSupport/Resistance or Round Number proximity
7volumeOBV, VWAP, Volume Spike, MFI signals
8sessionActive non-Asian session signal
9ote_fvg_obOTE Zone, Order Block, Fair Value Gap, FVG
10bill_williamsAlligator EATING (not sleeping), AO Zero Line Cross
11killzoneLondon KZ or NY KZ signal active
12fibonacciFibonacci Golden Zone or 38.2–61.8% zone
13htf_biasHTF Bias signal on H1/H4/D1
14probabilityWin 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

TableRecordsPurpose
setupsEvery Best Setup (Grade A/B/C) detectedOutcome tracking, backtest analytics
all_signalsEvery signal above 68% confidenceFull signal history, JSON export
price_ticksEvery live price tick (24h rolling)Outcome resolution for pending setups

JSON exports (auto-generated hourly)

FileContents
data/setups_export.jsonAll Best Setups with outcomes, grades, confluence cats
data/signals_export.jsonLast 10,000 raw signals
data/analytics_export.jsonFull 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

GET
/
Main dashboard (dashboard.html)
GET
/backtest
Standalone backtest analytics page (backtest.html)

Live Scanner

GET
/api/state
Full live state: price, bid, ask, spread, all signals (up to 40), candles (last 80 bars per TF), account info, scan count, connection status, diag info
GET
/api/ping
Health check: returns ok, time, MT5 available flag, backtest available flag
GET
/api/confluence
Live confluence score for BUY and SELL based on current signals
GET
/api/regime
Current market regime detection (TRENDING/RANGING/VOLATILE/BREAKOUT) per timeframe

Position Sizing

GET
/api/position-size?balance=10000&risk_pct=1&entry=4835&sl=4830&pip_value=10
Returns lot_size, sl_pips, risk_usd, risk_actual. All params required except pip_value (default 10).

Database / Setup Backtest

GET
/api/db/stats
Quick stats: total setups, wins, losses, pending, all_signals count, db_path
GET
/api/db/backtest
Full backtest analytics: win rate, net R, profit factor, expectancy, equity curve, by_strategy, by_grade, by_timeframe, recent trades
GET
/api/db/signals?limit=200&tf=M5
Recent signals from all_signals table. Optional: limit (default 200), tf (filter by timeframe)
POST
/api/db/export
Trigger immediate JSON export to data/ folder. Returns paths and counts.
POST
/api/db/clear
Delete all stored setups and price ticks. Irreversible. Used to start fresh.

MT5 Backtest Engine

POST
/api/backtest/run
Start MT5 historical backtest (runs in background thread). Requires MT5 connection. Takes 60–90 seconds.
GET
/api/backtest/status
Progress: running, progress (0–100), step, message, error
GET
/api/backtest/results
Full simulation results: win rate, equity curve, by_strategy table, Monte Carlo simulation, regime recommendations

37 — Alerts System

Alert typeTriggerHow
Grade A Browser NotificationNew Grade A setup detectedBrowser native notification popup (requires Allow permission)
Grade A In-App ToastNew Grade A setup detectedGold-bordered overlay top-right, auto-dismisses after 15 seconds
Grade A Audio BeepNew Grade A setup detectedTwo-tone via AudioContext API: high pitch = BUY, low pitch = SELL
Console alert (scanner.py mode)Any alert above minconfANSI-colored box printed to terminal
Windows toast notificationAny alert above minconf (scanner.py mode)win10toast library popup
Sound beep (scanner.py mode)Any alert above minconfwinsound.Beep() — 880/1100 Hz for BUY, 440/330 Hz for SELL
Log fileEvery signal above minconfWritten 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)

FlagDefaultEffect
--symbolXAUUSDSymbol to scan
--tfsM1,M5,M15,H1Timeframes (comma-separated)
--interval10Scan interval in seconds
--minconf68Minimum confidence threshold
--cooldown15Minutes between re-alerts of same pattern
--bars500History bars to load per timeframe
--no-soundoffDisable audio alerts
--no-desktopoffDisable 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

ProblemCauseFix
Dashboard blank / "Connecting to MT5..."MT5 not connected or algo trading disabledOpen MT5, log in, Tools→Options→Expert Advisors→Allow algorithmic trading ✓
name 'np2' is not definedStale Python cacheDelete __pycache__ folder, restart scanner
Could not select XAUUSDXAUUSD not in Market WatchMT5 → Market Watch (Ctrl+M) → right-click → Show All → find XAUUSD → double-click
Connected to wrong MT5 terminalMultiple MT5 installationsClose MetaQuotes demo terminal, keep only your broker's MT5 open
No signals appearingAll signals contradictory / Asian sessionTurn off filter pills (R:R, Conf, Session) temporarily. Check if it's Asian session.
Best Setups panel emptyFilters too strict or mixed marketDisable R:R ≥ 1:3 or Conf ≥ 75% pills. Increase expiry slider.
Port 5000 already in usePrevious scanner instance still runningClose all CMD windows, open Task Manager → find python.exe → End Task
Grade A notification not showingBrowser permission not grantedClick the lock icon in browser URL bar → Allow notifications for localhost
Database not saving setupsdata/ folder permission issueRun CMD as Administrator, or manually create the data/ folder
Backtest tab shows "No data"Scanner hasn't run long enoughLeave the scanner running. Best Setups auto-save. Check after 1–2 hours of scanning.

40 — Changelog

v3.2.1 (Current — Hotfix)

v3.2

v3.1

v3.0

v2.2 and earlier

⚠ Risk Disclaimer This software is for research and educational purposes only. Past pattern performance does not guarantee future results. Always use proper risk management. Never risk more than you can afford to lose. The scanner does not constitute financial advice.