OPEN-SOURCE SCRIPT

Superior-Range Bound Renko - Strategy - 11-29-25 - SignalLynx

84
Superior-Range Bound Renko Strategy with Advanced Risk Management Template

Signal Lynx | Free Scripts supporting Automation for the Night-Shift Nation 🌙

1. Overview

Welcome to Superior-Range Bound Renko (RBR) — a volatility-aware, structure-respecting swing-trading system built on top of a full Risk Management (RM) Template from Signal Lynx.

Instead of relying on static lookbacks (like “14-period RSI”) or plain MA crosses, Superior RBR:

Adapts its range definition to market volatility in real time

Emulates Renko Bricks on a standard, time-based chart (no Renko chart type required)

Uses a stack of Laguerre Filters to detect genuine impulse vs. noise

Adds an Adaptive SuperTrend powered by a small k-means-style clustering routine on volatility

Under the hood, this script also includes the full Signal Lynx Risk Management Engine:

A state machine that separates “Signal” from “Execution”

Layered exit tools: Stop Loss, Trailing Stop, Staged Take Profit, Advanced Adaptive Trailing Stop (AATS), and an RSI-style stop (RSIS)

Designed for non-repainting behavior on closed candles by basing execution-critical logic on previous-bar data

We are publishing this as an open-source template so traders and developers can leverage a professional-grade RM engine while integrating their own signal logic if they wish.

2. Quick Action Guide (TL;DR)

Best Timeframe:
4 Hours (H4) and above. This is a high-conviction swing-trading system, not a scalper.

Best Assets:
Volatile instruments that still respect market structure:
Bitcoin, Ethereum, Gold (XAUUSD), high-volatility Forex pairs (e.g., GBPJPY), indices with clean ranges.

Strategy Type:
Volatility-Adaptive Trend Following + Impulse Detection.
It hunts for genuine expansion out of ranges, not tiny mean-reversion nibbles.

Key Feature:
Renko Emulation on time-based candles.
We mathematically model Renko Bricks and overlay them on your standard chart to define:

“Equilibrium” zones (inside the brick structure)

“Breakout / impulse” zones (when price AND the impulse line depart from the bricks)

Repainting:
Designed to be non-repainting on closed candles.
All RM execution logic uses confirmed historical data (no future bars, no security() lookahead). Intrabar flicker during formation is allowed, but once a bar closes the engine’s decisions are stable.

Core Toggles & Filters:

Enable Longs and Shorts independently

Optional Weekend filter (block trades on Saturday/Sunday)

Per-module toggles: Stop Loss, Trailing Stop, Staged Take Profits, AATS, RSIS

3. Detailed Report: How It Works
A. The Strategy Logic: Superior RBR

Superior RBR builds its entry signal from multiple mathematical layers working together.

1) Adaptive Lookback (Volatility Normalization)

Instead of a fixed 100-bar or 200-bar range, the script:

Computes ATR-based volatility over a user-defined period.

Normalizes that volatility relative to its recent min/max.

Maps the normalized value into a dynamic lookback window between a minimum and maximum (e.g., 4 to 100 bars).

High Volatility:
The lookback shrinks, so the system reacts faster to explosive moves.

Low Volatility:
The lookback expands, so the system sees a “bigger picture” and filters out chop.

All the core “Range High/Low” and “Range Close High/Low” boundaries are built on top of this adaptive window.

2) Range Construction & Quick Ranges

The engine constructs several nested ranges:

Outer Range:

rangeHighFinal – dynamic highest high

rangeLowFinal – dynamic lowest low

Inner Close Range:

rangeCloseHighFinal – highest close

rangeCloseLowFinal – lowest close

Quick Ranges:
“Half-length” variants of those, used to detect more responsive changes in structure and volatility.

These ranges define:

The macro box price is trading inside

Shorter-term “pressure zones” where price is coiling before expansion

3) Renko Emulation (The Bricks)

Rather than using the Renko chart type (which discards time), this script emulates Renko behavior on your normal candles:

A “brick size” is defined either:

As a standard percentage move, or

As a volatility-driven (ATR) brick, optionally inhibited by a minimum standard size

The engine tracks a base value and derives:

brickUpper – top of the emulated brick

brickLower – bottom of the emulated brick

When price moves sufficiently beyond those levels, the brick “shifts”, and the directional memory (renkoDir) updates:

renkoDir = +2 when bricks are advancing upward

renkoDir = -2 when bricks are stepping downward

You can think of this as a synthetic Renko tape overlaid on time-based candles:

Inside the brick: equilibrium / consolidation

Breaking away from the brick: momentum / expansion

4) Impulse Tracking with Laguerre Filters

