Adaptive Regime Momentum [JOAT]Adaptive Regime Momentum
Introduction
The majority of publicly available trend-following strategies rely on one of two entry mechanisms: a moving average crossover, or a price-versus-MA relationship. These are valid starting points, but they share a common weakness — they fire signals based on a single confirmatory condition that can be triggered by brief, low-conviction price moves. A single bar pushing above a moving average while volume is thin and the MA is barely sloping is not the same market condition as a sustained directional move with volume behind it and a clearly sloping MA. Yet a simple strategy would treat both identically.
Adaptive Regime Momentum is a trend-following strategy that requires three independent conditions to align before generating an entry signal. These three layers — MA slope confirmation over multiple consecutive bars, price position relative to the MA, and a volume-based demand filter — must all agree simultaneously. The result is a strategy that generates fewer signals but with higher internal consistency between entry conditions. It is designed for liquid markets on daily or higher timeframes where each component is reliably measurable.
This is an overlay strategy — all visuals are plotted directly on the price chart.
---
Strategy Properties
The following default settings are used for all backtests unless modified:
Initial capital: $10,000
Position sizing: 5% of equity per trade
Commission: 0.05% per side
Pyramiding: 0 (only one open position at a time; new signals are ignored while a position is active)
Stop loss: 2.5x ATR below the entry price (long), 2.5x ATR above the entry price (short), calculated from strategy.position_avg_price
Take profit: 4.0x ATR above the entry price (long), 4.0x ATR below the entry price (short), calculated from strategy.position_avg_price
Trail / slope exit: Position is closed early if price crosses to the wrong side of ComboMA ± 1.5x ATR, or if the MA slope reverses direction
The stop and take profit are anchored to strategy.position_avg_price — the actual average fill price of the position — rather than the signal bar's close. This ensures that in backtesting, stop and TP distances are measured from where the trade was actually opened, not from a theoretical signal level.
These are backtesting defaults only. They do not represent a recommendation for live trading position sizing or risk management.
---
Core Concepts
Signal 1 — ComboMA Slope Confirmation (Structural Momentum)
The ComboMA is a blend of two moving averages:
ALMA (Arnaud Legoux Moving Average) — a smooth MA with reduced lag, fitting to recent price without overreacting to single bars
ZLMA (Zero-Lag Moving Average) — a lag-compensated MA designed to reduce the delay between price movement and MA response
The two are blended into a single ComboMA value. The slope of this composite is then evaluated not just on the current bar, but across the last N consecutive bars (default: 3). A slope is only confirmed as UP if all of the last 3 bars showed a positive slope. A slope is only confirmed as DOWN if all 3 bars showed a negative slope. A single slope fluctuation — even if the most recent bar shows a positive slope — does not trigger confirmation unless all N bars agree.
This multi-bar slope confirmation is the primary mechanism that distinguishes this strategy from a simple MA-based entry. A one-bar slope flip that immediately reverses is filtered out. Only a sustained slope direction triggers the first condition.
Signal 2 — Price vs. ComboMA (Real-Time Confirmation)
The second condition requires that price is currently on the correct side of the ComboMA:
For a long: close > ComboMA
For a short: close < ComboMA
This condition is evaluated at the current bar, providing real-time confirmation that price is aligned with the structural slope direction. The MA slope could be upward from prior bars, but if price has already pulled back below the MA, the second condition vetoes the entry. Both the historical slope and the current price position must agree.
Signal 3 — Volume RSI (Demand Pressure Validation)
Volume RSI is RSI applied to raw volume over an 8-bar period, then divided by 50. A result above 1.0 (the default threshold) means the Volume RSI is above 50 — indicating that volume activity on recent bars has been relatively elevated compared to the preceding period.
For a long entry: Volume RSI / 50 must exceed the threshold
For a short entry: same condition applies
Volume RSI does not confirm direction — it confirms participation . A move accompanied by above-average volume has more demand/supply backing than a low-volume drift. When volume is below threshold, the third condition is not met and no entry is generated, even if slope and price position align.
RSI Filter
An additional RSI filter is applied to the close:
RSI(14) must be above 50 for long entries
RSI(14) must be below 50 for short entries
This acts as a momentum gating condition — confirming that short-term momentum is consistent with the trade direction before entry is permitted.
Non-Repainting Execution
All entry conditions are gated by barstate.isconfirmed . No signal is generated until the current bar has fully closed. This prevents intra-bar signal flickering and ensures that the backtest accurately represents what would have been traded on confirmed bar closes.
---
Exit Logic
The strategy uses a layered exit system combining fixed risk-defined targets with adaptive trend exits:
Fixed exits (via strategy.exit):
Stop loss at 2.5x ATR from entry price
Take profit at 4.0x ATR from entry price
Trail exits (via strategy.close):
Price closes beyond ComboMA ± 1.5x ATR on the wrong side
The ComboMA slope reverses (multi-bar confirmation fails in the opposite direction)
The trail exit allows winning positions to exit earlier if the trend deteriorates before reaching the fixed take profit, while the fixed TP provides a defined maximum target. The stop loss is the unconditional floor regardless of trail conditions.
---
ATR Shadow Visual
The chart displays two layers of ATR bands around the ComboMA:
Inner band: ComboMA ± 1x ATR
Outer band: ComboMA ± 2x ATR
These bands give a visual read of how extended price is from the MA relative to recent volatility, and where the trail exit threshold sits (1.5x ATR, between the two bands). They are visual aids only and do not affect strategy logic.
---
Performance Table
A table is displayed on the chart showing current strategy metrics:
Net P&L
Open P&L (current unrealized)
Win Rate
Average winning trade
Average losing trade
Maximum drawdown
Total trades
Current position direction
Current MA slope status
---
Features
Three-layer entry confirmation: multi-bar MA slope, price vs. MA, and Volume RSI
RSI momentum filter as an additional gating condition
ALMA + ZLMA blend for the ComboMA, reducing lag without sacrificing smoothness
Multi-bar slope confirmation preventing single-bar slope flickers from triggering entries
ATR-based stop and take profit anchored to actual fill price via strategy.position_avg_price
Trail exit on slope reversal or price-vs-MA breach
Non-repainting: all signals confirmed via barstate.isconfirmed
Pyramiding disabled — one position at a time
ATR shadow bands for visual context around the ComboMA
Live performance table with key metrics
---
Input Parameters
ALMA / ZLMA settings — length, offset, and sigma for each MA component
Slope Confirm Bars (default 3) — consecutive bars of slope agreement required for confirmation
Volume RSI Length (default 8) — RSI period applied to volume
Volume Threshold (default 1.0) — Volume RSI / 50 minimum for the demand filter
RSI Length (default 14) — RSI period for the momentum filter
ATR Length — period for ATR used in stop, TP, trail, and visual bands
Stop Multiplier (default 2.5) — ATR multiplier for the fixed stop loss
TP Multiplier (default 4.0) — ATR multiplier for the fixed take profit
Trail Multiplier (default 1.5) — ATR multiplier for the trail exit threshold
---
How to Use
Apply to daily or higher timeframes on liquid instruments. Volume RSI is most meaningful where volume data is consistent and representative of actual market participation.
Allow the chart to load sufficient historical bars before evaluating backtest results. The ComboMA slope confirmation requires multiple bars of agreement, and early bars in the dataset may not reflect the strategy's typical behavior. Aim for at least several hundred bars of data for meaningful backtest statistics.
Review the performance table while backtesting to understand average win size relative to average loss, drawdown, and total trade count. A strategy with very few trades may show favorable metrics by chance rather than edge — consider whether the trade count is sufficient to draw conclusions.
The default 5% equity position size produces moderate equity curve sensitivity. Smaller sizes will reduce drawdown and return proportionally; larger sizes will amplify both.
Commission is set to 0.05% per side (0.1% round trip) by default. Adjust this to match your actual trading costs. Higher commission rates — especially relevant for frequent-trading timeframes — will reduce net results.
Do not optimize parameters on the same data you use to evaluate performance. Optimization on historical data produces settings tuned to past noise, not future edge.
The trail exit on slope reversal means that strongly trending markets where the MA briefly flattens before resuming may see early exits. This is the tradeoff for using slope as an exit condition.
---
Limitations
Backtest results are calculated on historical data and do not guarantee future performance. Market conditions change, and a strategy that performed well in a particular regime may perform differently as conditions evolve.
The Volume RSI filter requires reliable volume data. This strategy is not recommended for synthetic instruments, CFDs where volume represents contracts rather than underlying market activity, or very short intraday timeframes where volume is fragmented and noisy. On such instruments, the third entry condition may be meaningless or misleading.
The multi-bar slope confirmation requirement means the strategy will miss fast, sharp trend initiations where the MA slope has not yet had N bars to confirm. This is a deliberate tradeoff — reducing false entries at the cost of some late entries on fast moves.
Pyramiding is disabled. The strategy will not add to winning positions. This limits upside during strongly trending markets where additional entries might be beneficial, but it also limits drawdown from compounding positions that subsequently reverse.
ATR-based stops and TPs are fixed at entry. They do not adjust after the trade is open (apart from the trail exit). If volatility expands significantly after entry, a 2.5x ATR stop that was appropriate at entry may become relatively tight.
The performance table reflects cumulative backtest results as of the current bar. Results will vary across different lookback windows and instruments.
Default capital of $10,000 with 5% equity sizing means each trade risks approximately $500 before the stop is hit (assuming stop is the loss floor). This is a backtesting convention — it is not a recommendation for live account sizing.
No strategy produces guaranteed results. The three-layer entry system improves internal signal consistency but cannot eliminate the inherent uncertainty of financial markets.
---
Originality Statement
Standard MA-based trend strategies treat a single bar's price-vs-MA relationship as sufficient for entry. ARM's primary differentiation is the multi-bar slope confirmation requirement : the ComboMA slope must be consistently positive (or negative) across N consecutive bars before the first condition is met. A one-bar slope deviation — common during consolidations and brief retracements — does not trigger entry. Only a sustained slope direction qualifies.
The ComboMA itself is a blend of ALMA and ZLMA, combining the smoothness and Gaussian weighting of ALMA with the lag-compensation of ZLMA. Neither is used in isolation because each has a specific weakness: ALMA can lag on sharp moves; ZLMA can be sensitive to noise. The blend leverages the strengths of both while partially offsetting their weaknesses.
The three-layer confirmation architecture — slope duration, price position, and demand validation — requires agreement across genuinely different measurement types: structural momentum over time, current price location, and volume activity. These are not three views of the same quantity. The stop and TP placement using strategy.position_avg_price rather than the signal bar close is a practical accuracy measure: in backtesting, it means risk distances are calculated from the price at which the trade was actually filled, not from where the signal was generated, which can differ from the fill price particularly on gap opens.
---
Disclaimer
This strategy is provided for educational and informational purposes only. It does not constitute financial advice, investment advice, or a recommendation to buy or sell any security. Backtested results are hypothetical and do not reflect actual trading. Hypothetical performance results have inherent limitations and do not account for execution slippage, liquidity constraints, or the psychological challenges of live trading. All trading involves risk, including the possible loss of principal. Always conduct your own research and consult a qualified financial professional before making any trading or investment decisions.
-Made with passion by officialjackofalltrades
策略

