OPEN-SOURCE SCRIPT

Flexible S/R Channels

461
🟩 Flexible S/R Channels is a visualization tool that draws curved support and resistance boundaries through user-defined anchor points. Unlike traditional trendlines and channels that force linear interpretation onto price action, this indicator captures the curved structures that markets frequently form—rounded tops and bottoms, parabolic advances and declines, arcing rallies and pullbacks. Three anchor points per curve define the shape; the indicator fits a smooth mathematical curve through these points and projects it forward. The approach is simple: draw what you see. Curved market structure that resists precise definition with traditional tools can now be rendered with mathematical accuracy.

The indicator bridges the gap between static drawing tools and programmable indicators. TradingView's arc tool draws curves but produces only visual pixels with no analytical value. Flexible S/R Channels creates live data series that integrate with other analysis tools. Four curve-fitting methods—Quadratic, Quadratic-Linear, Weighted Linear, and Natural Cubic Spline—accommodate different market structures. The curved levels naturally lend themselves to breakout and reversion strategies—applications left to the trader's discretion. The open-source code invites experimentation and customization.
ảnh chụp nhanh

💡 THEORY AND CONCEPT 💡

Traders have long relied on horizontal levels and diagonal trendlines to define support and resistance. Linear tools assume constant slope—a property rarely exhibited by actual market movement. When momentum accelerates or decelerates, price trajectories curve rather than hold to fixed angles. The resulting structures—parabolic advances during expansion phases, arcing pullbacks during consolidation, rounded formations at reversal points—represent changes in the rate of change itself. Traditional drawing tools cannot accommodate this variable geometry without sacrificing mathematical precision..

Flexible S/R Channels extends familiar support and resistance concepts into curved space. The approach is simple: draw what you see. When the eye recognizes a curved boundary in price action, this indicator provides the means to define it precisely. Three anchor points per curve—an initial point, an intermediate point, and a recent point—are all that is required. The indicator fits a smooth mathematical curve through these points and extends it forward as a projection.
ảnh chụp nhanh
This indicator represents a blend of human pattern recognition and algorithmic precision. Fully automated indicators make decisions without user input—efficient but detached from trader discretion. Manual drawing tools rely entirely on freehand skill—expressive but imprecise. Flexible S/R Channels occupies the middle ground. The trader identifies the curved structure; the algorithm renders it mathematically. The result is human insight expressed with computational accuracy—for traders who recognize curved structure in price action but lack precise tools to define it.

This projection is not a prediction. It is a visual hypothesis—a structured way of asking "if this trajectory continues, where would price be?" The underlying assumption is simple: like Newton's first law of motion, a trajectory in motion tends to continue unless acted upon by an external force. Future price action validates or invalidates the projection, just as it does with any trendline or channel.

TradingView offers an arc drawing tool for freehand curved lines, but these are purely visual—static pixels on a screen with no programmable value. Flexible S/R Channels bridges this gap. The fitted curves exist as data series that can generate alerts, trigger signals, and interact with other analysis tools. The visual drawing becomes operational structure.


🔁 CURVE METHODS 🔁

The indicator offers four curve-calculation methods, each producing different shapes suited to different market structures:
  • Quadratic — Fits a parabolic arc through the three anchor points. Best for smooth, continuous curves such as rounded tops and bottoms. It captures the natural "swing" of the market, assuming the momentum will maintain its current rate of acceleration or deceleration.

  • Quadratic-Linear — Uses a parabolic curve through the anchor points, then transitions to a straight line after the final anchor. Useful when curved structure gives way to linear trend continuation. This is the "bridge" between a turning market and a steady, directed move, preventing the projection from curving back on itself when the price begins to run.

  • Weighted Linear — Connects anchor points with straight line segments rather than a smooth curve. Suited for angular market structures with distinct inflection points. It treats the market as a series of rigid shifts, providing a clear "corridor" when the price is bouncing between sharp, diagonal levels.

  • Natural Cubic Spline — Produces the smoothest curve by minimizing abrupt directional changes. Ideal for organic, flowing market movements. It acts as a flexible spine that adapts to complex transitions without the rigid constraints of a fixed geometric shape.

ảnh chụp nhanhQuadratic Fitting: A smooth, parabolic arc defines a curved resistance boundary. By fitting a mathematical path through three anchor points, the curve captures rounded structures and arcing price action that traditional linear trendlines fail to represent.