The script uses multiple Laguerre Filters to smooth price and brick-derived data without traditional lag.

Key filters include:

LagF_1 / LagF_W: Based on brick upper/lower baselines

LagF_Q: Based on HLCC4 (high + low + 2×close)/4

LagF_Y / LagF_P: Complex averages combining brick structures and range averages

LagF_V (Primary Impulse Line):
A smooth, high-level impulse line derived from a blend of the above plus the outer ranges

Conceptually:

When the impulse line pushes away from the brick structure and continues in one direction, an impulse move is underway.

When its direction flips and begins to roll over, the impulse is fading, hinting at mean reversion back into the range.

5) Fib-Based Structure & Swaps

The system also layers in Fib levels derived from the adaptive ranges:

Standard levels (12%, 23.6%, 38.2%, 50%, 61%, 76.8%, 88%) from the main range

A secondary “swap” set derived from close-range dynamics (fib12Swap, fib23Swap, etc.)

These Fibs are used to:

Bucket price into structural zones (below 12, between 23–38, etc.)

Detect breakouts when price and Laguerre move beyond key Fib thresholds

Drive zSwap logic (where a secondary Fib set becomes the active structure once certain conditions are met)

6) Adaptive SuperTrend with K-Means-Style Volatility Clustering

Under the hood, the script uses a small k-means-style clustering routine on ATR:

ATR is measured over a fixed period

The range of ATR values is split into Low, Medium, High volatility centroids

Current ATR is assigned to the nearest centroid (cluster)

From that, a SuperTrend variant (STK) is computed with dynamic sensitivity:

In quiet markets, SuperTrend can afford to be tighter

In wild markets, it widens appropriately to avoid constant whipsaw

This SuperTrend-based oscillator (LagF_K and its signals) is then combined with the brick and Laguerre stack to confirm valid trend regimes.

7) Final Baseline Signals (+2 / -2)

The “brain” of Superior RBR lives in the Baseline & Signal Generation block:

Two composite signals are built: B1 and B2:

They combine:

Fib breakouts

Renko direction (renkoDir)

Expansion direction (expansionQuickDir)

Multiple Laguerre alignments (LagF_Q, LagF_W, LagF_Y, LagF_Z, LagF_P, LagF_V)

They also factor in whether Fib structures are expanding or contracting.

A user toggle selects the “Baseline” signal:

finalSig = B2 (default) or B1 (alternate baseline)

finalSig is then filtered through the RM state machine and only when everything aligns, we emit:

+2 = Long / Buy signal

-2 = Short / Sell signal

0 = No new trade

Those +2 / -2 values are what feed the Risk Management Engine.

B. The Risk Management (RM) Engine

This script features the Signal Lynx Risk Management Engine, a proprietary state machine built to separate Signal from Execution.

Instead of firing orders directly on indicator conditions, we:

Convert the raw signal into a clean integer (Fin = +2 / -2 / 0)

Feed it into a Trade State Machine that understands:

Are we flat?

Are we in a long or short?

Are we in a closing sequence?

Should we permit re-entry now or wait?

Logic Injection / Template Concept:

The RM engine expects a simple integer:

+2 → Buy

-2 → Sell

Everything else (0) is “no new trade”

This makes the script a template:

You can remove the Superior RBR block

Drop in your own logic (RSI, MACD, price action, etc.)

As long as you output +2 or -2 into the same signal channel, the RM engine can drive all exits and state transitions.

Aggressive vs Conservative Modes:

The input AgressiveRM (Aggressive RM) governs how we interpret signals:

Conservative Mode (Aggressive RM = false):

Uses a more filtered internal signal (AF) to open trades

Effectively waits for a clean trend flip / confirmation before new entries

Minimizes whipsaw at the cost of fewer trades

Aggressive Mode (Aggressive RM = true):

Reacts directly to the fresh alert (AO) pulses

Allows faster re-entries in the same direction after RM-based exits

Still respects your pyramiding setting; this script ships with pyramiding = 0 by default, so it will not stack multiple positions unless you change that parameter in the strategy() call.

The state machine enforces discipline on top of your signal logic, reducing double-fires and signal spam.

C. Advanced Exit Protocols (Layered Defense)

The exit side is where this template really shines. Instead of a single “take profit or stop loss,” it uses multiple, cooperating layers.

1) Hard Stop Loss

A classic percentage-based Stop Loss (SL) relative to the entry price.

Acts as a final “catastrophic protection” layer for unexpected moves.

2) Standard Trailing Stop

A percentage-based Trailing Stop (TS) that:

Activates only after price has moved a certain percentage in your favor (tsActivation)

Then trails price by a configurable percentage (ts)