Index Futures Position Size CalculatorA simple, free position size calculator for CME index futures.
Click Entry, click Stop Loss, pick your asset, get your contract size. That's it.
═══════════════════════════════════
✦ SUPPORTED INSTRUMENTS
MNQ • MES • NQ • ES — all CME tick values hardcoded.
═══════════════════════════════════
✦ FEATURES
→ One-click Entry & Stop Loss directly on chart
→ Auto 1-handle SL buffer (protects against wick hunts)
→ Asset dropdown — no manual tick value entry
→ Custom rounding (≥0.75 rounds up, else down)
→ Green Entry / Red SL lines with price labels
→ Clean black-on-white size panel, top right
═══════════════════════════════════
✦ HOW TO USE
Add to chart → click Entry → click Stop Loss
Settings → pick asset, enter Account Size & Risk %
Read your size from the top-right panel
═══════════════════════════════════
✦ TIP
If you're trading a funded challenge, here are two clean ways to use this tool with your max loss limit:
Method 1 — Loss budget split
Decide how many consecutive losses you can take before you're out. Divide your max loss by that number, and use the result as your "Account Size" with Risk % at 100.
Example: $2,000 max loss ÷ 5 losses = $400 per trade
→ Account Size: $400 | Risk %: 100
Method 2 — Direct percentage
Enter your full max loss as Account Size and set Risk % to your per-trade percentage.
Example: $2,000 max loss, risking 20% per trade
→ Account Size: $2,000 | Risk %: 20
Both give the same result — pick whichever feels more natural.
═══════════════════════════════════
✦ A NOTE FROM THE AUTHOR
Built with Claude AI for my own daily trading. Sharing it free because clean tools shouldn't be locked behind paywalls.
100% free. 100% open source. No Discord, no course, no affiliate links, nothing to buy. Copy it, modify it, republish your own version — it's yours.
═══════════════════════════════════
✦ DISCLAIMER
Educational tool only. Not financial advice. Futures trading carries substantial risk of loss. Always verify calculations against your broker's parameters before trading.
Built with ❤️ by REDz & Claude 指标