ảnh chụp nhanhWeighted Linear Fitting: This method produces an angular, segmented path by connecting anchor points with distinct linear slopes. Unlike the continuous smoothness of a quadratic arc, the weighted linear approach creates a more jointed geometry, allowing for a precise match to market structures that exhibit sharp, localized changes in trajectory.

ảnh chụp nhanhNatural Cubic Spline Fitting: This method creates a highly fluid, elastic curve that can accommodate complex price oscillations. In this instance, the curves define a narrowing range as support and resistance converge, highlighting the volatility compression that often precedes a significant breakout or breakdown from established structures.


🖱️ HOW IT WORKS 🖱️

1️⃣Initial Setup

Unlike traditional indicators that calculate values automatically from price data, Flexible S/R Channels requires user-defined anchor points. This is intentional. The trader's eye is the pattern recognition engine—no algorithm can see the curved structure that experience and intuition reveal. The indicator waits for this input, then applies mathematical precision to render what the trader has identified.

ảnh chụp nhanhThe Recognition of Natural Structure: Effective analysis begins when a curved rhythm becomes visible within price action that traditional trendlines cannot satisfy. Identifying the specific swing highs and swing lows that define these boundaries is the first step in organizing a chart. By isolating three key pivots for resistance and three for support, the underlying framework of the market's trajectory is established, providing the necessary coordinates to accurately map the path.

ảnh chụp nhanhInteractive Setup Workflow: Upon loading, the indicator prompts for the sequential selection of six points—three swing highs and three swing lows—to serve as the raw data for the calculation. While the chart remains blank during this initial phase, the curves generate instantly once the final anchor is confirmed. These points are not permanent; they appear as interactive grips that can be dragged in real time to refine the boundaries as the market structure evolves.

The indicator prompts for six sequential selections—three for resistance, three for support. The first three selections define the resistance boundary; the final three define support. This sequential grouping is distinct from zigzag-style selection patterns. Within each group, clicking order is flexible—the algorithm automatically sorts points chronologically, allowing traders to select visually prominent pivots in whatever sequence feels natural.

ảnh chụp nhanhStructural Anchor Identification: Identifying three key swing highs [red grips] and three key swing lows [green grips] provides the foundation for the dual-curve geometry. These specific structural peaks and troughs serve as the coordinates for the mathematical models, ensuring that the resulting boundaries accurately reflect the underlying skeleton of the market action.


2️⃣Interactive Adjustment

After the initial setup, all six anchor points are fully adjustable:
  • Points are automatically sorted chronologically regardless of selection order
  • Grip handles appear at each anchor location
  • Any point can be repositioned by clicking and dragging its grip handle
  • The curves recalculate instantly as points are adjusted

The algorithm produces a mathematically perfect curve based on the anchor points provided. If the result does not match the trader's vision, adjustments are immediate. This iterative refinement—see, adjust, refine—continues until the rendered curve represents what the trader sees in the price action. The user remains in control; the algorithm remains in service.

ảnh chụp nhanhInteractive Channel Boundaries: Six user-defined anchor points—three for resistance [red grips] and three for support [green grips] —establish a non-linear range that moves beyond the constraints of a flat, horizontal channel. This configuration captures the arcing trajectory of the market while showing price action respecting the curved boundaries in a classic reversion pattern. By manually positioning these anchors, a dynamic dimension is added to the chart that maintains structural integrity even as the price follows a rounded path.


🛠️ SETTINGS 🛠️
ảnh chụp nhanhCustomizable Visual Feedback: Beyond the core geometry, the visualization offers various user-defined settings to tailor the chart's information density. From identifying specific price targets to toggling structural labels, these options allow the trader to adjust the level of detail to suit their personal analysis style while maintaining a clear view of the non-linear boundaries.

Configuration Options
  • Curve Method — Select the curve-fitting algorithm: Quadratic, Quadratic-Linear, Weighted Linear, or Natural Cubic Spline.
  • Projection Length — Number of bars to project the curves beyond current price action. Projections appear as dashed lines.

Visual Settings
  • Grip Size — Size of the draggable handles displayed at each anchor point. Set to zero to hide grips entirely.
  • Line Width — Thickness of the support and resistance curves.
  • Support Color / Resistance Color — Color settings for each curve.
  • Show Info Table — Toggle display of the info table showing the current curve method in the chart corner.