This is a straightforward, battle-tested trailing mechanism.

3) Staged Take Profits (Three Levels)

The script supports three staged Take Profit levels (TP1, TP2, TP3):

Each stage has:

Activation percentage (how far price must move in your favor)

Trailing amount for that stage

Position percentage to close

Example setup:

TP1:

Activate at +10%

Trailing 5%

Close 10% of the position

TP2:

Activate at +20%

Trailing 10%

Close another 10%

TP3:

Activate at +30%

Trailing 5%

Close the remaining 80% (“runner”)

You can tailor these quantities for partial scaling out vs. letting a core position ride.

4) Advanced Adaptive Trailing Stop (AATS)

AATS is a sophisticated volatility- and structure-aware stop:

Uses Hirashima Sugita style levels (HSRS) to model “floors” and “ceilings” of price:

Dungeon → Lower floors → Mid → Upper floors → Penthouse

These levels classify where current price sits within a long-term distribution.

Combines HSRS with Bollinger-style envelopes and EMAs to determine:

Is price extended far into the upper structure?

Is it compressed near the lower ranges?

From this, it computes an adaptive factor that controls how tight or loose the trailing level (aATS / bATS) should be:

High Volatility / Penthouse areas:

Stop loosens to avoid getting wicked out by inevitable spikes.

Low Volatility / compressed structure:

Stop tightens to lock in and protect profit.

AATS is designed to be the “smart last line” that responds to context instead of a single fixed percentage.

5) RSI-Style Stop (RSIS)

On top of AATS, the script includes a RSI-like regime filter:

A McGinley Dynamic mean of price plus ATR bands creates a dynamic channel.

Crosses above the top band and below the lower band change a directional state.

When enabled (UseRSIS):

RSIS can confirm or veto AATS closes:

For longs: A shift to bearish RSIS can force exits sooner.

For shorts: A shift to bullish RSIS can do the same.

This extra layer helps avoid over-reactive stops in strong trends while still respecting a regime change when it happens.

D. Repainting Protection

Many strategies look incredible in the Strategy Tester but fail in live trading because they rely on intrabar values or future-knowledge functions.

This template is built with closed-candle realism in mind:

The Risk Management logic explicitly uses previous bar data (open[1], high[1], low[1], close[1]) for the key decisions on:

Trailing stop updates

TP triggers

SL hits

RM state transitions

No security() lookahead or future-bar access is used.

This means:

Backtest behavior is designed to match what you can actually get with TradingView alerts and live automation.

Signals may “flicker” intrabar while the candle is forming (as with any strategy), but on closed candles, the RM decisions are stable and non-repainting.

4. For Developers & Modders

We strongly encourage you to mod this script.

To plug your own strategy into the RM engine:

Look for the section titled:
// BASELINE & SIGNAL GENERATION

You will see composite logic building B1 and B2, and then selecting:

baseSig = B2
altSig = B1
finalSig = sigSwap ? baseSig : altSig


You can replace the content used to generate baseSig / altSig with your own logic, for example:

RSI crosses

MACD histogram flips

Candle pattern detectors

External condition flags

Requirements are simple:

Your final logic must output:

2 → Buy signal

-2 → Sell signal

0 → No new trade

That output flows into the RM engine via finalSig → AlertOpen → state machine → Fin.

Once you wire your signals into finalSig, the entire Risk Management system (Stops, TPs, AATS, RSIS, re-entry logic, weekend filters, long/short toggles) becomes available for your custom strategy without re-inventing the wheel.

This makes Superior RBR not just a strategy, but a reference architecture for serious Pine dev work.

5. About Signal Lynx

Automation for the Night-Shift Nation 🌙

Signal Lynx focuses on helping traders and developers bridge the gap between indicator logic and real-world automation. The same RM engine you see here powers multiple internal systems and templates, including other public scripts like the Super-AO Strategy with Advanced Risk Management.

We provide this code open source under the Mozilla Public License 2.0 (MPL-2.0) to:

Demonstrate how Adaptive Logic and structured Risk Management can outperform static, one-layer indicators

Give Pine Script users a battle-tested RM backbone they can reuse, remix, and extend

If you are looking to automate your TradingView strategies, route signals to exchanges, or simply want safer, smarter strategy structures, please keep Signal Lynx in your search.

License: Mozilla Public License 2.0 (Open Source).
If you make beneficial modifications, please consider releasing them back to the community so everyone can benefit.

Exención de responsabilidad

La información y las publicaciones no pretenden ser, ni constituyen, asesoramiento o recomendaciones financieras, de inversión, de trading o de otro tipo proporcionadas o respaldadas por TradingView. Más información en Condiciones de uso.