TrueMove: Council of 7 Schools [TechnicalZen]A Decision Support System for Risk Management.
Imagine seven analysts — each a specialist in a different discipline — studying the same price chart simultaneously. One reads volume flow. Another scores multi-factor confluence. A third measures Wyckoff effort dynamics. A fourth compares wave speed and amplitude. A fifth tracks volume-weighted momentum. A sixth applies adaptive Kalman filtering. A seventh learns patterns from the instrument's own history using machine learning. Each arrives at their own independent conclusion. Then they vote.
This is what this indicator does. Seven academically grounded analytical Schools, each examining price action through a fundamentally different lens, casting independent votes on market direction. The result is not a prediction — it is a decision support system designed to help traders manage risk with confidence.
The core question it answers: "Is this move real, or is it a trap?"
When the council reaches consensus, you trade with conviction. When it doesn't, you wait. The strength of this system is not in any single School — it is in the convergence of independent perspectives. A move confirmed by volume flow, momentum, wave dynamics, and machine learning simultaneously carries fundamentally different weight than a move flagged by one method alone.
This is risk management through structured consensus. Not a black box. Not a single signal line. A council of seven independent minds, each with a transparent methodology, each with a tracked hit rate, each accountable for its calls.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The System
The indicator operates on three layers:
Signal Layer — Seven independent Schools analyze price action using different methodologies. Each votes Bull or Bear when its conditions are met.
Council Layer — Votes are aggregated. In "2+ Agree" mode, a signal fires only when two or more Schools vote in the same direction within a 3-bar window. In "All Signals" mode, any School's vote fires a signal.
Visual Layer — POC lines (anchored VWAP), EVWAP (exponentially weighted VWAP), risk/reward boxes, and direction labels present the council's verdict on the price chart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Council
The council aggregates school votes using a configurable consensus mechanism:
"2+ Agree" Mode — Requires two or more enabled Schools to vote in the same direction within a 3-bar window. This is the conservative mode. Fewer signals, higher conviction. If only one School is enabled, it automatically drops to requiring just that one vote.
"All Signals" Mode — Any enabled School's vote fires a signal. This is the aggressive mode. More signals, lower filtering. Useful for seeing what each School detects independently.
Conflict Resolution — If bull and bear votes arrive on the same bar, the direction with more votes wins. If tied, bull wins (consistent tie-breaking).
Cooldown — Separate bull and bear cooldowns prevent signal spam in the same direction while allowing quick reversals when the market genuinely flips.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The 7 Schools
Each School uses a fundamentally different analytical approach. They are designed to be independent — a signal from one School does not depend on or duplicate another.
School 1: OBV Flow
What it sees: Volume flow divergence and acceleration
Detects when On-Balance Volume diverges from price (hidden buying or selling pressure) and when volume flow is accelerating in a direction supported by market structure.
School 2: Confluence
What it sees: Multi-factor agreement across independent indicators
Triggers when RSI exits oversold (bull) or crosses below the momentum midline (bear) in a trending market. Scores seven independent factors and requires four or more to agree.
School 3: Wyckoff
What it sees: Effort vs Result on pullbacks, plus trap events
Measures whether pullback volume is declining relative to pre-pullback volume (Wyckoff effort), whether the bounce bar shows commitment (result), and detects Spring and Upthrust events — false breakdowns and breakouts that trap weak hands.
School 4: Amplitude Strength
What it sees: Wave dynamics — speed, time, and volume at swing points
Compares consecutive swing waves: is the trend wave faster than the pullback? Is the pullback shorter in time? Is volume declining at successive swing lows (or highs)? Is momentum oversold (or overbought) at the swing point? Scores seven wave-quality factors.
School 5: VWMA Delta
What it sees: Volume-weighted momentum crossing fair value
Computes the difference between short-term and long-term Volume Weighted Moving Averages, smooths it with RMA, and fires when this delta crosses zero. Volume is built into the measurement itself — not added as a secondary filter.
School 6: Kalman Filter (LQE)
What it sees: Adaptive filtered trend crossover
Applies two Kalman filters (Linear Quadratic Estimator) to price at different speeds. The short filter crossing above or below the long filter signals a trend shift. The Kalman filter adapts its responsiveness automatically based on estimation uncertainty.
School 7: Naive Bayes (Adaptive)
What it sees: Learned patterns in raw price action DNA
A machine learning classifier that observes six raw features no other School uses: body trend, wick dominance, price percentile, volatility regime, momentum acceleration, and gap behavior. It builds Gaussian probability profiles from resolved outcomes and votes when its confidence exceeds 65% in either direction. This School learns and adapts to the specific instrument and timeframe over time.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
School Rules — Complete Reference
School 1: OBV Flow (5 rules)
Price at/near 20-bar low (within 5% of range) — bull trigger
OBV well above its 20-bar low (>15% of OBV range) — divergence detection
OBV above its SMA(20) — volume flow trend confirmation
OBV slope accelerating (current 5-bar slope > previous) — momentum
Bull structure (higher lows) confirmed — structural context
Bear: symmetric mirror of all conditions
School 2: Confluence (9 rules — 2 trigger + 7 scored, need 4/7)
Trigger: RSI crosses above 30 (bull) or below 50 (bear)
Trigger gate: ADX ≥ 20 + price on correct side of EMA
Score: ADX ≥ 25 (strong trend)
Score: Bull/bear structure confirmed
Score: Price above/below SMA(50) (longer-term trend alignment)
Score: MACD line vs signal agreement
Score: Price touched EMA in last 2 bars (level test)
Score: Volume above average
Score: Candle body ratio > 50%
School 3: Wyckoff (9 rules — 7 standard + 2 trap events)
EMA cross initiates pullback tracking
Pullback duration ≥ 3 bars
Average pullback volume < pre-pullback average volume (declining effort)
OR average body ratio < 0.45 during pullback (narrow bars)
Bounce bar body ratio > 50% (strong commitment)
Bounce bar volume > pullback average volume (expanding effort)
EMA cross back confirms resolution
Spring: price breaks below previous swing low, closes back above with volume
Upthrust: price breaks above previous swing high, closes back below with volume
School 4: Amplitude Strength (7 scored, need 4/7)
Bull/bear structure confirmed
Trend wave amplitude > 0.8 ATR (bull: up-wave, bear: down-wave separately)
Trend wave speed > pullback speed (impulsive move, not grinding)
Pullback duration < trend wave duration (quick correction)
Current pullback shallower than previous (< 1.2x)
Current swing volume < previous swing volume (swing-to-swing comparison)
RSI < 40 at swing low (bull) / RSI > 60 at swing high (bear)
School 5: VWMA Delta (1 rule)
RMA(30) of VWMA(5) minus VWMA(30) crosses zero
School 6: Kalman Filter LQE (1 rule)
Kalman filter (length 50, R=0.01, Q=0.10) crosses above/below Kalman filter (length 100)
School 7: Naive Bayes Adaptive (6 features + confidence threshold)
Feature: 3-bar body trend (growing or shrinking candle bodies)
Feature: Wick dominance (upper vs lower wick ratio — rejection direction)
Feature: Price percentile in 20-bar range (position within recent range)
Feature: Volatility regime (ATR vs its SMA — expanding or contracting)
Feature: Momentum acceleration (bar-to-bar price change speeding up or slowing)
Feature: Gap behavior (open vs previous close, ATR-normalized)
Threshold: P(bull) ≥ 65% to vote bull, P(bull) ≤ 35% to vote bear
Requires minimum 15 resolved samples before voting
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How the Schools Differ
Schools 1 & 5 are volume-driven — they measure where money is flowing, not where price is moving.
Schools 2 & 4 are multi-factor scoring systems — they require multiple conditions to align before voting, reducing false positives.
School 3 is event-driven — it detects specific Wyckoff structural events (springs, upthrusts, effort exhaustion) rather than continuous measurements.
School 6 is filter-driven — it uses an adaptive mathematical estimator that adjusts its own responsiveness based on estimation uncertainty.
School 7 is the only School that learns — it builds its model from the instrument's own history and adapts over time. Every other School uses fixed rules.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Voting System
Each School votes independently. Votes are collected within a 3-bar window — Schools do not need to fire on the exact same bar to count as agreeing. This accommodates the fact that different analytical methods detect events at slightly different times.
The dashboard shows each School's most recent vote using directional emojis and colors the School name green (bull vote) or red (bear vote) when it participated in the last signal. Schools are sorted by recency — the most recently active School appears at the top of the list.
The Hit Rate column shows each School's accuracy when it participated in council signals — how often signals were correct when that School voted. This is not standalone accuracy; it measures performance within the council context.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
POC Lines (Anchored VWAP)
Three dashed lines that represent volume-weighted fair value since the last extreme volume event:
Center — the anchored VWAP: where volume-weighted price has centered since the last climax event
Upper and Lower — standard deviation bands that start at the same point as the center (origin) and branch outward as price disperses
The POC re-anchors when a volume extreme is detected (volume z-score exceeds the threshold with a directional candle). All three lines converge to a single origin point at the climax bar, then branch as the new VWAP accumulates data.
The line closest to price is highlighted with increased width and brightness. When the council signals a direction and price subsequently moves against it (crossing the POC center in the wrong direction for 3+ bars), the highlighted line changes color — red for a failed bull signal, green for a failed bear signal. This failure detection provides immediate visual feedback that the anticipated move did not materialize.
Hull smoothing can be applied to the POC lines for cleaner visual tracking.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EVWAP (Exponentially Weighted VWAP)
A solid line that tracks volume-weighted fair value with exponential decay, re-anchoring at swing direction changes:
Uses the same Exponentially Weighted Moving Average formula as the DS-VWAP methodology
Re-seeds at swing pivot points detected by the swing period setting
Volume spikes are capped at 3x the 20-bar average to prevent single bars from hijacking the calculation
Changes color based on swing direction — bull color when the most recent swing high is more recent, bear color when the most recent swing low is more recent
Direction change triangles mark where each new segment begins
Hull smoothing can be applied for a cleaner line.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Cyclic Structure: POC within EVWAP
The POC and EVWAP operate on different cycles and anchor to different events:
EVWAP re-anchors on swing direction changes (structural pivots in price). It represents the macro fair value — where the broader trend says price should be.
POC re-anchors on volume extreme events (climax bars). It represents the micro fair value — where volume clustered after the last burst of aggressive participation.
These cycles are not synchronized. A volume climax can happen mid-swing. A swing pivot can happen without a volume extreme. When both re-anchor near the same bar, that is a structurally significant event — both macro and micro fair value are resetting simultaneously.
The POC lines oscillate within the EVWAP framework. When the POC center is above the EVWAP line, volume-weighted activity is biased above the structural trend — bullish pressure. When below, bearish pressure. This relationship provides a dynamic reading of whether short-term volume activity agrees with the broader trend direction.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Risk/Reward Boxes
When a signal fires, two boxes are drawn:
Green box (above entry for bull, below for bear) — the take-profit zone at 2:1 risk-reward ratio
Red box (below entry for bull, above for bear) — the stop-loss zone at 0.5 ATR from the signal bar's extreme
Boxes extend 15 bars forward
Higher vote counts produce slightly more opaque boxes (stronger conviction = more visible)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Hit Rate and Accuracy Tracking
The indicator tracks signal accuracy using Maximum Favorable Excursion (MFE):
After each signal, the tracker monitors the next 12 bars
If price reaches 0.5 ATR in the signal direction at any point during those 12 bars (using the bar's high for bull signals, low for bear signals), the signal is marked correct
This is not a close-at-bar-12 check — it measures whether the move occurred , not whether it held
The dashboard displays:
Per-School Hit Rate — accuracy when that School participated in the council signal
Council Accuracy — overall accuracy across all evaluated signals
Signals — evaluated count vs total fired (signals during an active evaluation window are not double-counted)
Naive Bayes Learning — current status and class distribution of the adaptive learner
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Visual Aesthetics
The indicator is designed for visual clarity on dark-themed charts:
POC lines — dashed, in a distinct blue tone, with the tracked line highlighted at double width
EVWAP line — solid, colored by swing direction (bull/bear), with direction triangles at segment starts
Climax circles — small colored dots marking extreme volume events, no glow clutter
Signal labels — directional arrows with vote counts (e.g., "↑ Up (3/7)")
Dashboard — Schools sorted by recency of last vote, with bull/bear emojis and color-coded names. Schools that voted in the most recent signal appear at the top and light up in the direction color.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Council Behavior — "2+ Agree" (consensus) or "All Signals" (any School)
Signal Cooldown — Minimum bars between same-direction signals (default 30). Opposite-direction signals are not blocked.
School Toggles — Enable or disable each of the 7 Schools independently.
POC/EVWAP Smoothing — Raw or Hull smoothed. Hull length configurable.
Swing Period — Controls EVWAP re-anchoring sensitivity (default 55).
Volume Lookback — Bars analyzed for climax detection and volume statistics.
NB Min Samples — Minimum resolved outcomes before the Naive Bayes School starts voting.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, and it does not constitute a recommendation to buy, sell, or hold any financial instrument.
All trading involves risk. Past performance of any signal, voting system, or analytical method does not guarantee future results. The council votes, hit rates, and accuracy statistics displayed represent computational assessments based on the indicator's rules applied to historical data loaded in TradingView. They are not predictions and should not be treated as certainties.
The Naive Bayes School learns from the chart data currently loaded. Its learned patterns may not generalize to future market conditions, different instruments, or different timeframes. The hit rates displayed in the dashboard reflect performance on the loaded chart history only and are subject to survivorship bias, lookback bias, and data limitations inherent to backtesting on historical bars.
No indicator, algorithm, or model — regardless of how many independent methods it combines — can account for all market variables including liquidity events, news-driven gaps, exchange outages, dark pool activity, or sudden regime changes.
Traders should always use independent risk management, position sizing, and their own judgment before entering any trade.
By using this indicator, you acknowledge that you are solely responsible for your own trading decisions and that the authors accept no liability for any losses incurred.
指标

Sovereign Execution [JOAT]Sovereign Execution
Introduction
Sovereign Execution is an open-source multi-layer trading strategy that synthesizes five independent analytical engines into a unified execution framework. Rather than relying on a single indicator or a simple crossover, this strategy requires alignment across regime classification, momentum displacement, session timing, imbalance confluence, and multi-timeframe bias scoring before any trade is taken. The result is a highly selective system that filters out low-conviction setups and only enters when multiple independent analytical dimensions agree.
The strategy uses ATR-based adaptive stop-losses, configurable risk-reward ratio targets, optional trailing stops, and multiple exit conditions including regime flips and opposite displacement detection. It is designed for traders who want a systematic, rules-based approach to execution with full transparency into every decision the system makes.
Why This Strategy Exists
Most trading strategies suffer from one of two problems: they are either too simple (single-indicator entries that generate excessive noise) or too complex (dozens of conditions that are impossible to understand or debug). Sovereign Execution occupies the middle ground by using exactly five analytical layers, each addressing a different aspect of market conditions:
Regime Cipher: Is the market trending or compressing? Only trade in trending regimes.
Displacement Lens: Is there institutional momentum right now? Only enter on confirmed displacement.
Session Filter: Is the market in an active trading session? Avoid low-liquidity periods.
Imbalance Confluence: Is there a Fair Value Gap nearby? Optional confirmation of institutional interest.
Confluence Ledger: Do multiple timeframes agree on direction? Only trade when the score exceeds the threshold.
Each layer acts as an independent filter. A trade only fires when ALL active filters align simultaneously. This multi-gate approach dramatically reduces false signals compared to single-indicator strategies.
Module 1: Regime Cipher — Trend and Volatility Classification
The regime engine uses an Outlier-Resistant Moving Average (ORMA) as its foundation. The ORMA applies a square-root transformation to price, calculates a base moving average (configurable: EMA, SMA, RMA, WMA, HMA, DEMA, or TEMA), then applies a volatility-dampening filter using the ratio of full ATR to half-period ATR. This creates a moving average that is responsive to genuine trend changes but resistant to outlier spikes.
ATR-based bands are drawn above and below the ORMA. When price closes above the upper band, the regime is classified as Trending Bull. When price closes below the lower band, Trending Bear. The strategy also monitors Bollinger Band width relative to its 50-bar average to detect compression (BB width below 85% of average) and expansion (above 110%).
The key rule: the strategy only takes trades when the regime is Trending (not Compressed or Transitional). This single filter eliminates the majority of choppy, range-bound conditions where most strategies bleed money.
Module 2: Displacement Lens — Momentum Timing
The displacement engine normalizes three momentum oscillators (Bollinger %B, CCI, ROC) to a scale and blends them with a volume-weighted candle body analysis. The composite is smoothed with an EMA and compared against adaptive threshold bands calculated from the signal's own standard deviation.
A "strong bull displacement" occurs when the composite exceeds the upper threshold — meaning momentum, volume, and candle structure all confirm bullish institutional activity. Strong bear displacement is the mirror condition. The strategy only enters when displacement confirms the regime direction.
Module 3: Session Filter
Trading sessions are defined by UTC hour ranges (configurable for Asia, London, and New York). When the session filter is enabled (default), the strategy only takes trades during active sessions. This avoids entries during low-liquidity periods (overnight gaps, holiday hours) where spreads widen and price action is unreliable.
The session filter is optional — it can be disabled for instruments that trade 24/7 with consistent liquidity (e.g., major crypto pairs).
Module 4: FVG Confluence (Optional)
When enabled, the strategy scans the last 10 bars for Fair Value Gaps in the entry direction. A bullish FVG (gap up in price delivery) near the entry confirms institutional buying interest. A bearish FVG confirms selling interest. This filter is optional (default off) because not all valid setups occur near FVGs, but when enabled, it adds an additional layer of institutional confirmation.
Module 5: Confluence Score — Multi-Timeframe Bias Gate
The strategy calculates a simplified confluence score combining trend alignment, momentum, volatility state, market structure, and volume conviction on the current timeframe, then blends it with a higher timeframe score (default 4H) at a 40/60 weighting (HTF gets more weight).
The score is mapped to 0-100. Long entries require the score to exceed the long threshold (default 60). Short entries require the score to be below the short threshold (default 40). This ensures the strategy only trades when multiple analytical dimensions across timeframes agree on direction.
Entry Conditions
A long entry requires ALL of the following simultaneously:
Regime is Trending Bull (price above upper ORMA band, not compressing)
Confluence score >= long threshold (default 60)
Strong bullish displacement (composite above adaptive threshold)
Active session (if session filter enabled)
Recent bullish FVG (if FVG filter enabled)
Bar is confirmed (barstate.isconfirmed — no intrabar entries)
Short entries require the bearish mirror of all conditions. Edge detection ensures each signal fires only once — no repeated entries on the same setup.
Risk Management
Stop-Loss: ATR-based adaptive stop calculated as ATR(14) multiplied by the stop multiplier (default 1.5). For longs, the stop is placed below the entry price by this distance. For shorts, above. This means the stop automatically adapts to the instrument's current volatility — wider stops in volatile markets, tighter stops in calm markets.
Take-Profit: Calculated as the stop distance multiplied by the reward-risk ratio (default 2.0). A 1.5 ATR stop with a 2.0 R:R produces a 3.0 ATR take-profit target.
Trailing Stop: When enabled (default), the stop is trailed upward (for longs) or downward (for shorts) using the trail ATR multiplier (default 2.0). The trail only moves in the favorable direction — it never moves against the position.
Exit Conditions
Beyond the TP/SL levels, the strategy has two additional exit conditions:
Regime Flip: If the regime changes from Trending Bull to Trending Bear (or vice versa), or enters Compression, the position is closed immediately. The thesis for the trade no longer holds.
Opposite Displacement: If strong displacement fires in the opposite direction of the trade, the position is closed. Institutional momentum has shifted against the position.
Default Strategy Properties
These are the exact values used in the strategy's Properties dialog:
Initial Capital: $100,000 — a realistic account size for the average trader
Default Quantity: 5% of equity per trade — conservative position sizing
Commission: 0.04% per trade (round-trip 0.08%) — realistic for most exchanges
Slippage: 2 ticks per order — accounts for execution delay and spread
Pyramiding: 0 — only one position at a time
Calc on Every Tick: false — entries only on bar close for realistic execution
These settings are intentionally conservative. The commission and slippage values are included to produce realistic backtesting results. Traders should adjust these values to match their specific broker/exchange conditions.
Visualization
Regime MA: The ORMA line plotted with a glow effect (crisp line + transparent wider line) colored by trend state — teal for bullish, rose for bearish, gray for neutral
ATR Bands: Upper and lower bands showing the regime breakout thresholds
SL/TP Levels: When a position is active, the stop-loss (red), take-profit (green), and entry price (gray) are plotted as horizontal lines
Gradient Candles: Candles colored by the confluence score — transitioning from bearish rose (low score) to bullish teal (high score)
Session Background: Subtle amber tint when an active session is in progress
10-Row Dashboard
Row 1: Header — "SOVEREIGN EXECUTION"
Row 2: Regime — TREND LONG / TREND SHORT / COMPRESSED / TRANSITIONAL
Row 3: Displacement — BULL DISP / BEAR DISP / NEUTRAL
Row 4: Session — ASIA / LONDON / NEW YORK / OFF-SESSION
Row 5: Confluence — Score value + bias classification
Row 6: Volatility — EXPANDING / COMPRESSED / NORMAL
Row 7: Position — LONG / SHORT / FLAT
Row 8: Entry — Entry price when in a trade
Row 9: Stop — Current stop-loss level
Row 10: Target — Current take-profit level
Input Parameters
Execution Parameters:
Risk Per Trade % (default 1.5) — percentage of equity risked per trade
Reward:Risk Ratio (default 2.0) — take-profit as multiple of stop distance
ATR Stop Multiplier (default 1.5) — stop distance as ATR multiple
Use Trailing Stop (default on), Trail ATR Multiplier (default 2.0)
Entry Filters:
Confluence Threshold Long (default 60) — minimum score for long entries
Confluence Threshold Short (default 40) — maximum score for short entries
Require Active Session (default on)
Require FVG Confluence (default off)
Regime Cipher Parameters:
Adaptive MA Length (default 27), ATR Length (default 14), ATR Factor (default 1.05)
Base MA type (default EMA, options: RMA/SMA/EMA/WMA/HMA/DEMA/TEMA)
Displacement Parameters:
BB Length (20), BB Multiplier (2.0), CCI Length (23), ROC Length (50)
Displacement Smoothing (default 5)
Session Filter (UTC):
Asia Start/End (0/8), London Start/End (8/14), NY Start/End (14/21)
Strategy Limitations and Compromises
Every strategy involves design compromises. Here are the key ones for Sovereign Execution:
Selectivity vs Frequency: The multi-gate filter approach produces fewer trades than single-indicator strategies. On some instruments/timeframes, the strategy may go days without a signal. This is by design — it prioritizes quality over quantity — but it means the strategy needs sufficient historical data to produce a meaningful sample size.
Regime Lag: The ORMA-based regime classification has inherent lag. It will not catch the exact top or bottom of a trend. The strategy enters after the trend is confirmed, which means it misses the first portion of moves.
Session Filter Limitation: The UTC-based session filter works well for forex and indices but may need adjustment for instruments with non-standard trading hours. Crypto traders may want to disable the session filter entirely.
Single Timeframe Execution: While the confluence score incorporates HTF data, entries and exits are executed on the chart's timeframe. Very fast timeframes (1m) may produce noisy signals despite the filters.
Backtesting Caveats: All backtesting results are historical and do not guarantee future performance. The strategy uses calc_on_every_tick=false and barstate.isconfirmed to produce realistic entries, but real-world execution will always differ from backtesting due to slippage, partial fills, and latency.
No Guarantee of Profitability: This strategy is a systematic framework, not a profit guarantee. Market conditions change, and strategies that worked historically may underperform in different regimes.
Recommended Usage
Use on liquid instruments (major forex pairs, large-cap stocks, major crypto) for most reliable signals
Test on the 15m to 4H timeframe range — these provide enough bars for the regime and displacement engines while maintaining meaningful session context
Ensure the backtest produces at least 100 trades for statistical significance before drawing conclusions
Adjust commission and slippage to match your specific broker/exchange
Consider the strategy as one component of a broader trading plan, not a standalone system
Originality Statement
This strategy is original in its multi-layer filter architecture. While individual components (moving averages, momentum oscillators, session filters) are established concepts, this strategy is justified because:
It synthesizes five independent analytical engines (regime classification, displacement measurement, session timing, imbalance confluence, multi-TF scoring) into a unified execution framework where ALL must align for entry
The ORMA-based regime engine uses a volatility-dampened, outlier-resistant moving average with ATR bands — not a standard MA crossover
The displacement engine normalizes three oscillators and blends them with volume-weighted candle body analysis for institutional-grade momentum confirmation
The confluence score combines five analytical dimensions with HTF weighting, producing a quantitative bias gate rather than a subjective assessment
Multiple exit conditions (regime flip, opposite displacement, trailing stop, TP/SL) provide layered risk management beyond simple stop-loss
The strategy uses realistic default settings (commission, slippage, position sizing) and documents all Properties values for transparent backtesting
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss and is not suitable for all investors.
Backtesting results shown are historical and do not guarantee future performance. The results of a single backtest run do not constitute proof that the strategy will be profitable in the future. Market conditions change, and strategies that performed well historically may underperform or lose money in different market environments.
The default settings (commission 0.04%, slippage 2 ticks, 5% equity per trade, $100,000 initial capital) are designed to produce realistic results. Users should verify these match their trading conditions and adjust accordingly.
Always use proper risk management. Never risk more than you can afford to lose. Consider consulting with a qualified financial advisor before making investment decisions. The author is not responsible for any losses incurred from using this strategy.
-Made with passion by officialjackofalltrades
策略

指标

Quantum Scalper 5MWelcome to the Quantum Scalper 5M, a highly precise, confluence-based reversal indicator designed specifically for lower timeframes. Unlike traditional indicators that generate signals on simple crossovers, this system is built on a strict "Touch & Reject" logic, filtering out market noise and focusing only on high-probability reversal zones.
🔥 Core Philosophy: The Power of Triple Confluence
A signal is ONLY generated when price simultaneously interacts with three independent technical components. It must "touch/wick" the extreme levels of all three components and strictly "close" inside them, confirming a valid rejection.
Support & Resistance (SR): Dynamic lookback-based structure levels.
Bollinger Bands (BB): Volatility-based standard deviation bands.
Quantum Trend Flow (QTF): An advanced ATR and Volatility-based dynamic channel.
⚙️ Key Features:
Strict "Touch & Reject" Logic: Buy signals appear only when the low of the candle touches the lower BB, lower QTF, and Support, while the close remains above them. Sell signals require the exact opposite at resistance zones.
Dynamic Risk/Reward (RR) Boxes: Once a signal is triggered, the indicator automatically draws a real-time Risk/Reward box (Default: 0.5% SL, 1.0% TP). These boxes dynamically extend to the right with every new candle until the Take Profit or Stop Loss is explicitly hit, acting as a visual trade journal on your chart!
Multi-Timeframe (MTF) Trend Filter: An optional built-in higher timeframe filter ensures you are only taking scalp trades in the direction of the macro trend.
Momentum & Trend Dashboard: A clean, non-intrusive dashboard displays the current MTF Trend status, RSI-based Momentum strength (Strong/Weak Bull or Bear), and the last active signal.
Clean Visuals: By default, the complex bands and channels are hidden to keep your chart perfectly clean. You only see what matters: Price action, strict signals, and your dynamic RR boxes.
📊 How to Use:
Timeframe: Optimized for 5-minute (5M) and 15-minute (15M) charts.
Markets: Highly effective on Crypto, Forex, and Indices with decent volatility.
Risk Management: The dynamic RR boxes are visual guides. Always use hard stop losses in your actual exchange terminal.
Disclaimer: This script is for educational purposes only and does not constitute financial advice. Always backtest strategies before using real funds. 指标

Smart Reversal EntrySmart Reversal Entry
Smart Reversal Entry is an open-source reversal-entry indicator built around one specific analytical idea:
after a short, directional three-candle expansion move, the first confirmed candle closing back in the opposite direction can create a structured reversal-entry opportunity when it appears in the correct EMA context.
This script is not designed to mark every bullish or bearish candle, and it is not intended to behave like a generic trend-following overlay, a standard candlestick-pattern indicator, or a broad “signal generator” that reacts to every small reversal. Its purpose is to measure short-term directional exhaustion in a standardized way, filter that move through an EMA context, require close-confirmed reversal behavior, and then project a fixed-risk trade structure directly on the chart for analysis and review.
The script also includes an internal background optimizer and review tables so users can compare how the same reversal framework behaves under different parameter combinations. These review tools are included to support study and comparison, not to imply future performance.
OPEN-SOURCE NOTE
This script is published open-source so users can inspect the logic directly, verify what the script is doing, and adapt parts of the workflow for their own research if they wish.
Even though the code is open, this description is intentionally detailed because many TradingView users do not read Pine Script. The goal is for a user to understand what the script does, how it works, why its parts belong together, and how it may be used in practice without having to study the code line by line.
OVERVIEW
At a high level, the script does six things:
1. It measures whether the last three candles produced a directional move large enough to matter in pip terms.
2. It checks whether price is positioned on the correct side of a selected EMA filter.
3. It requires the current candle to close in the opposite direction as confirmation of a possible reversal.
4. It maps a fixed stop-loss and a selectable take-profit multiple directly onto the chart.
5. It tracks projected trade outcomes and summarizes them in a review table and a daily PnL table.
6. It runs a hidden background optimizer over multiple EMA and move-threshold combinations so the user can compare the current settings to an internal parameter sweep.
The script is therefore meant to function as a complete reversal-entry and review framework rather than as a single-purpose candle-pattern marker.
CORE IDEA
Many reversal-style tools identify isolated candles or basic candlestick formations, but they do not standardize the market context around them.
This script is built around the idea that a reversal signal becomes more meaningful when three specific things happen together:
1. price has already made a clear short-term directional move,
2. that move is large enough to matter relative to the chosen pip structure,
3. and the next confirmed candle closes back in the opposite direction while price remains on the correct side of an EMA filter.
The model is intentionally narrow.
It does not try to identify every turning point in the market.
It does not try to classify broad market structure.
It does not use discretionary support and resistance interpretation.
It does not rely on vague candle descriptions such as “looks weak” or “looks exhausted”.
Instead, it defines reversal-entry conditions using a fixed sequence:
first measure a three-candle directional push,
then filter it using EMA context,
then require an opposite close-confirmed candle,
then project a standardized risk framework,
then review the resulting projected outcomes over time.
That narrower focus is the main reason this script exists in its current form.
WHY THIS SCRIPT IS NOT A SIMPLE MASHUP
This script combines multiple components, but they are not included simply to place more features into one publication.
Each component has a specific function inside the same analytical workflow:
- The EMA filter defines directional context.
- The three-candle move measurement defines whether a short-term push is large enough to qualify.
- The reversal candle confirmation defines the actual entry trigger.
- The pip-based stop-loss and RR framework standardize trade projection.
- The summary and daily review tables organize projected outcomes into a readable review structure.
- The internal optimizer compares the same reversal logic across multiple hidden EMA and move-threshold combinations.
These layers are interdependent.
Without the three-candle move measurement, the script would react to many small candles that do not represent meaningful short-term expansion.
Without the EMA filter, the script would lose its directional context and become a more generic reversal marker.
Without the close-confirmed reversal candle, the script would identify momentum but not the actual reversal-entry moment.
Without the risk projection layer, the user would still need to manually draw the entry, stop, and target after every signal.
Without the review tables, the user would have less organized feedback when reviewing results under the selected settings.
Without the internal optimizer, the user would see only the current configuration and not how the same logic behaves across a broader parameter range.
For that reason, the script is intended as a single reversal-entry framework, not as a random collection of unrelated features.
WHAT THE SCRIPT DOES
The script identifies reversal-entry setups using a strict, rule-based structure.
Long setup requirements:
- price must be above the selected EMA,
- the prior three candles must all be bearish,
- the combined bearish move across that sequence must reach the minimum pip threshold,
- the current candle must close bullish.
Short setup requirements:
- price must be below the selected EMA,
- the prior three candles must all be bullish,
- the combined bullish move across that sequence must reach the minimum pip threshold,
- the current candle must close bearish.
When a valid signal appears, the script can:
- place a BUY or SELL label,
- project a fixed stop loss in pips,
- project a take-profit level using the selected RR multiple,
- draw TP/SL boxes,
- draw an entry line,
- keep historical projected trades visible for later review,
- summarize projected outcomes in a summary table,
- summarize recent daily projected behavior in a daily PnL table.
The script also evaluates an internal optimizer in the background. That optimizer tests multiple EMA lengths and minimum-move combinations using the same reversal logic and displays the best-performing parameter combination inside the summary table over the shared analysis window.
HOW THE SCRIPT WORKS
1) EMA CONTEXT FILTER
The script uses a single EMA as a directional filter.
For long setups:
price must close above the selected EMA.
For short setups:
price must close below the selected EMA.
This does not turn the script into a pure trend-following system. Instead, it acts as a directional context filter so that reversal entries are only considered when price is positioned on the chosen side of the EMA.
In practical terms, the EMA filter is used to reduce context-free reversal signals. A bullish candle appearing after a bearish push is not enough by itself. The script still wants price to be trading above the selected EMA for longs, and below it for shorts.
2) THREE-CANDLE DIRECTIONAL MOVE MEASUREMENT
The script looks at the three candles immediately before the signal candle.
For a long setup:
those three candles must all be bearish.
For a short setup:
those three candles must all be bullish.
The script then measures the total directional move across that sequence in pip terms.
For long setups, it calculates the bearish move from the open of the first candle in the sequence to the close of the third bearish candle.
For short setups, it calculates the bullish move from the open of the first candle in the sequence to the close of the third bullish candle.
That move must be at least as large as the user-defined “Minimum 3-Candle Move (Pips)” setting.
This is one of the key parts of the script’s logic. It ensures that the setup is not based on three arbitrary candles, but on a directional push that is large enough to meet the minimum threshold selected by the user.
3) REVERSAL CANDLE CONFIRMATION
After the three-candle directional push is identified, the current candle must close in the opposite direction.
For long setups:
the current candle must close bullish.
For short setups:
the current candle must close bearish.
This requirement is intentionally strict. The script does not treat intrabar movement or unfinished candles as a valid signal. Signals are confirmed only when the bar closes.
This matters because a reversal that looks valid intrabar can disappear by the close. By waiting for close confirmation, the script reduces premature signal marking.
4) COOLDOWN FILTER
The script includes a cooldown period between signals.
Once a signal has fired, a new signal is not allowed until a defined number of bars has passed. In the current implementation, that cooldown is handled internally.
The purpose of this filter is to reduce signal clustering and prevent the chart from producing multiple nearby entries from the same short-term market behavior.
5) PIP-BASED RISK PROJECTION
When a valid signal appears, the script creates a projected trade framework using:
- entry at the signal close,
- a fixed stop-loss distance in pips,
- a take-profit level based on the selected risk/reward multiple.
This makes the projection logic standardized across signals.
For long setups:
- stop loss is placed below entry,
- take profit is placed above entry.
For short setups:
- stop loss is placed above entry,
- take profit is placed below entry.
The script can draw:
- entry line,
- TP box,
- SL box,
- BUY / SELL label,
- TP / SL hit labels.
This projection layer is not meant to claim that a setup will succeed. Its purpose is to reduce manual chart annotation and make the behavior of the signal model easier to inspect after the fact.
6) SAME-BAR TP/SL PRIORITY RULE
The script uses a strict and conservative rule when both target and stop would appear to be touched on the same bar after entry:
if TP and SL are both reached on the same bar, SL takes priority.
This is an important implementation detail because it directly affects projected statistics. It makes the review logic more conservative and avoids optimistic ambiguity when bar data alone cannot determine exact intrabar order.
7) SHARED ANALYSIS WINDOW
The script uses a shared analysis window internally.
Projected results and optimizer comparisons are evaluated over a rolling historical range rather than over the full unlimited chart history. This keeps the internal review process more controlled and makes the optimizer comparison consistent inside the same defined lookback window.
8) INTERNAL OPTIMIZER
One of the script’s more advanced components is the internal optimizer.
The optimizer runs in the background and is intentionally not exposed as a user-facing optimization panel. Instead of asking the user to manually test every variation, the script internally evaluates combinations of:
- 10 EMA values,
- 10 minimum-move thresholds.
That produces 100 total internal combinations.
Each combination uses the same reversal logic:
- EMA context,
- three-candle directional sequence,
- minimum move threshold,
- opposite close-confirmed candle,
- same stop-loss and RR structure.
The optimizer then tracks projected wins, losses, net R, gross profit, and gross loss for each combination, and the summary table displays the current best combination based on the script’s internal comparison rules.
This optimizer is not intended to present a “perfect setting”. It is a comparative review aid that helps the user understand how the same reversal framework behaves across multiple hidden parameter combinations.
WHAT MAKES THIS SCRIPT ORIGINAL
This script uses familiar technical-analysis building blocks such as:
- EMA filtering,
- candle-sequence logic,
- pip-based move measurement,
- fixed stop-loss projection,
- risk/reward mapping,
- performance review tables.
Those building blocks are not original by themselves.
The originality of this script is not in inventing a completely new primitive indicator. The originality lies in how these familiar elements are arranged into one tightly defined reversal-entry workflow:
EMA context
→ three-candle directional expansion
→ minimum pip-threshold validation
→ opposite candle close confirmation
→ fixed-risk trade projection
→ on-chart review
→ internal background parameter comparison
That full sequence is the main reason this script exists as its own publication.
It is not intended to be simply another EMA filter, another candlestick marker, another TP/SL visualizer, or another optimizer dashboard. It is specifically a short-term reversal-entry framework that combines directional context, expansion measurement, confirmation logic, risk mapping, and review in one workflow.
WHAT APPEARS ON THE CHART
Depending on settings, the chart may display:
- EMA line,
- BUY labels,
- SELL labels,
- signal-bar background highlights,
- entry line,
- TP box,
- SL box,
- TP hit labels,
- SL hit labels,
- summary table,
- daily PnL table.
Users who want a cleaner chart can disable some visual layers and keep only the ones most relevant to their workflow.
HOW TO USE THE SCRIPT
A practical workflow is:
1. Add the script to a standard candlestick chart.
2. Select the EMA length you want to use as directional context.
3. Set the minimum three-candle move threshold in pips.
4. Set the pip preset correctly for the instrument, or use manual pip size if needed.
5. Choose the stop-loss distance in pips.
6. Select the RR mode used for take-profit projection.
7. Wait for a valid long or short setup to appear.
8. Use the projected entry, stop, and target structure as a chart-analysis framework rather than as a blind instruction.
9. Review projected trade behavior in the summary table and daily table.
10. Compare your selected settings with the optimizer’s best internal combination, but do not treat the optimizer output as a guaranteed best future configuration.
This script is best understood as a structured decision-support and reversal-review tool, not as a self-sufficient trading system.
SETTINGS REFERENCE
Signal Settings
- EMA Length: sets the EMA used as the directional filter.
- Minimum 3-Candle Move (Pips): defines how large the directional three-candle move must be before a reversal candle can qualify.
Pip Settings
- Pip Preset: selects a predefined pip-size interpretation for common instrument types.
- Manual Pip Size: allows direct control when the selected symbol needs a custom pip conversion.
Risk Management
- Stop Loss (Pips): sets the fixed stop-loss distance in pip units.
- Take Profit RR: sets the projected target multiple relative to the stop-loss distance.
Visual Settings
- Show Buy/Sell Labels: shows or hides the signal labels.
- Highlight Signal Bars: adds background color to signal bars.
- Show Entry Line: shows or hides the projected entry line.
- Show TP/SL Hit Labels: controls whether projected outcomes are labeled.
- Show TP Hit Labels: controls TP hit labels specifically.
- Show SL Hit Labels: controls SL hit labels specifically.
Summary Table
- Show Summary Table: enables or disables the main review table.
- Table Position: sets the table location.
- Table Text Size: controls summary-table text size.
Daily PnL Table
- Show Daily PnL Table: enables or disables the daily review table.
- Daily Table Position: sets the daily table location.
- Daily Table Text Size: controls daily-table text size.
INTERNAL LOGIC NOTES
The current code also includes internal settings that are not exposed as user-facing optimization controls. These include:
- signal cooldown,
- shared analysis window,
- maximum stored closed-trade visuals,
- hidden optimizer activation,
- internal optimizer parameter combinations.
These internal elements exist to keep the public interface simpler while still allowing the script to maintain consistent review behavior in the background.
IMPORTANT PRACTICAL NOTE ON PIP SIZE
The script uses pip-based calculations for:
- the minimum three-candle move,
- stop-loss distance,
- take-profit distance,
- optimizer comparison logic.
Because of that, correct pip interpretation is extremely important.
If signals appear too frequent, too rare, too compressed, or visually inconsistent for the instrument being analyzed, the first setting to verify is Pip Preset or Manual Pip Size.
This matters especially for:
- gold symbols,
- 5-digit forex symbols,
- JPY forex pairs,
- indices and CFD-style instruments,
- custom broker symbols with unusual decimal formatting.
LIMITATIONS AND SHORTCOMINGS
This script has important limitations:
- It is a short-term reversal model, not a full market-structure engine.
- It only evaluates one specific reversal pattern based on a three-candle directional push and an opposite close-confirmed candle.
- It does not use support/resistance structure, volume profile, or discretionary context.
- It relies on pip conversion, so poor pip settings can distort signal behavior.
- The internal optimizer compares parameter combinations only inside the defined shared analysis window.
- The optimizer output is a comparative review tool, not a guarantee that the best historical combination will remain best in future market conditions.
- Projected results depend on the script’s own simplified outcome logic.
- If TP and SL are both touched on the same bar, SL is prioritized by design, which makes the logic more conservative but also affects outcome statistics.
- Historical projected trades and review metrics are chart-based review aids, not proof of tradable real-world execution.
- No reversal-entry model can remove all false signals or all regime-dependent behavior.
For those reasons, the script should be used as a structured analysis and review framework, not as a promise of future profitability.
WHO THIS SCRIPT MAY BE USEFUL FOR
This script may be useful for traders who:
- want a rules-based short-term reversal-entry model,
- want EMA-based directional context,
- want a minimum expansion threshold before a reversal is allowed,
- want fixed-risk trade projection on the chart,
- want review tables for projected outcomes,
- want background comparison of multiple EMA and move-threshold combinations.
It may be less suitable for traders who:
- want a broad trend-following system,
- want a discretionary support/resistance engine,
- want a multi-pattern candlestick library,
- want a fully automated strategy with no outside confirmation,
- want outcome metrics interpreted as live performance promises.
DISCLAIMER
This script is provided for educational and informational purposes only.
It does not constitute financial, investment, or trading advice.
Market conditions change, historical behavior does not guarantee future results, and users should perform their own analysis, validation, and risk management before using the script in live decision-making. 指标