Advanced: Time/Price Coordinates
The settings panel includes precise time and price values for each of the six anchor points, grouped under Resistance Time/Price and Support Time/Price. These values are populated automatically when points are selected on the chart.

Adjusting anchor points by dragging the grip handles directly on the chart is faster and more intuitive. The time/price fields are available for situations requiring exact coordinate entry—such as aligning an anchor to a specific candle timestamp or a precise price level. These fields can be safely ignored unless fine-tuning is necessary.


🖼️ CHART EXAMPLES 🖼️

The Flexible S/R Channels indicator adapts to diverse market structures across multiple timeframes and instruments. Curved boundaries can define subtle momentum shifts in near-linear trends, dramatic reversals in rounding formations, or volatility compression as channels converge toward breakout points. The four curve-fitting methods accommodate different geometries—smooth parabolic arcs for continuous momentum changes, segmented linear paths for angular structures, and elastic splines for complex oscillations. Each anchor point adjustment instantly recalculates the curves, allowing iterative refinement until the rendered boundaries align with the trader's interpretation of market structure. Forward projections extend these mathematical relationships into future territory, providing visual context for hypothetical support and resistance levels if current trajectories persist.

ảnh chụp nhanhSubtle Curve Alignment: Even in structures that appear linear, subtle curvature allows the channel boundaries to breathe with the market’s internal momentum. By utilizing three anchor points rather than two, the channel adapts to the slight acceleration of a trend, providing a more precise fit than a rigid, straight corridor.

ảnh chụp nhanhDecelerating Momentum and Convergence: This classic rounding structure illustrates a transition where the initial wide oscillations between highs and lows begin to contract. As the boundaries converge, the curve captures the diminishing volatility and the shift in market energy, providing a clear visual representation of a trend losing its expansive momentum as it approaches a potential turning point.

ảnh chụp nhanhOrganic Trend Modeling: In an accelerating uptrend, the Natural Cubic Spline provides a highly adaptable boundary that mirrors the organic flow of momentum. This non-traditional approach allows the channel to follow complex price pulses that a standard linear trendline would likely cut through, maintaining a precise fit even as the angle of the trend shifts over time.

ảnh chụp nhanhNon-Linear Projections: Unlike standard trendlines that converge at a fixed rate, curved projections adapt to the historical momentum of the move. This allows the indicator to map a dynamic squeeze, capturing the subtle nuances of how price action tightens toward an apex. It provides a more sophisticated view of future convergence points that traditional linear channels often fail to anticipate.

ảnh chụp nhanhThe "Draw What You See" Philosophy: Market structures are rarely perfect, and this example highlights the indicator’s ability to map unconventional rhythms. Rather than forcing price into a predefined category, the tool remains flexible enough to define any structural path the trader identifies. If you can see a trend's trajectory, the indicator can provide the mathematical framework to support it.

ảnh chụp nhanhComparative Projection Modeling: Using identical anchor points as above, this example demonstrates how selecting a different calculation method can alter the projected path. While the historical fit remains precise, the variation in the forward-looking trajectory allows traders to explore multiple mathematical interpretations of the same market structure, choosing the model that best aligns with the current volatility and trend behavior.

ảnh chụp nhanhExtended Timeframe Channel Definition: This multi-year perspective demonstrates the indicator's ability to define curved channel boundaries across extended timeframes spanning hundreds of bars and multiple market cycles. The resistance curve captures the rounded distribution of swing highs while the support curve follows the accelerating base formation, creating a non-linear channel that frames long-term structural trends more precisely than traditional parallel channels or static trendlines.

ảnh chụp nhanhRounding Bottom Reversal and Channel Convergence: This example captures a classic rounding bottom formation—a reversal pattern that linear tools cannot adequately define. The Quadratic method produces a smooth parabolic arc through the resistance anchors, tracing the deceleration of the downtrend, the capitulation low, and the subsequent re-acceleration upward as a single continuous curve. The support boundary mirrors this momentum shift from below, creating a curved channel that narrows toward current price. This convergence represents structural compression—the boundaries tightening as volatility contracts and directional resolution approaches. Price action oscillates within these non-linear boundaries, demonstrating that channel behavior persists even when the geometry is curved rather than parallel. The projection extends both curves forward, mapping the hypothetical trajectory if the current momentum structure continues, providing visual context for potential breakout or breakdown levels as the channel reaches its apex.

