OPEN-SOURCE SCRIPT

Account Guardian

230
Account Guardian: Dynamic Risk/Reward Overlay

Introduction

Account Guardian is an open-source indicator for TradingView designed to help traders evaluate trade setups before entering positions. It automatically calculates Risk-to-Reward ratios based on market structure, displays visual Stop Loss and Take Profit zones, and provides real-time position sizing recommendations.

The indicator addresses a fundamental question every trader should ask before entering a trade: "Does this setup make mathematical sense?" Account Guardian answers this question visually and numerically, helping traders avoid impulsive entries with poor risk profiles.

Core Functionality

Account Guardian performs four primary functions:

  • Detects swing highs and swing lows to identify logical stop loss placement levels
  • Calculates Risk-to-Reward ratios for both long and short setups in real-time
  • Displays visual SL/TP zones on the chart for immediate trade planning
  • Computes position sizing based on your account size and risk tolerance


The goal is to provide traders with instant feedback on whether a potential trade meets their minimum risk/reward criteria before committing capital.

How It Works

Swing Detection

The indicator uses pivot point detection to identify recent swing highs and swing lows on the chart. These swing points serve as logical areas for stop loss placement:

  • For Long Trades: The most recent swing low becomes the stop loss level. Price breaking below this level would invalidate the bullish thesis.
  • For Short Trades: The most recent swing high becomes the stop loss level. Price breaking above this level would invalidate the bearish thesis.


The swing detection lookback period is configurable, allowing you to adjust sensitivity based on your trading timeframe and style.

It automatically adjusts the tp and sl when it is applied to your chart so it is always moving up and down!
istantanea


Risk/Reward Calculation

Once swing levels are identified, the indicator calculates:

  • Entry Price: Current close price (where you would enter)
  • Stop Loss: Recent swing low (for longs) or swing high (for shorts)
  • Risk: Distance from entry to stop loss
  • Take Profit: Entry plus (Risk × Target Multiplier)
  • R:R Ratio: Reward divided by Risk


The R:R ratio is then evaluated against your configured thresholds to determine if the setup is valid, marginal, or poor.

Visual Elements

SL/TP Zones

When enabled, the indicator draws colored boxes on the chart showing:

  • Red Zone: Stop Loss area - the region between your entry and stop loss
  • Green/Gold/Red Zone: Take Profit area - colored based on R:R quality


The color coding provides instant visual feedback:
  • Green: R:R meets or exceeds your "Good R:R" threshold (default 3:1)
  • Gold: R:R meets minimum threshold but below "Good" (between 2:1 and 3:1)
  • Red: R:R below minimum threshold - setup should be avoided


Swing Point Markers

Small circles mark detected swing points on the chart:
  • Green circles: Swing lows (potential support / long SL levels)
  • Red circles: Swing highs (potential resistance / short SL levels)


Dashboard Panel

The dashboard in the top-right corner displays comprehensive trade planning information:

  • R:R Row: Current Risk-to-Reward ratio for long and short setups
  • Status Row: VALID, OK, BAD, or N/A based on R:R thresholds
  • Stop Loss Row: Exact price level for stop loss placement
  • Take Profit Row: Exact price level for take profit placement
  • Pos Size Row: Recommended position size based on your risk parameters
  • Risk $ Row: Dollar amount at risk per trade


Position Sizing Logic

The indicator calculates position size using the formula:

Position Size = Risk Amount / Risk per Unit

Where:
  • Risk Amount = Account Size × (Risk Percentage / 100)
  • Risk per Unit = Entry Price - Stop Loss Price


For example, with a $10,000 account risking 1% per trade ($100), if your entry is at 100 and stop loss at 98 (risk of 2 per unit), your position size would be 50 units.

Input Parameters

Swing Detection:
  • Swing Lookback: Number of bars to look back for pivot detection (default: 10). Higher values find more significant swing points but may be slower to update.
  • Target Multiplier: Multiplier applied to risk to calculate take profit distance (default: 2). A value of 2 means TP is 2× the distance of SL from entry.


Risk/Reward Thresholds:
  • Minimum R:R: Minimum acceptable Risk-to-Reward ratio (default: 2.0). Setups below this show as "BAD" in red.
  • Good R:R: Threshold for excellent setups (default: 3.0). Setups at or above this show as "VALID" in green.


Account Settings:
  • Account Size ($): Your trading account size in dollars (default: 10,000). Used for position sizing calculations.
  • Risk Per Trade (%): Percentage of account to risk per trade (default: 1.0%). Professional traders typically risk 0.5-2% per trade.


Display:
  • Show SL/TP Zones: Toggle visibility of the colored zone boxes on chart (default: enabled)
  • Show Dashboard: Toggle visibility of the information panel (default: enabled)
  • Analyze Direction: Choose to analyze Long only, Short only, or Both directions (default: Both)


How to Use This Indicator