指标

Omega Ratio AnalysisThe Omega ratio was introduced by Keating and Shadwick in 2002 as a superior alternative to the Sharpe ratio.
Sharpe assumes normally distributed returns (ignores fat tails and might be unrealistic sometimes), Omega captures the entire return distribution. This makes it ideal for analyzing crypto, leveraged ETFs, and any assets with asymmetric returns or fat tails (I love fat tails, as part of my investment strategy of course).
Quant funds prefer Omega because it answers:
"How much do I gain above my threshold versus how much do I lose below it?"
This aligns with actual investment goals better than abstract volatility penalties.
THE MATH
Omega ratio is defined as:
Ω(MAR) = (Sum of returns above MAR) / (Sum of returns below MAR)
Where MAR (Minimum Acceptable Return) is your return threshold .
The indicator calculates this using log returns
for better statistical properties:
Log returns: ln(price / previous price)
For time series mode: Loops through lookback period, summing gains above threshold and losses below threshold
For curve mode: Calculates Omega at multiple MAR levels (from 0% to max) to reveal distribution shape
Values above 1.0 indicate gains exceed losses. For example, Ω = 1.5 means $1.50 in gains for every $1.00 in losses relative to your target.
Time Series Mode
Tracks Omega over time using a rolling window (default 252 bars). Shows color-coded performance zones: Excellent (>1.5), Good (>1.0), Caution (>0.7), Poor (<0.7). Set your annual return target and the indicator converts it to per-bar threshold. Monitor whether you're beating your goal over time.
Omega Curve Mode
It plots Omega versus different MAR thresholds to reveal the return distribution shape. A steep declining curve indicates normal distribution with thin tails. A gentle slope indicates fat tails with asymmetric upside. Compare your asset against any benchmark (default QQQ) to see which has better tail performance at different return thresholds.
HOW TO USE
For Long-Term Investors:
Use 252-bar lookback on daily charts (1 year) or use even weekly charts. Set your annual target around 10% (historical market average). If Omega stays above 1.0, you're beating your goal. Check the curve periodically - a gentle slope means the asset has upside potential beyond average returns.
For Comparing Assets:
Plot two assets (like SPY vs TQQQ). If the leveraged version has a gentler curve slope, it captures more explosive upside days. The crossover point shows which MAR threshold favors which asset. Asset above benchmark at high MAR levels = better for aggressive return goals.
For Regime Detection:
Use shorter periods (60-90 bars) for curve calculation. When curves become steeper, returns are normalizing and momentum may be fading. When curves flatten or become more convex, fat tails are developing (bullish regime forming).
APPLICATIONS
Asset Selection: Screen for asymmetric opportunities by comparing curve shapes. Gentle slopes indicate lottery-ticket upside potential.
Leverage Analysis: Quantify whether leveraged ETFs justify the volatility by comparing curves at high MAR levels. If 3x ETF curve significantly above 1x at MAR = 2%, leverage premium exists.
Risk Assessment: Steep curves = predictable, capped returns. Gentle curves = volatile but moonshot potential. Choose based on your risk tolerance and return goals.
Performance vs Benchmark: Compare your holdings against sector ETFs or market indices. If your curve is below benchmark at your target MAR, you're not getting paid for the extra risk.
PRACTICAL TIPS
Curve Period: Use 60-90 bars to see asymmetry during volatile markets. Longer periods (252-1000 bars) average out cycles and produce linear curves.
MAR Increments: Keep at 50 for smooth curves. Only lower for performance reasons.
Multi-Symbol Analysis: Compare growth stocks vs QQQ, value vs SPY, crypto vs BTC, or leveraged vs unleveraged to quantify relative risk-reward.
Reading the X-Axis: MAR shows per-bar percentage. On daily charts, 0.5% MAR means "only days with +0.5%+ returns count as wins." On monthly charts, 3% MAR means "only months with +3%+ returns count as wins."
My indicator is perfect for quant investors who want institutional-grade risk analysis. Goes beyond simple volatility metrics to reveal the true shape of return distributions.
PRACTICAL EXAMPLE:
This chart compares SPY versus TQQQ (3x leveraged Nasdaq ETF) on monthly bars over 252 months (21 years), spanning the 2008 crisis, 2020 crash, and multiple market cycles.
Both start at Omega = 1.50 (identical overall risk-adjusted returns), but the curve shapes reveal how those returns were achieved:
SPY (in cyan): Steep drop from 1.5 to near zero by MAR = 1.7% per month. Returns cluster tightly around average - predictable but limited upside.
TQQQ (in red): Gradual slope maintaining Omega = 0.35 even at MAR = 8.7% per month. Shows fat right tail with many explosive +20-40% months that SPY never sees.
Key insight is: For aggressive goals (20-30% annual), SPY's Omega drops to 0.5 (losses dominate) while TQQQ stays above 1.0 (gains exceed losses). TQQQ offers better odds at high return targets, but requires surviving -60 to -90% bear market drawdowns.
This demonstrates how curves reveal distribution characteristics that price charts or Sharpe ratios miss - specifically the asymmetric upside advantage of leveraged products for long-term holders with high risk tolerance.
Let me know if you have questions or suggestions:
- Henrique Centieiro
指标