ảnh chụp nhanhBuilt-in Precision vs. Algorithmic Power: While TradingView offers basic curve drawing tools (shown here as dashed lines), the Flexible S/R Channels indicator elevates this concept into a functional analytical framework. By converting manual observations into mathematical models, it moves beyond mere drawing to provide a data-driven structure that can be utilized for advanced technical analysis and future Pine Script trading logic.


⚙️TECHNICAL DETAILS⚙️
  • Curve Fitting vs. Overfitting: The term curve fitting often carries negative connotations in quantitative analysis due to its association with overfitting—the practice of adjusting a model until it perfectly matches historical data, producing an illusion of accuracy that fails when applied to new data. The application here is fundamentally different. Flexible S/R Channels does not optimize parameters to maximize historical fit; it constructs a mathematical curve through user-selected anchor points, then projects that curve into unknown territory. The curve is not fitted to price data—it is fitted to structural pivots identified by the trader. The projection represents a hypothesis about trajectory continuation, not a prediction derived from statistical optimization. Future price action validates or invalidates this hypothesis in real time, exactly as it does with any trendline or channel. The anchor points remain fixed unless manually adjusted, ensuring the curve does not adapt to new data retroactively.

  • Non-Repainting Behavior: The indicator does not repaint historical bars. The mathematical coefficients that define each curve are calculated once—when the final anchor point is set—and stored as fixed values. These coefficients remain constant unless an anchor point is manually repositioned. The backfit polyline is drawn once using these coefficients, spanning the known range from the first to last anchor point. The plot() function applies the same coefficients to each subsequent bar, updating in real-time as new bars form but never altering previously plotted values. The projection polyline extends forward from the current bar using the same fixed coefficients, projecting a user-defined number of future bars (maximum 500). This projection redraws on each tick to maintain its position relative to the moving current bar, but the mathematical trajectory remains constant—only the starting point advances. The current bar's curve value will update tick-by-tick as price develops, which is standard real-time behavior, not repainting. Once a bar closes, all curve values on that bar are permanent. The hybrid architecture (backfit polyline for known history, plot() for unlimited real-time range, projection polyline for controlled forward extension) prevents overflow errors while maintaining non-repainting integrity across all components.


🗒️NOTES🗒️
  • The indicator renders curves based on any anchor points provided without validation. Unusual anchor placement produces mathematically accurate but potentially non-useful results. Adjustment is iterative—if the curve doesn't match expectations, reposition the anchors.

  • Because anchor points are stored as specific time and price coordinates, a new instance of the indicator should be added when analyzing a different chart or timeframe.

  • Grip handles can be hidden by setting Grip Size to zero in the settings. This is useful for clean chart screenshots or presentations where interactive elements are not needed.

  • Projection length can be set to zero if forward-looking curves are not desired. The indicator will still render the backfit curves through the anchor points and continue plotting in real-time without the dotted projection extensions.

  • Anchor points remain fixed at their selected time-price coordinates as new bars form. The curves extend forward automatically from these historical anchors, allowing observation of how projected trajectories align with developing price action.



⚠️ DISCLAIMER ⚠️

The Flexible S/R Channels indicator is a visual analysis tool designed to illustrate geometric market inertia and serve as a framework for understanding dynamic support and resistance. While the indicator generates structural channels and projected paths, no guarantee is made regarding the accuracy or profitability of these projections. Like all technical indicators, the curves and boundaries generated by this tool may appear to align with favorable trading opportunities in hindsight. However, these visualizations are not intended as standalone recommendations for trading decisions. This indicator is intended for educational and analytical purposes, complementing other tools and methods of market analysis.


🧠BEYOND THE CODE 🧠

Flexible S/R Channels is part of a broader collection of tools designed to provide structured market analysis. This includes the Grid Bot Simulator, the Grid Bot Auto, the Grid Bot Parabolic, and the Gridbot Ping Pong. While each tool serves a distinct purpose, they all utilize dynamic anchor mechanics and non-linear boundaries to adapt to evolving market conditions.

This indicator shares the same educational philosophy as the Fibonacci Time-Price Zones and the Fibonacci Geometry Series - providing frameworks for understanding market concepts through visualization and experimentation rather than black-box signals.

The Flexible S/R Channels indicator, like other xxattaxx indicators, is designed to encourage both education and community engagement. Feedback and insights are invaluable to refining and enhancing this tool. We look forward to the creative applications, observations, and discussions this indicator inspires within the trading community.

Thông báo miễn trừ trách nhiệm

Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.