Basic Workflow:

  • Add the indicator to your chart
  • Configure your account size and risk percentage in the settings
  • Set your minimum and good R:R thresholds based on your trading rules
  • Look at the dashboard to see current R:R for potential long and short entries
  • Only consider trades where the status shows "VALID" or at minimum "OK"
  • Use the displayed SL and TP levels for your order placement
  • Use the position size recommendation to determine lot/contract size


Interpreting the Dashboard:

  • VALID (Green): Excellent setup - R:R meets your "Good" threshold. This is the ideal scenario for taking a trade.
  • OK (Gold): Acceptable setup - R:R meets minimum but isn't optimal. Consider taking if other confluence factors align.
  • BAD (Red): Poor setup - R:R below minimum threshold. Avoid this trade or wait for better entry.
  • N/A (Gray): Cannot calculate - usually means no valid swing point detected yet.


Best Practices:

  • Use this indicator as a filter, not a signal generator. It tells you IF a trade makes sense, not WHEN to enter.
  • Combine with your existing entry strategy - use Account Guardian to validate setups from other analysis.
  • Adjust the swing lookback based on your timeframe. Lower timeframes may need smaller lookback values.
  • Be honest with your account size input - accurate position sizing requires accurate inputs.
  • Consider the target multiplier carefully. Higher multipliers mean larger potential reward but lower probability of hitting TP.


Alerts

The indicator includes four alert conditions:

  • Good Long Setup: Triggers when long R:R reaches or exceeds your "Good R:R" threshold
  • Good Short Setup: Triggers when short R:R reaches or exceeds your "Good R:R" threshold
  • Bad Long Setup: Triggers when long R:R falls below your minimum threshold
  • Bad Short Setup: Triggers when short R:R falls below your minimum threshold


These alerts can help you monitor multiple charts and get notified when favorable setups appear.

Technical Implementation

The indicator is built using Pine Script v6 and includes:

  • Pivot-based swing detection using ta.pivothigh() and ta.pivotlow()
  • Dynamic box drawing for visual SL/TP zones
  • Table-based dashboard for clean information display
  • Color-coded visual feedback system
  • Persistent variable tracking for swing levels


Code Structure:

Pine Script®
// Swing Detection float swingHi = ta.pivothigh(high, swingLen, swingLen) float swingLo = ta.pivotlow(low, swingLen, swingLen) // R:R Calculation for Long float longSL = recentSwingLo float longRisk = entry - longSL float longTP = entry + (longRisk * targetMult) float longRR = (longTP - entry) / longRisk // Position Sizing float riskAmount = accountSize * (riskPct / 100) float posSize = riskAmount / longRisk


Limitations

  • The indicator uses historical swing points which may not always represent optimal SL placement for your specific strategy
  • Position sizing assumes you can trade fractional units - adjust accordingly for instruments with minimum lot sizes
  • R:R calculations assume linear price movement and don't account for gaps or slippage
  • The indicator doesn't predict price direction - it only evaluates the mathematical viability of a setup
  • Swing detection has inherent lag due to the lookback period required for pivot confirmation


Recommended Settings by Trading Style

Scalping (1-5 minute charts):
  • Swing Lookback: 5-8
  • Target Multiplier: 1-2
  • Minimum R:R: 1.5
  • Good R:R: 2.0


Day Trading (15-60 minute charts):
  • Swing Lookback: 8-12
  • Target Multiplier: 2
  • Minimum R:R: 2.0
  • Good R:R: 3.0


Swing Trading (4H-Daily charts):
  • Swing Lookback: 10-20
  • Target Multiplier: 2-3
  • Minimum R:R: 2.5
  • Good R:R: 4.0


Why Risk/Reward Matters

Many traders focus solely on win rate, but profitability depends on the combination of win rate AND risk/reward ratio. Consider these scenarios:

  • 50% win rate with 1:1 R:R = Breakeven (before costs)
  • 50% win rate with 2:1 R:R = Profitable
  • 40% win rate with 3:1 R:R = Profitable
  • 60% win rate with 1:2 R:R = Losing money


Account Guardian helps ensure you only take trades where the math works in your favor, even if you're wrong more often than you're right.

Disclaimer


This indicator is provided for educational and informational purposes only. It is not intended as financial, investment, trading, or any other type of advice or recommendation.

Trading involves substantial risk of loss and is not suitable for all investors. The calculations provided by this indicator are based on historical price data and mathematical formulas that may not accurately predict future price movements.

Position sizing recommendations are estimates based on user inputs and should be verified before placing actual trades. Always consider factors such as leverage, margin requirements, and broker-specific rules when determining actual position sizes.

The Risk-to-Reward ratios displayed are theoretical calculations based on swing point detection. Actual trade outcomes will vary based on market conditions, execution quality, and other factors not captured by this indicator.

Past performance does not guarantee future results. Users should thoroughly test any trading approach in a demo environment before risking real capital. The authors and publishers of this indicator are not responsible for any losses or damages arising from its use.

Always consult with a qualified financial advisor before making investment decisions.

Declinazione di responsabilità

Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.