指标

Profit Loss Display UniversalUniversal Profit Loss Display
is a chart overlay for quickly visualizing projected reward, risk, and reference levels from the current price.
The script lets you select:
- one main profit target
- one main stop loss level
- four additional reference sources
The sources can be any element of another indicator displayed on the current chart (using the TradingView's source parameter.
**How it works**
The indicator compares each selected level to the current price and estimates the move using your configured position base. This makes it useful for planning trades around fixed targets, stops, VWAPs, pivots, bands, or any custom level source.
For each active level, it displays the move from current price as price points, dollar value, or both. The profit target and stop loss also get dedicated value labels, and the script calculates a live reward-to-risk ratio in `R` format.
**Key features**
- Configurable `input.source` levels for profit target, stop loss, and 4 extra references
- Display mode selector: `Price Points`, `$ Value`, or `Both`
- Automatic leverage detection by asset class, with manual override
- Dollar projection based on chunk size and leverage
- Clean on-chart labels that only appear when a source is different from `close`
- Reward-to-risk ratio displayed directly on the chart
- Bottom-right info table showing active chunk size and leverage
**Best use cases**
- Pre-trade reward/risk planning
- Visual target and stop mapping
- Comparing multiple nearby levels from current price
- Quick dollar impact estimation without manual calculation
**Notes**
This is a planning helper, not a strategy or execution tool. Dollar projections do not include fees, spread, slippage, funding, or partial exits.
---------------------------------------------------------------------------------------------------------------------
**How To Use**
1. Add the indicator to your chart.
2. Set your main `Profit Target` and `Stop Loss Limit`.
These are the two primary levels used for the projected profit/loss labels and the `R` ratio.
3. Optionally assign `Extra Source 1-4`.
Use these for additional levels you want to monitor, such as VWAPs, pivots, moving averages, bands, or custom plotted values.
4. Choose your `Display Mode`.
- `Both` shows price distance and dollar value
- `Price Points` shows only the raw move from current price
- `$ Value` shows only the projected dollar impact
5. Set your `Chunk Size`.
This is the base position size used in the calculation.
6. Set `Leverage X`.
- Leave it at `0` to use automatic leverage by asset class
Automatic Leverage Rules
If Leverage X is set to 0, the script uses these defaults:
crypto: 5
forex: 30
futures: 10
cfd: 10
stock: 5
index: 20
fund: 5
anything else: 10
A small table in the bottom-right corner shows the active chunk size and leverage.
- Enter a manual value if you want to override auto leverage
7. Turn `Show Labels?` on or off as needed.
**What You Will See**
- A source label for the profit target
- A source label for the stop loss
- Source labels for up to 4 extra levels
- A dedicated profit value label
- A dedicated stop-loss value label
- An `R:x.x` reward-to-risk ratio label
- A bottom-right table showing current chunk size and leverage
**Important Behavior**
- Labels only appear when the selected source is different from `close`
- `close` acts as the default “off” state for any source input
- Labels are updated on the latest bar only
- The ratio is based on distance from current price to target and stop
**Practical Example**
If you are planning a trade:
- set `Profit Target` to your take-profit level
- set `Stop Loss Limit` to your invalidation level
- set `Chunk Size` to your standard trade allocation
- choose a leverage value or leave auto mode enabled
- use the extra sources for nearby confluence or reaction zones
This gives you an immediate view of:
- potential upside
- potential downside
- reward-to-risk ratio
- relative distance to other important levels
**Notes**
This script is a visual planning tool. It does not place trades and does not account for fees, slippage, spread, funding, or scaling in and out.
指标

策略

Ultimate Risk Manager: Fixed Dollar Risk & Position CalculatorAre you tired of manually calculating your position size to risk exactly $10, $50, or $100 per trade?
The Ultimate Risk Manager is a professional-grade position sizing and risk calculation tool designed for day traders and scalpers. Instead of guessing your position size and hoping your stop loss doesn't wipe out your account, this tool allows you to set a Fixed Dollar Risk. It tells you exactly how much margin to use so that if your Stop Loss is hit, you lose exactly the amount you planned for.
Perfect for futures and leverage traders on any exchange (MEXC, Binance, Bybit, etc.).
✨ Key Features:
🎯 Strict Risk Management: Input your desired risk (e.g., $2.00) and the calculator outputs the exact "Total Position" and "Margin" required based on your Stop Loss distance.
🤖 Auto Long/Short Detection: No need to toggle directions. The script automatically detects if it's a LONG or SHORT based on where you place your Stop Loss relative to your Entry.
💸 Built-in Fee Calculator: Input your exchange's round-trip fee percentage. The table calculates your exact fee cost and provides your Net Profit (after fees) at your Take Profit target.
🧹 Ultra-Minimalist Chart Visuals: Say goodbye to indicator lines cutting through your price action. This script uses short, clean floating markers for Entry, SL, and TP that sit neatly in the empty space on the right side of your chart.
🎨 Customizable UI: Includes a Light/Dark theme toggle, adjustable table positioning, and sliders to push the floating chart markers exactly where you want them.
🛠️ How to Use:
Open the indicator Settings (Double-click the table).
Under "Trade Setup," enter your Fixed Risk ($), Leverage, and Exchange Fee (%).
Under "Price Levels," use the Price Picker tool (the target icon) to click your desired Entry, Stop Loss, and Take Profit levels directly on the chart.
Look at the dashboard table! Copy the highlighted Yellow Margin Number and type it directly into your exchange's order box.
Protect your capital and trade like a professional by keeping your risk mathematically consistent on every single trade. 指标

Position and Risk CalculatorFirst of all I'd like to thank @Famouzx
for the use of his original code. I had this idea for a long time - but, had no idea on how to execute it. I found a reference to his script and it had some elements that showed me how this could be completed.
This script does two main things:
First, the user can input their account size and risk amount and the script will calculate the amount of size to enter the trade. The user can also choose the size they desire and it will calculate the risk amount.
Second, the script will project TP levels based upon input from the user. There are two take profit level types: The first is TP levels based upon risk/reward and the distance between the SL and Entry. The second is that the user can use a "measured move" to project TP levels.
There are options for the levels to show or not show the following: Ticks, USD, R/R, and the security price for that level.
For my use case I use several different elements of this script:
1) I use the Entry and SL locations to provide me with the correct size to enter the trade.
2) I use the Measured Move elements to set take profit levels.
3) Within the Take Profit levels I use Fibonacci levels.
In the next image one can see how this works.
1) The Stop and Entry are set. In the settings the risk is set at .4% of 50k and that is $200 which is shown in the table on the top right. The correct size for that amount of risk is shown on the Entry line as 2 Micros (this is NQ Futures).
2) The Measured move begins at the top of the last impulse up and ends on the first mail reversal that dips into the "golden zone" and is rejected. This is the distance is used to calculate the TP levels and the Fib levels.
3) The RR, USD profit, and ticks are calculated using the SL and Entry.
So, the trader can calculate the entry size and R/R before entering the trade.
In this example we can see that there was profit taking at the 0.618 (an almost guaranteed level to reach in most of these type of setups). And, you can see that is an important level as this trade finished at the 1.618 level.
In the next image the trader is not using the measured move or fib take profit levels. They are only using the SL and TP. But, the Risk is still $200 and the script shows that 2 micro contracts should be used. In settings the user could make the TP levels transparent if they only wanted to use the size calculator.
This video demonstrate how to use the script.
Please DM me if any bugs are found. 指标

指标

Wedge Pattern [UAlgo]Overview
Wedge Pattern is a chart overlay that detects rising and falling wedge formations using strict pivot based rules and a validation engine that enforces classic technical analysis requirements. The script builds two trendlines from confirmed pivot highs and pivot lows, verifies that both boundaries converge toward an apex in the future, and ensures that price remains contained within the wedge until a valid breakout occurs.
The indicator is designed to reduce subjective pattern drawing. It requires a minimum number of touches on each boundary, checks that no candle closes outside the wedge during formation, and treats the wedge as invalid if price breaks in the wrong direction or if the two boundaries collapse into each other. When a breakout is confirmed, the script updates the wedge label and can project a measured target based on the initial wedge width.
This tool is meant for traders who want automatic, rules driven wedge identification with clear status states, breakout confirmation, and optional target projection on the chart.
🔹 Features
1) Pivot Based Wedge Construction
The script identifies swing highs and swing lows using pivot detection. Each confirmed pivot is stored as a Coordinate containing bar index and price. When enough pivots exist, the script forms:
An upper trendline from the earliest required pivot high to the most recent pivot high
A lower trendline from the earliest required pivot low to the most recent pivot low
Pivot Left and Pivot Right control swing sensitivity. Larger values produce fewer but stronger pivots. Smaller values react faster but may include minor swings.
2) Minimum Touch Requirement Per Boundary
A wedge is only considered valid when there are at least a user defined number of pivot touches for both the upper and lower boundary. This aligns with standard charting practice where two points draw a line, but three points validate it.
Min Touches per Line controls the minimum pivot count required before a wedge can be formed.
3) Objective Wedge Type Classification
After calculating slopes for the upper and lower trendlines, the script classifies wedge type using slope direction and relative steepness:
Rising wedge requires both slopes to be positive and the lower slope to be steeper than the upper slope
Falling wedge requires both slopes to be negative and the upper slope to be steeper than the lower slope in the negative direction
This ensures convergence and distinguishes wedges from simple channels.
4) Apex Projection and Future Convergence Rule
The wedge apex is computed as the intersection point of the two trendlines. A valid wedge requires the apex index to be in the future. This confirms that the boundaries are converging and that the pattern is not already expired at detection time.
5) Mandatory Containment Rule During Formation
A core validation rule enforces that no closes occur outside the wedge boundaries while the wedge is forming. If any close is above the upper boundary or below the lower boundary by at least one tick, the candidate wedge is rejected. This prevents premature breakouts from being treated as valid patterns.
6) Live Updating Boundaries
Once a wedge becomes active, the script extends both boundary lines on every bar by updating their end coordinates using the trendline slope. This keeps the wedge aligned with current time and allows breakout checks to remain accurate.
7) Breakout Detection and Status Labeling
The script defines correct breakouts by wedge type:
Rising wedge is bearish biased, so a valid breakout is a close below the lower boundary
Falling wedge is bullish biased, so a valid breakout is a close above the upper boundary
When a valid breakout occurs, the wedge status is updated to BROKEOUT and the label color reflects direction. If price breaks the opposite boundary, or if boundaries collapse, the wedge is marked FAILED.
8) Target Projection Using Measured Move
If enabled, the script projects a target line after breakout. The target distance is based on the wedge width measured near the start of the pattern, then projected from the breakout boundary:
For a rising wedge breakdown, the target is placed below the lower boundary by the measured width
For a falling wedge breakout, the target is placed above the upper boundary by the measured width
A target label prints the projected price level.
🔹 Calculations
1) Pivot Detection and Coordinate Storage
Swing points are detected using symmetric pivots:
float ph = ta.pivothigh(high, INPUT_PIVOT_LEFT, INPUT_PIVOT_RIGHT)
float pl = ta.pivotlow(low, INPUT_PIVOT_LEFT, INPUT_PIVOT_RIGHT)
Confirmed pivots are stored using the pivot right offset so the bar index matches where the pivot actually formed:
if not na(ph)
pivot_highs.push(Coordinate.new(bar_index - INPUT_PIVOT_RIGHT, ph))
if not na(pl)
pivot_lows.push(Coordinate.new(bar_index - INPUT_PIVOT_RIGHT, pl))
Arrays are capped to keep only recent pivot history.
2) Trendline Construction and Slope Calculation
When enough pivots exist, the script picks the earliest required touch and the most recent touch for both highs and lows, then builds trendlines:
Coordinate p1h = pivot_highs.get(pivot_highs.size() - MIN_TOUCHES_PER_LINE)
Coordinate pNh = pivot_highs.get(pivot_highs.size() - 1)
Trendline tl_up = Trendline.new(p1h, pNh, 0.0, na)
tl_up.slope := tl_up.calc_slope()
Slope is defined as:
(this.end.price - this.start.price) / (this.end.index - this.start.index)
The same logic is used for the lower trendline from pivot lows.
3) Wedge Type Rules
Wedge type is derived from slope sign and convergence:
Rising wedge:
if tl_up.slope > 0 and tl_lo.slope > 0 and tl_lo.slope > tl_up.slope
w_type := 1
Falling wedge:
if tl_up.slope < 0 and tl_lo.slope < 0 and tl_up.slope < tl_lo.slope
w_type := 2
This ensures both boundaries move in the same direction while converging.
4) Apex Index Calculation
The apex index is calculated from the line intersection of the two trendlines:
float apex_x = (y2 - y1 + m1 * x1 - m2 * x2) / (m1 - m2)
math.round(apex_x)
A candidate wedge is only accepted if apex index is greater than the current bar index.
5) Containment Validation Using Close Prices
The script checks each bar from the wedge start to the current bar to ensure that close remains within boundaries:
float up_p = this.upper.get_price_at(i)
float lo_p = this.lower.get_price_at(i)
float c_p = close
if c_p > up_p + syminfo.mintick or c_p < lo_p - syminfo.mintick
violated := true
If violated is true, the wedge is rejected.
6) Live Boundary Update and Breakout Checks
For active wedges, end coordinates are updated each bar using the projected boundary price:
line.set_y2(w.upper.line_id, w.upper.get_price_at(bar_index))
line.set_y2(w.lower.line_id, w.lower.get_price_at(bar_index))
Breakout checks use the current close against projected boundary prices:
bool b_up = close > u_p
bool b_dn = close < l_p
Correct breakout:
Rising wedge requires b_dn
Falling wedge requires b_up
Invalidation:
Rising wedge fails if b_up
Falling wedge fails if b_dn
Any wedge fails if upper boundary price is less than or equal to lower boundary price
7) Target Projection
Measured width is derived from the initial distance between boundaries near the start of the wedge, then projected from the breakout side:
float m = math.abs(w.upper.start.price - w.lower.get_price_at(w.upper.start.index))
float t = w.is_rising ? l_p - m : u_p + m
The target line and label are drawn forward a fixed number of bars to provide a clear reference after breakout. 指标

指标

Gold/Spread AlgoXAUUSD 1-Minute RSI Scalping Strategy – Mean-Reversion with Fixed Exits
This open-source strategy is a high-frequency, counter-trend scalping system designed specifically for **XAUUSD (Gold)** on the 1-minute timeframe.
Core Logic
The strategy uses classic RSI(14) to identify short-term overextension:
- Long entry when RSI drops below oversold (default 30) → expects quick snap-back
- Short entry when RSI rises above overbought (default 70) → expects quick pullback
Entries are taken only when flat (no pyramiding). Exits are fixed in pips and set immediately on entry:
- Take Profit: +10 pips (0.10 in XAUUSD price)
- Stop Loss: –5 pips (0.05 in XAUUSD price)
- Built-in Risk:Reward = 1:2
This fixed structure gives the system positive mathematical expectancy even with moderate win rates (≈55–65% before costs), provided gold continues to exhibit frequent mean-reversion behavior on 1-minute charts.
Why this simple approach?
Gold is one of the most volatile and momentum-driven instruments on very short timeframes. Pure RSI extremes often capture quick exhaustion moves after news spikes, order flow imbalances, or session transitions — especially during London/NY overlap. Fixed pip targets prevent over-optimization and mimic real broker execution more closely than dynamic trailing or percentage-based exits.
Important Realism & Backtesting Notes
To produce non-misleading results, use these settings when publishing/testing:
- Initial Capital: $10,000 – $30,000 (realistic retail size)
- Position sizing: fixed 0.10–0.30 lots or 1–3% equity per trade
- Commission: 5–8 USD round-turn per lot (typical ECN/raw-spread)
- Slippage: 3–8 ticks (≈0.03–0.08 in price) — gold spreads widen during volatility
- Minimum dataset: 12–36 months of 1-minute data (aim for 800–2000+ trades)
- Risk per trade: usually 0.5–1.5% with defaults — never exceeds sustainable levels
Results vary significantly:
- Strongest in ranging or mildly trending sessions
- Weaker during strong directional moves or major news (NFP, FOMC, geopolitics)
- Expect drawdowns during trending regimes — this is NOT a trend-following system
Visual & Dashboard Elements
- RSI line + fill (blue/orange background) + overbought/oversold zones
- BUY/SELL triangles at entry points
- Professional top-right dashboard showing:
- Net Profit & Loss
- Total Trades / Win Rate / Profit Factor
- Winning / Losing Trades
- Current RSI value
- Position status (LONG / SHORT / FLAT)
- TP:SL ratio
Alerts
- 🟢 LONG ENTRY – RSI oversold
- 🔴 SHORT ENTRY – RSI overbought
How to Use
1. Apply to XAUUSD 1-minute chart only
2. Use realistic commission/slippage in Strategy Tester
3. Trade primarily during London & New York sessions for best liquidity
4. Avoid major news events or widen stops manually
5. Forward-test on demo for 2–3 months minimum
6. Always size conservatively — never risk more than 1–2% per trade
Publish Recommendation
- Use a clean chart: only this strategy, no extra indicators/drawings
- Show realistic tester results with commission/slippage applied
- Screenshot during active session with visible entry signals + dashboard
Educational tool — open-source for learning and testing. Not financial advice. Gold 1-minute trading is extremely volatile and carries high risk of loss. Trade responsibly. 策略

指标

Risk & Lot Calculator PanelFXMANS Risk & Lot Panel
Smart Risk Management Tool for TradingView
- Overview
FXMANS Risk & Lot Panel is a lightweight and professional risk management tool designed to help traders calculate position size (lot) and take-profit levels directly on the chart, without cluttering the screen.
The panel is displayed as a minimal table in the top-right corner of the chart and automatically adapts to the currently opened symbol.
This tool focuses on clarity, precision, and usability, making it suitable for scalpers, day traders, and swing traders.
- Key Features
Automatic Direction Detection
The script can automatically determine BUY or SELL direction based on:
Entry Price
Stop Loss Price
Logic:
Stop Loss below Entry → BUY
Stop Loss above Entry → SELL
Manual override is available if auto direction is disabled.
Risk-Based Lot Size Calculation
Calculates position size based on:
User-defined risk amount in USD
Distance between Entry and Stop Loss
Symbol-specific tick size and point value
Ensures consistent risk management across all markets.
Automatic Take Profit (RR Based)
Take Profit is calculated automatically using a predefined Risk / Reward (RR) ratio.
Supports both BUY and SELL scenarios.
- Symbol-Aware Calculation
Uses TradingView’s built-in symbol properties:
syminfo.mintick
syminfo.pointvalue
Works correctly on:
Forex
Indices
Metals
Crypto
- Minimal & Non-Intrusive UI
Small, fixed panel located at the top-right corner
Designed to avoid covering price action
Clean FXMANS-style color palette
- Safe Panel Size Control
Panel size can be adjusted from settings:
Small
Medium
Large
Size changes are handled without modifying layout geometry, preventing UI bugs.
- How It Works
Enter your Entry Price and Stop Loss Price
Define your Risk Amount ($)
Set your desired Risk / Reward ratio
The script automatically calculates:
Trade Direction (BUY / SELL)
Lot Size
Take Profit Level
All results are displayed instantly in the panel
- Example Use Case
Risk: $100
Entry: 1.0850
Stop Loss: 1.0800
RR: 2.0
- The panel will automatically display:
Direction: BUY
Lot Size adjusted to risk exactly $100
Take Profit at 2R
- Important Notes
Entry and Stop Loss prices must be valid (greater than zero).
The tool does not place trades automatically.
Calculations are for position sizing only and may vary slightly depending on broker specifications.
- Disclaimer
This script is intended for educational and analytical purposes only.
Trading involves risk, and users are responsible for their own trading decisions.
- Ideal For
Traders who follow strict risk management rules
Forex, crypto, and index traders
Scalpers and intraday traders
Anyone who wants clean and fast position sizing on TradingView 指标

Profit Punch: Risk & Target Planner (ATR + Fixed R)Profit Punch: Risk & Target Planner (ATR + Fixed R)
This indicator is a complete trade planning tool designed to visualize your Risk (R) and Reward levels instantly. Whether you use a volatility-based strategy (ATR) or precise manual levels, this tool draws your roadmap directly on the chart.
It solves the problem of calculating "R-Multiples" manually and ensures every trade plan is consistent.
Key Features
1. Smart Risk Calculation
Auto Mode (ATR): Uses the stock's daily volatility (ATR) to automatically suggest a logical Stop Loss.
Manual Mode: Lets you type in your exact Stop Loss price (e.g., below a recent low), and the tool automatically adjusts your Profit Targets to match that specific risk.
2. Hybrid Targeting (The "Nuance")
You can set a tight manual stop but keep your profit targets based on daily volatility (ATR). This allows for "Hybrid" setups where you risk a small amount (tight stop) but aim for a standard volatility move (ATR targets).
3. Backtesting Friendly
Use the "Target Date" feature to apply the tool to any past candle. It will calculate the targets based on what the volatility was on that specific day , allowing you to accurately review past trades.
4. Clean & Customizable
Editable Labels: Rename "1R" to "Goal 1" or "Take Profit".
Clean Look: Toggle any line on/off to keep your chart simple.
Timeframe Independent: Calculations are always anchored to Daily data for consistency, even if you are viewing a 5-minute chart.
How to Use
Step 1: Add to Chart. The lines will appear on the latest bar by default.
Step 2: Set Entry. In Settings, check "Use Manual Entry" to type your exact buy price, or leave unchecked to use the closing price.
Step 3: Set Stop. Choose "Auto (ATR)" for a volatility-based stop, or "Manual Price" to type in your specific stop level.
Step 4: Visualize. The tool draws your 1R, 3R, 5R, and 7R targets instantly.
Settings Guide
Risk Factor: Multiplier for the ATR calculation (Default is 1.5).
Target Base: Choose whether profit targets are multiples of your Stop Distance (Classic) or Fixed ATR (Volatility).
Custom Labels: Change the text displayed on the chart (e.g., "Safe Exit" instead of "1R").
Who is this for?
This tool is built for swing traders, educators, and anyone who uses "R-Multiples" (Risk Units) to manage their portfolio. It is especially useful for creating consistent trade plan screenshots. 指标

Risk & Reward Position PlannerDescription
This script is a trade architecture tool designed to help traders calculate position sizes and visualize risk-reward ratios dynamically on the chart. It focuses on functional precision and clean aesthetics, offering two distinct visual styles: "Cyber" for modern high-tech charts and "Classic" for a traditional look.
Key Features
Interactive Setup: Upon adding the script or resetting, it prompts you to click directly on the chart to set your Entry and Stop Loss levels.
Dynamic Position Sizing: Calculates the total risk in currency (USD) based on your custom unit size.
Multi-Target Planning: Visualizes four customizable Take Profit targets based on specific RR ratios.
Cyber UI Aesthetics: Full control over colors, neon glow effects, and horizontal alignment to fit any chart layout.
Comprehensive Data: Displays price, percentage distance, currency risk, and RR ratios at a single glance.
User Guide (How to use)
To ensure the most efficient workflow, here are the essential steps for operating the tool:
Setting a New Trade (Resetting)
If you change your symbol or want to plan a completely new trade, you can clear the current setup and trigger the interactive selection again:
Right-click on the indicator in the chart OR click the three dots (...) next to the indicator name in the legend.
Select "Reset Points".
The indicator will prompt you to click two new points on the chart: first for the Entry, then for the Stop Loss.
Moving Entry and Stop Loss
Move the mouse over the line of the Entry or the StopLoss and grab the grip of the line to move it up or down. Drop it to the price you want to set. 指标

Smart Trader, Episode 02, by Ata Sabanci | Battle of Candles ⚠️ CRITICAL: READ BEFORE USING ⚠️
This indicator is 100% VOLUME-BASED and requires Lower Timeframe (LTF) intrabar data for accurate calculations. Please understand the following limitations before using:
📊 DATA ACCURACY LEVELS:
• 1T (Tick) — Most accurate, real volume distribution per tick
• 1S (1 Second) — Reasonably accurate approximation
• 15S (15 Seconds) — Good approximation, longer historical data available
• 1M (1 Minute) — Rough approximation, maximum historical data range
⚠️ BACKTEST & REPLAY LIMITATIONS:
• Replay mode results may differ from live trading due to data availability
• For longer back test periods, use higher LTF settings (15S or 1M)
• Not all symbols/exchanges support tick-level data
• Crypto and Forex typically have better LTF data availability than stocks
💡 A NOTE ON TOOLS:
Successful trading requires proper tools. Higher TradingView plans provide access to more historical intrabar data, which directly impacts the accuracy of volume-based calculations. More precise volume data leads to more reliable signals. Consider this when evaluating your trading infrastructure.
📌 OVERVIEW
Smart Trader Episode 02: Battle of Candles is an advanced educational indicator that combines multiple analysis engines to help traders identify market scenarios and understand market dynamics. This is NOT financial advice or a trading signal service — it's a learning tool designed to help you understand how institutional traders might interpret price action.
The indicator integrates 7 major analysis engines into a unified dashboard, providing real-time insights into volume flow, trend structure, market phases, and potential trade setups.
⚡ KEY FEATURES
🎯 16-Pattern Scenario Engine
Automatically detects and classifies market conditions into 16 distinct scenarios, from strong continuation moves to potential reversals and traps.
💰 Trade Advisor Panel
Aggregates all signals into actionable suggestions with confidence levels, suggested entry/SL/TP levels, and risk/reward calculations.
📊 Volume Engine
Splits volume into buy/sell components using either Geometry (candle shape) or Intrabar (LTF data) methods for precise delta analysis.
📈 CVD (Cumulative Volume Delta)
Tracks the running total of buying vs selling pressure to identify accumulation, distribution, and divergences.
🎯 Stop-Hunt Detection
Identifies potential stop-hunt patterns where price sweeps liquidity levels before reversing.
📐 Pure Structure Trend Engine
Zero-lag trend detection based on swing highs/lows (HH/HL/LH/LL) without any lagging indicators.
⚡ Effort vs Result Analysis
Measures energy spent (volume) versus ground taken (price movement) to detect stalls, breakthroughs, and exhaustion.
🎯 SCENARIO ENGINE — 16 Market Patterns
The Scenario Engine analyzes multiple factors (candle anatomy, volume, forces, CVD, wick analysis) to classify each candle into one of 16 scenarios:
Continuation Scenarios (1-3)
1. ⚔️ STRONG MOVE — Big body candle (>60%) with volume confirming direction. Indicates strong momentum continuation.
2. 🛡️ ABSORPTION — One side attacks but the other absorbs the pressure. Price holds despite volume. Continuation expected in the absorbing side's favor.
3. 📉 PULLBACK — Small move against the trend with low volume. Indicates a healthy retracement before trend continuation.
Reversal Scenarios (4-6, 13-16)
4. 💥 REJECTION — Big wick (>40%) with small body and high volume. Price was rejected
at a level, potential reversal.
5. 🪤 TRAP — Pin direction disagrees with delta. Extreme wick size. Looks bullish/bearish but the opposite may happen.
6. 😫 EXHAUSTION — High energy spent (volume) but low ground taken (price movement). Both sides active but momentum fading.
13. 🔄 CVD BULL DIV — Price falling but CVD rising. Hidden buying detected (accumulation). Potential bullish reversal.
14. 🔄 CVD BEAR DIV — Price rising but CVD falling. Hidden selling detected (distribution). Potential bearish reversal.
15. 🎯 STOP HUNT BULL — Shorts were liquidated below support. Price swept liquidity and reversed. Expect bullish move.
16. 🎯 STOP HUNT BEAR — Longs were liquidated above resistance. Price swept liquidity and reversed. Expect bearish move.
Range/Stalemate Scenarios (7-9)
7. ⚖️ DEADLOCK — Market in balance. Force ratio between 0.4-0.6. Low volume. No side winning.
8. 🔥 BATTLE — High volume fight in a range. Both sides attacking. Wicks on both ends of candle.
9. 🎯 WAITING — Building phase with quiet volume. Market is preparing but no trigger yet. Wait for breakout.
Pre-Breakout Scenarios (10-12)
10. 🚀 BULL SETUP — Buyers accumulating in a building phase. Positive delta building. Bullish pressure growing.
11. 💣 BEAR SETUP — Sellers distributing in a building phase. Negative delta building. Bearish pressure growing.
12. ⚡ BREAKOUT — Price at boundary with strong candle and volume supporting. Imminent breakout expected.
💰 TRADE ADVISOR ENGINE
The Trade Advisor aggregates all signals from the different engines into a single actionable output. It uses a weighted scoring system:
Scoring Weights:
• Scenario Signal: 30%
• Trend Alignment: 20%
• CVD Momentum: 15% + Divergence Bonus
• Pin Forces: 15%
• Liquidity Sweep: 12%
• Stop-Hunt Detection: 10%
• Effort vs Result: 10%
Possible Actions:
• ⏳ WAIT — Edge not strong enough (stay patient)
• 🟢 LONG ENTRY — Buyers have strong advantage + signals align
• 🔴 SHORT ENTRY — Sellers have strong advantage + signals align
• ⚠️ CLOSE LONG/SHORT — Position at risk (reversal/trend flip)
• 🛑 STOP LOSS — Price hit risk threshold
• 💰 TAKE PROFIT — Target threshold reached
📊 EXTENDED INFO PANEL (Detailed Explanations)
The Extended Info panel is hidden by default (toggle: Show Extended Info in settings). It provides detailed metrics that feed into the main engines:
CVD ANALYSIS
What is CVD?
Cumulative Volume Delta (CVD) is the running total of Buy Volume minus Sell Volume. It reveals the underlying buying/selling pressure that may not be visible in price alone.
CVD Value & Slope:
• ↗ Rising: CVD increasing = net buying pressure (bullish)
• ↘ Falling: CVD decreasing = net selling pressure (bearish)
• → Flat: No clear pressure direction
Accumulation vs Distribution:
• Accumulation %: Shows buying pressure strength (0-100). High accumulation with CVD rising = strong bullish bias.
• Distribution %: Shows selling pressure strength (0-100). High distribution with CVD falling = strong bearish bias.
Divergence Alerts:
• ⚠️ BULLISH DIVERGENCE: Price falling but CVD rising. Hidden buying = potential reversal UP.
• ⚠️ BEARISH DIVERGENCE: Price rising but CVD falling. Hidden selling = potential reversal DOWN.
WICK ANALYSIS
Wick Torque:
Torque measures the "rotational force" from wicks. It's calculated from wick length, volume, and body efficiency.
• Positive Torque (Bullish): Bottom wick power dominates. Buyers defended lower prices.
• Negative Torque (Bearish): Top wick power dominates. Sellers defended higher prices.
• ⚡ High Torque (>30): Strong signal, significant wick rejection occurred.
Stop-Hunt Detection:
The engine detects when price has likely swept stop-losses clustered at key levels:
• Stop Hunt Risk %: Likelihood score (0-100). Above 55% = confirmed hunt.
• "Shorts hunted": Price swept below support, liquidating shorts, expect bounce UP.
• "Longs hunted": Price swept above resistance, liquidating longs, expect drop DOWN.
LIQUIDITY SWEEPS
This section appears only when a liquidity sweep is detected. The engine monitors for price sweeping recent highs/lows and then reversing:
• 🎯 LIQUIDITY SWEPT ABOVE: Price broke recent highs but closed back below. Longs trapped, expect DOWN.
• 🎯 LIQUIDITY SWEPT BELOW: Price broke recent lows but closed back above. Shorts trapped, expect UP.
POWER BALANCE
The Power Balance meter shows the real-time strength comparison between buyers and sellers.
Force Ratio:
• 0% = Complete seller dominance
• 50% = Perfect balance
• 100% = Complete buyer dominance
Visual Bar:
• Left side (▓): Bear territory
• Right side (▓): Bull territory
• The bar is smoothed over recent history to reduce noise.
EFFORT vs RESULT
This section measures the efficiency of price movement relative to volume expended.
Energy:
How much volume was spent relative to the average. Energy > 1.0x means above-average volume activity.
Ground:
How much price movement occurred relative to average range. Ground > 1.0x means above-average price movement.
STALL Warning:
A STALL is detected when high energy is spent but low ground is taken (high effort, low result). This often indicates institutional battle, exhaustion, or imminent reversal.
MARKET PHASE
The Phase Engine classifies the current market regime:
RANGE : No clear trend. Price confined to middle of channel. Low ADX. Balanced forces. Trade breakouts with caution.
BUILDING : Compression/preparation phase. Channel tightening or boundary penetration without follow-through. Watch for breakout direction.
TRENDING : Active directional move. Clear slope, good efficiency, price on trending side of channel. Favor pullback entries.
Strength:
0-100% score combining slope, volume validity, and force/efficiency filters.
Bars: How many candles the current phase has persisted.
TRACK RECORD (Validation Panel)
Enable with Show Validation Panel in settings. This section tracks the historical accuracy of scenario predictions:
Accuracy: Percentage of validated predictions that were correct.
Best/Worst Scenario: Shows which scenarios have the highest and lowest accuracy on the current symbol.
Recent Signals: Last 5 predictions with their outcomes. ✓ = correct, ✗ = wrong, ⏳ = pending validation.
⚙️ SETTINGS GUIDE
📊 Volume Analysis
Volume Calculation: Choose Geometry (estimates from candle shape) or Intrabar (precise LTF data).
Intrabar Resolution: LTF for precise mode. Try 1S, 15S, or 1T. Must be lower than chart timeframe.
History Depth: Candles stored in memory (5-50). Higher = more context, slower.
Memory Lookback: Bars for moving averages and Z-scores (10-100).
🏷️ Market Phase
Range Zone Width: How much of channel center is considered "range" (0.1-0.8).
Trend Sensitivity: Minimum slope to detect trending. Lower = more sensitive.
Min Episode Length: Minimum bars before phase can change. Prevents flickering.
🎯 Scenarios
Min Confidence to Show: Only display scenarios above this confidence level (30-90).
Bars to Validate: How many bars to wait before checking if prediction was correct.
Success Move %: Minimum price movement to consider prediction successful.
💰 Trade Advisor
Min Confidence for Entry: Minimum confidence to suggest a trade entry (50-90).
Default Risk %: Stop loss distance as % of price (0.5-5.0).
Min Risk/Reward: Minimum acceptable R:R ratio (1.0-5.0).
🔔 ALERT CONDITIONS
The indicator provides the following alert conditions you can configure:
• 🟢 LONG Entry Signal
• 🔴 SHORT Entry Signal
• ⚠️ Close LONG Signal
• ⚠️ Close SHORT Signal
• 🛑 STOP LOSS Alert
• 💰 Take Profit Alert
• 🚨 High Urgency Signal
⚠️ IMPORTANT DISCLAIMER
EDUCATIONAL TOOL ONLY
This indicator is designed for educational purposes to help users identify different market scenarios and understand how various signals might be interpreted.
The Trade Advisor is NOT a recommendation to buy, sell, or invest.
• Past performance does not guarantee future results
• All trading involves risk of loss
• The creator is not a licensed financial advisor
• Always do your own research (DYOR)
• Consult a qualified financial advisor before making any investment decisions
By using this indicator, you acknowledge that you understand these risks and accept full responsibility for your trading decisions.
指标
