Quantile Regression Bands [BackQuant]Quantile Regression Bands
Tail-aware trend channeling built from quantiles of real errors, not just standard deviations.
What it does
This indicator fits a simple linear trend over a rolling lookback and then measures how price has actually deviated from that trend during the window. It then places two pairs of bands at user-chosen quantiles of those deviations (inner and outer). Because bands are based on empirical quantiles rather than a symmetric standard deviation, they adapt to skewed and fat-tailed behaviour and often hug price better in trending or asymmetric markets.
Why “quantile” bands instead of Bollinger-style bands?
Bollinger Bands assume a (roughly) symmetric spread around the mean; quantiles don’t—upper and lower bands can sit at different distances if the error distribution is skewed.
Quantiles are robust to outliers; a single shock won’t inflate the bands for many bars.
You can choose tails precisely (e.g., 1%/99% or 5%/95%) to match your risk appetite.
How it works (intuitive)
Center line — a rolling linear regression approximates the local trend.
Residuals — for each bar in the lookback, the indicator looks at the gap between actual price and where the line “expected” price to be.
Quantiles — those gaps are sorted; you select which percentiles become your inner/outer offsets.
Bands — the chosen quantile offsets are added to the current end of the regression line to draw parallel support/resistance rails.
Smoothing — a light EMA can be applied to reduce jitter in the line and bands.
What you see
Center (linear regression) line (optional).
Inner quantile bands (e.g., 25th/75th) with optional translucent fill.
Outer quantile bands (e.g., 1st/99th) with a multi-step gradient to visualise “tail zones.”
Optional bar coloring: bars trend-colored by whether price is rising above or falling below the center line.
Alerts when price crosses the outer bands (upper or lower).
How to read it
Trend & drift — the slope of the center line is your local trend. Persistent closes on the same side of the center line indicate directional drift.
Pullbacks — tags of the inner band often mark routine pullbacks within trend. Reaction back to the center line can be used for continuation entries/partials.
Tails & squeezes — outer-band touches highlight statistically rare excursions for the chosen window. Frequent outer-band activity can signal regime change or volatility expansion.
Asymmetry — if the upper band sits much further from the center than the lower (or vice versa), recent behaviour has been skewed. Trade management can be adjusted accordingly (e.g., wider take-profit upslope than downslope).
A simple trend interpretation can be derived from the bar colouring
Good use-cases
Volatility-aware mean reversion — fade moves into outer bands back toward the center when trend is flat.
Trend participation — buy pullbacks to the inner band above a rising center; flip logic for shorts below a falling center.
Risk framing — set dynamic stops/targets at quantile rails so position sizing respects recent tail behaviour rather than fixed ticks.
Inputs (quick guide)
Source — price input used for the fit (default: close).
Lookback Length — bars in the regression window and residual sample. Longer = smoother, slower bands; shorter = tighter, more reactive.
Inner/Outer Quantiles (τ) — choose your “typical” vs “tail” levels (e.g., 0.25/0.75 inner, 0.01/0.99 outer).
Show toggles — independently toggle center line, inner bands, outer bands, and their fills.
Colors & transparency — customize band and fill appearance; gradient shading highlights the tail zone.
Band Smoothing Length — small EMA on lines to reduce stair-step artefacts without meaningfully changing levels.
Bar Coloring — optional trend tint from the center line’s momentum.
Practical settings
Swing trading — Length 75–150; inner τ = 0.25/0.75, outer τ = 0.05/0.95.
Intraday — Length 50–100 for liquid futures/FX; consider 0.20/0.80 inner and 0.02/0.98 outer in high-vol assets.
Crypto — Because of fat tails, try slightly wider outers (0.01/0.99) and keep smoothing at 2–4 to tame weekend jumps.
Signal ideas
Continuation — in an uptrend, look for pullback into the lower inner band with a close back above the center as a timing cue.
Exhaustion probe — in ranges, first touch of an outer band followed by a rejection candle back inside the inner band often precedes mean-reversion swings.
Regime shift — repeated closes beyond an outer band or a sharp re-tilt in the center line can mark a new trend phase; adjust tactics (stop-following along the opposite inner band).
Alerts included
“Price Crosses Upper Outer Band” — potential overextension or breakout risk.
“Price Crosses Lower Outer Band” — potential capitulation or breakdown risk.
Notes
The fit and quantiles are computed on a fixed rolling window and do not repaint; bands update as the window moves forward.
Quantiles are based on the recent distribution; if conditions change abruptly, expect band widths and skew to adapt over the next few bars.
Parameter choices directly shape behaviour: longer windows favour stability, tighter inner quantiles increase touch frequency, and extreme outer quantiles highlight only the rarest moves.
Final thought
Quantile bands answer a simple question: “How unusual is this move given the current trend and the way price has been missing it lately?” By scoring that question with real, distribution-aware limits rather than one-size-fits-all volatility you get cleaner pullback zones in trends, more honest “extreme” tags in ranges, and a framework for risk that matches the market’s recent personality.
แบนด์และแชนแนล
Supertrend Channel Histogram OscillatorThis histogram is based on the script "Supertrend Channels "
The idea of the indicator is to visually represent the interaction of price with several different supertrend channels of various lengths in an oscillator in order to make it much more clear to the trader how the longer trends are interacting with shorter trends of the price movement of an asset. I got this idea from the "Kurutoga Cloud" and "Kurutoga Histogram" by D7R which is based on the centerlines of 3 Donchian Channels, however after I started using the Supertrend Channel by LuxAlgo I found that it was a more reliable price range channel than a standard Donchian Channel and I made this indicator to accompany it.
This indicator plots a positive value above 0 when the price is above the centerline of the supertrend channel and a negative value below 0 when the price is below the centerline.
The first supertrend's length and multiple can be adjusted in the settings.
The given supertrend input is then doubled and quadrupled in both length and multiplication so that a supertrend histogram with the values of 3, 3 will be accompanied by 2 additional supertrend histograms with the values of 6, 6 and 12, 12.
The larger price trend histograms are clearly visible behind the short term supertrend channel's histogram, giving traders a balanced view of short and long term trends interacting. The less visible columns of the larger trend remain above or below the 0 line behind the more visible short term channel trend, helping to spot pullbacks within a larger trend.
Additionally, when the 3 separate histograms are all positive or all negative but the histogram columns are separating from each other this can indicate a potential trend exhaustion leading to reversal or pullback about to happen.
The overbought and oversold lines at 50 and -50 are representative primarily of the short term trend with above 50 or below -50 indicating that the price is pushing the boundary and potentially beginning a new short term supertrend in the opposite direction. If values do not noticably exceed these levels, then the current short term trend movement can be viewed as a pullback within a larger trend, with continuation potentially to follow.
I have had troubles converting the original code to v6 so this will be published here in v5 of pinescript to be used in conjunction with the original. I was intending to create a companion indicator for this oscillator that represents 3 supertrends with corresponding 2x and 4x calculations based on LuxAlgo's script, but I can't seem to get it to work correctly in v5.
For best visualization of the trends 3 LuxAlgo Supertrend channels with 2x and 4x values should be used in conjunction with each other to fully visualize the histogram.
Used in conjunction with other indicators this can be a very effective strategy to capture larger trend moves and pullbacks within trends, as well as warn of potential price trend exhaustion.
Euler-Lagrange Bands [AGP] Ver.1.0Euler-Lagrange Bands : A Modern Approach to Volatility and Trend Analysis
indicator is an innovative technical analysis tool that uses a Kalman Filter to create dynamic and price-sensitive volatility bands. Unlike traditional Bollinger Bands or Keltner Channels, which rely on moving averages, this approach applies advanced engineering and mathematical principles to intelligently smooth price data. This reduces market noise and provides a clearer view of an asset's boundaries and its fair value.
Key Features
Dynamic and Smoothed Bands: The upper and lower bands adapt in real time to market volatility, offering a fluid and precise channel for identifying overbought and oversold zones.
"Fair Value" Midpoint: The indicator calculates and displays a midpoint that serves as a "fair value" reference. This is crucial for assessing whether the current price is over- or undervalued.
Multidimensional Analysis: It integrates with RSI and volume analysis to provide a comprehensive market view. The floating RSI and volume labels change color, offering quick and effective visual alerts.
Clear Visual Signals: The indicator draws shapes on the chart to mark band crosses, potential reversals, and trend confirmations. Additionally, the candlestick color changes to indicate whether the price is above or below the midpoint.
Real-Time Information Panel: A table in the top corner displays the exact values of the bands and the midpoint, giving you all the crucial information at a glance without cluttering the chart. The table's cell colors also change to alert you to price crosses.
Logic and Adjustments
The elb_process_noise and elb_measurement_noise values are fixed in this code to optimize band performance.
The only parameter the user can change from the indicator's settings in TradingView is length_periods, which allows for adjusting the bands' lookback period without altering the algorithm's sophisticated filtering logic.
The default values have been selected to provide an optimal balance between the indicator's stability and responsiveness, aiming to avoid false signals and ensure accurate market tracking.
How to Use It
This indicator is ideal for traders looking for a more sophisticated alternative to conventional volatility bands. It can be used to:
Identify an asset's price range.
Detect potential reversals when the price reaches or crosses the bands.
Confirm trend strength with volume and RSI analysis.
Make decisions based on the price's relationship to its "Fair Value."
Disclaimer
WARNING: This indicator is provided for educational and technical analysis purposes only. It does not constitute, and should not be interpreted as, financial advice. The buying and selling of financial instruments involve significant risk, and losses may exceed deposits. The past performance of any indicator or strategy is not a guarantee of future results. Users must conduct their own research, exercise due diligence, and consider their personal financial situation before making any investment decisions. The code's creator is not responsible for any losses or damages that may arise from the use of this indicator.
Custom Strategy Builder [CLAMENZA] i changed this indicator to make the market session lines thicker and font bigger as well.
Weekly/Monthly Golden ATR LevelsWeekly/Monthly Golden ATR Levels
This indicator is designed to give traders a clear, rule-based framework for identifying support and resistance zones anchored to prior period ranges and the market’s own volatility. It uses the Average True Range (ATR) as a measure of how far price can realistically stretch, then projects fixed levels from the midpoint of the prior week and prior month.
Rather than “moving targets” that repaint, these levels are frozen at the start of each new week and month and stay fixed until the next period begins. This makes them reliable rails for both intraday and swing trading.
What It Plots
Weekly Midpoint (last week’s High + Low ÷ 2)
From this mid, the script projects:
Weekly +1 / −1 ATR
Weekly +2 / −2 ATR
Monthly Midpoint (last month’s High + Low ÷ 2)
From this mid, the script projects:
Monthly +1 / −1 ATR
Monthly +2 / −2 ATR
Customization
Set ATR length & timeframe (default: 14 ATR on Daily bars).
Adjust multipliers for Level 1 (±1 ATR) and Level 2 (±2 ATR).
Choose line color, style, and width separately for weekly and monthly bands.
Toggle labels on/off.
How to Use
Context at the Open
If price opens above last week’s midpoint, bias favors upside toward +1 / +2.
If price opens below the midpoint, bias favors downside toward −1 / −2.
Weekly Bands = Short-Term Rails
+1 / −1 ATR: Rotation pivots. Expect intraday reaction.
+2 / −2 ATR: Extreme stretch zones. Reversals or breakouts often occur here.
Monthly Bands = Big Picture Rails
Use these for swing positioning, or as “outer guardrails” on intraday charts.
When weekly and monthly bands cluster → high-confluence zone.
Trade Playbook
Trend Day: Hold above +1 → target +2. Break below −1 → target −2.
Range Day: Fade first test of ±2, scalp toward ±1 or midpoint.
Catalyst/News Day: Use with caution—levels provide context, not barriers.
Risk Management
Place stops just outside the band you’re trading against.
Scale profits at the next inner level (e.g., short from +2, cover partial at +1).
Runners can trail to the midpoint or opposite side.
Why It Works
ATR measures volatility—how far price tends to travel in a given period.
Anchoring to prior highs and lows captures where real supply/demand last clashed.
Combining the two gives levels that are statistically relevant, widely observed, and psychologically sticky.
Trading books from Mark Douglas (Trading in the Zone), Jared Tendler (The Mental Game of Trading), and Oliver Kell (Victory in Stock Trading) all stress the importance of having objective, repeatable reference points. These levels deliver that discipline—removing guesswork and reducing emotional trading
Auto Slope Extremes ChannelAuto Slope Extremes Channel
Expanding channel that locks onto the highest high and lowest low of the slope between A and B.
This indicator builds a dynamic channel between two anchors, A and B.
Unlike fixed-width channels, it adapts to the slope of the leg between A and B and expands until:
• The upper channel line touches the highest candle in that slope.
• The lower channel line touches the lowest candle in that slope.
This method ensures that the channel edges are defined only by the single most extreme high and the single most extreme low within the selected leg. No other candles in the range touch the edges.
A centerline is drawn midway between the two extremes, and small triangle markers highlight the exact candles that determine the upper and lower boundaries.
Features
• Anchored channel defined by two user-selected points (A and B).
• Expands to fit the highest high and lowest low of the slope between A and B.
• Optional centerline and channel fill.
• Extend lines left, right, or both.
• Customizable line widths and colours.
TURT Donchian Ladder v3.13How to trade TURT+ with the v3.13 script
1) Pick the system & arm the entry
• In the script, choose System = S1 (20D) or S2 (55D).
The HUD always shows both rails for reference, but the ladder (Entry/+Adds) uses the system you pick.
• Your Entry is shown as Pivot + 0.1×N (rounded).
• Place a stop-limit “parent” order at that Entry price. (Classic Turtle uses an entry stop; I suggest a tight limit offset so you don’t chase a blow-through.)
• Initial stop = N2 = Entry − 2×N (rounded). Put that in immediately.
If you like only confirming on a bar close, leave confirmClose = true and place the parent after the close that breaks out. If you want intrabar fills, set confirmClose = false and keep the stop-limit active intraday.
2) Size it the way you planned
• Set acctEquity / riskCapPct / posCapUSD / entryFrac / entryRiskFrac / sizingMode.
• HUD gives Rec Entry Qty (when flat) and, once in, it shows:
• Next Rung (price)
• Suggested AddShares (honors RiskCap & PosCap)
• Proj Stop if Add (ratcheted N2)
• A limiter note (RiskCap or PosCap) if you’re constrained.
3) After entry fills, stage the ADDs (only at fixed +N steps)
• Adds are NOT “every Donchian break.” You add only at:
• Add-1 = Entry + 0.5×N
• Add-2 = Entry + 1.0×N
• Add-3 = Entry + 1.5×N (optional)
• Use the HUD’s Suggested AddShares for each rung (it respects your RiskCap/PosCap).
• Place stop-limit orders for each add (either immediately as a contingent OTO chain that arms only after Entry fills, or you arm each add when price approaches—your choice).
• On each add fill, ratchet the catastrophic stop for the entire position to Last-Add − 2×N (the script and HUD show Proj Stop if Add so you know where it will land). Never move it lower.
Pro tip: If your broker supports OTO/OTOCO:
• OTO parent = Entry stop-limit.
• On fill, fire an OCO with the N2 stop (no target), and also stage child stop-limits for Add-1 / Add-2 / Add-3 with the correct sizes. If your broker can’t chain that deep, just use the script’s alerts (Entry/Add-1/Add-2/Add-3/Exits) to place/adjust orders quickly.
4) Exits (two layers)
• Catastrophic (always on): the N2 stop you’re ratcheting (Last-Add − 2×N).
• Trend exits (runner):
• S1: 10-low close (HUD shows it).
• S2: 20-low close (HUD shows it).
• Profit-taking (optional): sell ~50% at +2.5R to +3R vs current N2; let the runner trail with 10-low/20-low. You can keep N2 as a hard backstop.
5) Should you pre-set everything or buy live?
Both work; pick the style that fits you:
Preset (Turtle-pure, rules-based)
• ✅ You won’t miss the breakout; minimal discretion.
• ✅ Broker handles fills even if you’re away.
• ⚠️ You may get the occasional intraday “poke” (use confirmClose + place after close if you want fewer).
Buy on break manually
• ✅ Lets you check tape/volume or any extra gates before clicking.
• ⚠️ Higher chance of slippage or of simply missing the trigger.
A nice hybrid: place the Entry order, then arm Add-1/2/3 when price is nearing each rung and the HUD shows Suggested AddShares > 0 (green risk read).
⸻
6) Quick checklist per trade
1. System: S1 or S2?
2. Levels: Entry / Add-1 / Add-2 / Add-3 / 10-low / 20-low / N2 (rounded).
3. Sizing: confirm RiskCap/PosCap; HUD shows Suggested AddShares and limiter.
4. Orders:
• Parent Entry stop-limit.
• N2 stop (rounded).
• Stage adds (stop-limits) with sizes from HUD.
5. On fill: ratchet stop to Last-Add − 2×N; adjust remaining adds and sizes.
⸻
7) Example with your MU position (pattern)
• You’re already in: set entryQty and entryPman in the inputs to match your fill.
• HUD now focuses on Next Rung, Suggested AddShares, and Proj Stop if Add.
• If Suggested AddShares = 0 and limiter says RiskCap or PosCap, you’ll still see the next rung price and Proj Stop if Add so you can decide whether to override.
⸻
Bottom line
• Entry: buy the Donchian breakout + 0.1N with a stop-limit (Turtle style).
• Adds: only at +0.5N steps, sized by HUD; not on every future Donchian break.
• Stops: keep (and ratchet) the N2 catastrophic; trail runner on 10-low / 20-low.
If you want, tell me your broker/platform and I’ll map this to exact order ticket types (stop-limit/OTO/OCO) and a tiny checklist you can keep next to your screen.
EMA Zonen + Projektion (21, 50 + 200)standard 21ema, 50ema and 200ema,
ema Projection for next 3 Bars,
1% Box above to below all emas.
Range Grid From Two Levels (with intermediate lines)Range Grid From Two Levels of Initial Balance (works great with next day levels)
Confirmed Reversals After Bollinger Band ExtremesMean reversion confirmation - it will give reversal entry when price will reach at distance from EMA and it will move to opposite direction
Chanpreet RSI(3) Extreme Rays (4H, Adjustable Style)Chanpreet RSI(3) Extreme Rays (4H)
This indicator applies a short-length RSI (3) on the 4-hour timeframe and highlights momentum extremes directly on the chart.
🔎 What it does
Detects when RSI(3) moves into overbought (>80) or oversold (<20) territory.
Groups consecutive candles inside these zones into one “event” instead of marking each bar individually.
For each event:
• In overbought → records the highest high of the stretch and marks it with a horizontal ray.
• In oversold → records the lowest low of the stretch and marks it with a horizontal ray.
Keeps only the most recent N rays (default 5, adjustable).
⚙️ Inputs
Max Rays to Keep → how many unique events are kept visible.
Ray Thickness → adjust line thickness.
Overbought Ray Color → default red.
Oversold Ray Color → default green.
📈 How to use
Apply on any chart; RSI(3) values are always calculated from 4H data (via request.security).
Use rays as reference levels that highlight recent momentum extremes or exhaustion zones.
This is not a buy/sell signal by itself — combine with your own analysis, confirmation tools, and risk management.
Best Recommended time frame is 5 mins, 10 mins & 15 mins for intraday trading.
🧩 Unique features
Groups multiple bars into a single clean ray, reducing clutter.
Uses 4H RSI(3) regardless of the chart’s active timeframe.
Fully customizable appearance (colors, thickness, max events).
⚠️ Disclaimer
This script is provided for educational and informational purposes only.
It does not constitute financial advice or guarantee performance.
Always test thoroughly and use proper risk management before trading live.
Médias Móveis 5 - SMA, EMA, Pivot Boss📈 5 Moving Averages – SMA, EMA, Pivot Boss
This indicator displays five fully customizable moving averages, allowing you to choose between:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
Pivot Boss S (SMA of Pivot Point)
Pivot Boss E (EMA of Pivot Point)
Each moving average can have its own type and length, making this tool suitable for scalping, trend-following, and multi-timeframe analysis.
StarterPack MAs🚀 Starter Moving Averages Indicator
This indicator was built by combining all the moving averages I personally use in my trading, organized in a clear and visual way to make market reading much easier. Instead of jumping between multiple tools, you now have everything in one place – designed to highlight trend direction, potential reversal areas, and dynamic zones of support and resistance.
📊 With this tool, you will be able to:
Quickly identify whether moving averages are aligned or diverging.
Spot moments of strong trending movement and possible shifts in momentum.
Use it as a filter for cleaner trade entries, reducing noise.
Track areas that often act as price “magnets” during intraday sessions.
💡 The idea is not to give you a rigid “buy/sell” signal, but to provide a market reading framework that adapts to different trading styles – whether you’re riding trends or looking for reversals at key levels. It brings structure, clarity, and consistency to the way you analyze your charts.
🔥 At the end of the day, this indicator is about perspective: making your screen cleaner, your decision-making faster, and your execution more confident. It’s not a magic button – it’s a powerful lens to help you see what really matters in the market.
Rolling Range Bands by tvigRolling Range Bands
Plots two dynamic price envelopes that track the highest and lowest prices over a Short and Long lookback. Use them to see near-term vs. broader market structure, evolving support/resistance, and volatility changes at a glance.
What it shows
• Short Bands: recent trading range (fast, more reactive).
• Long Bands: broader range (slow, structural).
• Optional step-line style and shaded zones for clarity.
• Option to use completed bar values to avoid intrabar jitter (no repaint).
How to read
• Price pressing the short high while the long band rises → short-term momentum in a larger uptrend.
• Price riding the short low inside a falling long band → weakness with trend alignment.
• Band squeeze (narrowing) → compression; watch for breakout.
• Band expansion (widening) → rising volatility; expect larger swings.
• Repeated touches/rejections of long bands → potential areas of support/resistance.
Inputs
• Short Window, Long Window (bars)
• Use Close only (vs. High/Low)
• Use completed bar values (stability)
• Step-line style and Band shading
Tips
• Works on any symbol/timeframe; tune windows to your market.
• For consistent scaling, pin the indicator to the same right price scale as the chart.
Not financial advice; combine with trend/volume/RSI or your system for entries/exits.
Range Grid From Two LevelsRange Grid From Two Levels of Initial Balance (works great with next day levels)
Buzzara// © Buzzara
// =================================
// PLEASE SUPPORT THE TEAM
// =================================
//
// Telegram: t.me
a_trade// =================================
//@version=5
VERSION = ' Buzzara2.0'
strategy('ALGOX V6_1_24', shorttitle = '🚀〄 Buzzara2.0 〄🚀'+ VERSION, overlay = true, explicit_plot_zorder = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, initial_capital = 1000, default_qty_value = 1, calc_on_every_tick = false, process_orders_on_close = true)
G_SCRIPT01 = '■ ' + 'SAIYAN OCC'
//#region ———— <↓↓↓ G_SCRIPT01 ↓↓↓> {
// === INPUTS ===
res = input.timeframe('15', 'TIMEFRAME', group ="NON REPAINT")
useRes = input(true, 'Use Alternate Signals')
intRes = input(10, 'Multiplier for Alernate Signals')
basisType = input.string('ALMA', 'MA Type: ', options= )
basisLen = input.int(50, 'MA Period', minval=1)
offsetSigma = input.int(5, 'Offset for LSMA / Sigma for ALMA', minval=0)
offsetALMA = input.float(2, 'Offset for ALMA', minval=0, step=0.01)
scolor = input(false, 'Show coloured Bars to indicate Trend?')
delayOffset = input.int(0, 'Delay Open/Close MA', minval=0, step=1,
tooltip = 'Forces Non-Repainting')
tradeType = input.string('BOTH', 'What trades should be taken : ',
options = )
//=== /INPUTS ===
h = input(false, 'Signals for Heikin Ashi Candles')
//INDICATOR SETTINGS
swing_length = input.int(10, 'Swing High/Low Length', group = 'Settings', minval = 1, maxval = 50)
history_of_demand_to_keep = input.int(20, 'History To Keep', minval = 5, maxval = 50)
box_width = input.float(2.5, 'Supply/Demand Box Width', group = 'Settings', minval = 1, maxval = 10, step = 0.5)
//INDICATOR VISUAL SETTINGS
show_zigzag = input.bool(false, 'Show Zig Zag', group = 'Visual Settings', inline = '1')
show_price_action_labels = input.bool(false, 'Show Price Action Labels', group = 'Visual Settings', inline = '2')
supply_color = input.color(#00000000, 'Supply', group = 'Visual Settings', inline = '3')
supply_outline_color = input.color(#00000000, 'Outline', group = 'Visual Settings', inline = '3')
demand_color = input.color(#00000000, 'Demand', group = 'Visual Settings', inline = '4')
demand_outline_color = input.color(#00000000, 'Outline', group = 'Visual Settings', inline = '4')
bos_label_color = input.color(#00000000, 'BOS Label', group = 'Visual Settings', inline = '5')
poi_label_color = input.color(#00000000, 'POI Label', group = 'Visual Settings', inline = '7')
poi_border_color = input.color(#00000000, 'POI border', group = 'Visual Settings', inline = '7')
swing_type_color = input.color(#00000000, 'Price Action Label', group = 'Visual Settings', inline = '8')
zigzag_color = input.color(#00000000, 'Zig Zag', group = 'Visual Settings', inline = '9')
//END SETTINGS
// FUNCTION TO ADD NEW AND REMOVE LAST IN ARRAY
f_array_add_pop(array, new_value_to_add) =>
array.unshift(array, new_value_to_add)
array.pop(array)
// FUNCTION SWING H & L LABELS
f_sh_sl_labels(array, swing_type) =>
var string label_text = na
if swing_type == 1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HH'
else
label_text := 'LH'
label.new(
bar_index - swing_length,
array.get(array,0),
text = label_text,
style = label.style_label_down,
textcolor = swing_type_color,
color = swing_type_color,
size = size.tiny)
else if swing_type == -1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HL'
else
label_text := 'LL'
label.new(
bar_index - swing_length,
array.get(array,0),
text = label_text,
style = label.style_label_up,
textcolor = swing_type_color,
color = swing_type_color,
size = size.tiny)
// FUNCTION MAKE SURE SUPPLY ISNT OVERLAPPING
f_check_overlapping(new_poi, box_array, atrValue) =>
atr_threshold = atrValue * 2
okay_to_draw = true
for i = 0 to array.size(box_array) - 1
top = box.get_top(array.get(box_array, i))
bottom = box.get_bottom(array.get(box_array, i))
poi = (top + bottom) / 2
upper_boundary = poi + atr_threshold
lower_boundary = poi - atr_threshold
if new_poi >= lower_boundary and new_poi <= upper_boundary
okay_to_draw := false
break
else
okay_to_draw := true
okay_to_draw
// FUNCTION TO DRAW SUPPLY OR DEMAND ZONE
f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atrValue) =>
atr_buffer = atrValue * (box_width / 10)
box_left = array.get(bn_array, 0)
box_right = bar_index
var float box_top = 0.00
var float box_bottom = 0.00
var float poi = 0.00
if box_type == 1
box_top := array.get(value_array, 0)
box_bottom := box_top - atr_buffer
poi := (box_top + box_bottom) / 2
else if box_type == -1
box_bottom := array.get(value_array, 0)
box_top := box_bottom + atr_buffer
poi := (box_top + box_bottom) / 2
okay_to_draw = f_check_overlapping(poi, box_array, atrValue)
// okay_to_draw = true
//delete oldest box, and then create a new box and add it to the array
if box_type == 1 and okay_to_draw
box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = supply_outline_color,
bgcolor = supply_color, extend = extend.right, text = 'SUPPLY', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 1) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = poi_border_color,
bgcolor = poi_border_color, extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
else if box_type == -1 and okay_to_draw
box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = demand_outline_color,
bgcolor = demand_color, extend = extend.right, text = 'DEMAND', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 1) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = poi_border_color,
bgcolor = poi_border_color, extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
// FUNCTION TO CHANGE SUPPLY/DEMAND TO A BOS IF BROKEN
f_sd_to_bos(box_array, bos_array, label_array, zone_type) =>
if zone_type == 1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_top(array.get(box_array,i))
// if ta.crossover(close, level_to_break)
if close >= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
if zone_type == -1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_bottom(array.get(box_array,i))
// if ta.crossunder(close, level_to_break)
if close <= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
// FUNCTION MANAGE CURRENT BOXES BY CHANGING ENDPOINT
f_extend_box_endpoint(box_array) =>
for i = 0 to array.size(box_array) - 1
box.set_right(array.get(box_array, i), bar_index + 100)
//
stratRes = timeframe.ismonthly ? str.tostring(timeframe.multiplier * intRes, '###M') :
timeframe.isweekly ? str.tostring(timeframe.multiplier * intRes, '###W') :
timeframe.isdaily ? str.tostring(timeframe.multiplier * intRes, '###D') :
timeframe.isintraday ? str.tostring(timeframe.multiplier * intRes, '####') :
'60'
src = h ? request.security(ticker.heikinashi(syminfo.tickerid),
timeframe.period, close, lookahead = barmerge.lookahead_off) : close
// CALCULATE ATR
atrValue = ta.atr(50)
// CALCULATE SWING HIGHS & SWING LOWS
swing_high = ta.pivothigh(high, swing_length, swing_length)
swing_low = ta.pivotlow(low, swing_length, swing_length)
// ARRAYS FOR SWING H/L & BN
var swing_high_values = array.new_float(5,0.00)
var swing_low_values = array.new_float(5,0.00)
var swing_high_bns = array.new_int(5,0)
var swing_low_bns = array.new_int(5,0)
// ARRAYS FOR SUPPLY / DEMAND
var current_supply_box = array.new_box(history_of_demand_to_keep, na)
var current_demand_box = array.new_box(history_of_demand_to_keep, na)
// ARRAYS FOR SUPPLY / DEMAND POI LABELS
var current_supply_poi = array.new_box(history_of_demand_to_keep, na)
var current_demand_poi = array.new_box(history_of_demand_to_keep, na)
// ARRAYS FOR BOS
var supply_bos = array.new_box(5, na)
var demand_bos = array.new_box(5, na)
//END CALCULATIONS
// NEW SWING HIGH
if not na(swing_high)
//MANAGE SWING HIGH VALUES
f_array_add_pop(swing_high_values, swing_high)
f_array_add_pop(swing_high_bns, bar_index )
if show_price_action_labels
f_sh_sl_labels(swing_high_values, 1)
f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atrValue)
// NEW SWING LOW
else if not na(swing_low)
//MANAGE SWING LOW VALUES
f_array_add_pop(swing_low_values, swing_low)
f_array_add_pop(swing_low_bns, bar_index )
if show_price_action_labels
f_sh_sl_labels(swing_low_values, -1)
f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atrValue)
f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1)
f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1)
f_extend_box_endpoint(current_supply_box)
f_extend_box_endpoint(current_demand_box)
channelBal = input.bool(false, "Channel Balance", group = "CHART")
lr_slope(_src, _len) =>
x = 0.0, y = 0.0, x2 = 0.0, xy = 0.0
for i = 0 to _len - 1
val = _src
per = i + 1
x += per
y += val
x2 += per * per
xy += val * per
_slp = (_len * xy - x * y) / (_len * x2 - x * x)
_avg = y / _len
_int = _avg - _slp * x / _len + _slp
lr_dev(_src, _len, _slp, _avg, _int) =>
upDev = 0.0, dnDev = 0.0
val = _int
for j = 0 to _len - 1
price = high - val
if price > upDev
upDev := price
price := val - low
if price > dnDev
dnDev := price
price := _src
val += _slp
//
= ta.kc(close, 80, 10.5)
= ta.kc(close, 80, 9.5)
= ta.kc(close, 80, 8)
= ta.kc(close, 80, 3)
barsL = 10
barsR = 10
pivotHigh = fixnan(ta.pivothigh(barsL, barsR) )
pivotLow = fixnan(ta.pivotlow(barsL, barsR) )
source = close, period = 150
= lr_slope(source, period)
= lr_dev(source, period, s, a, i)
y1 = low - (ta.atr(30) * 2), y1B = low - ta.atr(30)
y2 = high + (ta.atr(30) * 2), y2B = high + ta.atr(30)
x1 = bar_index - period + 1, _y1 = i + s * (period - 1), x2 = bar_index, _y2 = i
//Functions
//Line Style function
get_line_style(style) =>
out = switch style
'???' => line.style_solid
'----' => line.style_dashed
' ' => line.style_dotted
//Function to get order block coordinates
get_coordinates(condition, top, btm, ob_val)=>
var ob_top = array.new_float(0)
var ob_btm = array.new_float(0)
var ob_avg = array.new_float(0)
var ob_left = array.new_int(0)
float ob = na
//Append coordinates to arrays
if condition
avg = math.avg(top, btm)
array.unshift(ob_top, top)
array.unshift(ob_btm, btm)
array.unshift(ob_avg, avg)
ob := ob_val
//Function to remove mitigated order blocks from coordinate arrays
remove_mitigated(ob_top, ob_btm, ob_left, ob_avg, target, bull)=>
mitigated = false
target_array = bull ? ob_btm : ob_top
for element in target_array
idx = array.indexof(target_array, element)
if (bull ? target < element : target > element)
mitigated := true
array.remove(ob_top, idx)
array.remove(ob_btm, idx)
array.remove(ob_avg, idx)
array.remove(ob_left, idx)
mitigated
//Function to set order blocks
set_order_blocks(ob_top, ob_btm, ob_left, ob_avg, ext_last, bg_css, border_css, lvl_css)=>
var ob_box = array.new_box(0)
var ob_lvl = array.new_line(0)
//Global elements
var os = 0
var target_bull = 0.
var target_bear = 0.
// Create non-repainting security function
rp_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src )
htfHigh = rp_security(syminfo.tickerid, res, high)
htfLow = rp_security(syminfo.tickerid, res, low)
// Main Indicator
// Functions
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r : x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
securityNoRep(sym, res, src) => request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on)
swingPoints(prd) =>
pivHi = ta.pivothigh(prd, prd)
pivLo = ta.pivotlow (prd, prd)
last_pivHi = ta.valuewhen(pivHi, pivHi, 1)
last_pivLo = ta.valuewhen(pivLo, pivLo, 1)
hh = pivHi and pivHi > last_pivHi ? pivHi : na
lh = pivHi and pivHi < last_pivHi ? pivHi : na
hl = pivLo and pivLo > last_pivLo ? pivLo : na
ll = pivLo and pivLo < last_pivLo ? pivLo : na
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
f_kc(src, len, sensitivity) =>
basis = ta.sma(src, len)
span = ta.atr(len)
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
f_top_fractal(_src) => _src < _src and _src < _src and _src > _src and _src > _src
f_bot_fractal(_src) => _src > _src and _src > _src and _src < _src and _src < _src
top_fractal = f_top_fractal(src)
bot_fractal = f_bot_fractal(src)
f_fractalize (_src) => top_fractal ? 1 : bot_fractal ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src >= topLimit ? src : na
fractalBot = f_fractalize(src) < 0 and src <= botLimit ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
// Get user input
enableSR = input(false , "SR On/Off", group="SR")
colorSup = input(#00000000 , "Support Color", group="SR")
colorRes = input(#00000000 , "Resistance Color", group="SR")
strengthSR = input.int(2 , "S/R Strength", 1, group="SR")
lineStyle = input.string("Dotted", "Line Style", , group="SR")
lineWidth = input.int(2 , "S/R Line Width", 1, group="SR")
useZones = input(true , "Zones On/Off", group="SR")
useHLZones = input(true , "High Low Zones On/Off", group="SR")
zoneWidth = input.int(2 , "Zone Width %", 0,
tooltip = "it's calculated using % of the distance between highest/lowest in last 300 bars", group="SR")
expandSR = input(true , "Expand SR")
// Get components
rb = 10
prd = 284
ChannelW = 10
label_loc = 55
style = lineStyle == "Solid" ? line.style_solid :
lineStyle == "Dotted" ? line.style_dotted : line.style_dashed
ph = ta.pivothigh(rb, rb)
pl = ta.pivotlow (rb, rb)
sr_levels = array.new_float(21, na)
prdhighest = ta.highest(prd)
prdlowest = ta.lowest(prd)
cwidth = percWidth(prd, ChannelW)
zonePerc = percWidth(300, zoneWidth)
aas = array.new_bool(41, true)
u1 = 0.0, u1 := nz(u1 )
d1 = 0.0, d1 := nz(d1 )
highestph = 0.0, highestph := highestph
lowestpl = 0.0, lowestpl := lowestpl
var sr_levs = array.new_float(21, na)
label hlabel = na, label.delete(hlabel )
label llabel = na, label.delete(llabel )
var sr_lines = array.new_line(21, na)
var sr_linesH = array.new_line(21, na)
var sr_linesL = array.new_line(21, na)
var sr_linesF = array.new_linefill(21, na)
var sr_labels = array.new_label(21, na)
if (not na(ph) or not na(pl))
for x = 0 to array.size(sr_levels) - 1
array.set(sr_levels, x, na)
highestph := prdlowest
lowestpl := prdhighest
countpp = 0
for x = 0 to prd
if na(close )
break
if not na(ph ) or not na(pl )
highestph := math.max(highestph, nz(ph , prdlowest), nz(pl , prdlowest))
lowestpl := math.min(lowestpl, nz(ph , prdhighest), nz(pl , prdhighest))
countpp += 1
if countpp > 40
break
if array.get(aas, countpp)
upl = (not na(ph ) and (ph != 0) ? high : low ) + cwidth
dnl = (not na(ph ) and (ph != 0) ? high : low ) - cwidth
u1 := countpp == 1 ? upl : u1
d1 := countpp == 1 ? dnl : d1
tmp = array.new_bool(41, true)
cnt = 0
tpoint = 0
for xx = 0 to prd
if na(close )
break
if not na(ph ) or not na(pl )
chg = false
cnt += 1
if cnt > 40
break
if array.get(aas, cnt)
if not na(ph )
if high <= upl and high >= dnl
tpoint += 1
chg := true
if not na(pl )
if low <= upl and low >= dnl
tpoint += 1
chg := true
if chg and cnt < 41
array.set(tmp, cnt, false)
if tpoint >= strengthSR
for g = 0 to 40 by 1
if not array.get(tmp, g)
array.set(aas, g, false)
if (not na(ph ) and countpp < 21)
array.set(sr_levels, countpp, high )
if (not na(pl ) and countpp < 21)
array.set(sr_levels, countpp, low )
// Plot
var line highest_ = na, line.delete(highest_)
var line lowest_ = na, line.delete(lowest_)
var line highest_fill1 = na, line.delete(highest_fill1)
var line highest_fill2 = na, line.delete(highest_fill2)
var line lowest_fill1 = na, line.delete(lowest_fill1)
var line lowest_fill2 = na, line.delete(lowest_fill2)
hi_col = close >= highestph ? colorSup : colorRes
lo_col = close >= lowestpl ? colorSup : colorRes
if enableSR
highest_ := line.new(bar_index - 311, highestph, bar_index, highestph, xloc.bar_index, expandSR ? extend.both : extend.right, hi_col, style, lineWidth)
lowest_ := line.new(bar_index - 311, lowestpl , bar_index, lowestpl , xloc.bar_index, expandSR ? extend.both : extend.right, lo_col, style, lineWidth)
if useHLZones
highest_fill1 := line.new(bar_index - 311, highestph + zonePerc, bar_index, highestph + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
highest_fill2 := line.new(bar_index - 311, highestph - zonePerc, bar_index, highestph - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill1 := line.new(bar_index - 311, lowestpl + zonePerc , bar_index, lowestpl + zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill2 := line.new(bar_index - 311, lowestpl - zonePerc , bar_index, lowestpl - zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
linefill.new(highest_fill1, highest_fill2, hi_col)
linefill.new(lowest_fill1 , lowest_fill2 , lo_col)
if (not na(ph) or not na(pl))
for x = 0 to array.size(sr_lines) - 1
array.set(sr_levs, x, array.get(sr_levels, x))
for x = 0 to array.size(sr_lines) - 1
line.delete(array.get(sr_lines, x))
line.delete(array.get(sr_linesH, x))
line.delete(array.get(sr_linesL, x))
linefill.delete(array.get(sr_linesF, x))
if (not na(array.get(sr_levs, x)) and enableSR)
line_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
array.set(sr_lines, x, line.new(bar_index - 355, array.get(sr_levs, x), bar_index, array.get(sr_levs, x), xloc.bar_index, expandSR ? extend.both : extend.right, line_col, style, lineWidth))
if useZones
array.set(sr_linesH, x, line.new(bar_index - 355, array.get(sr_levs, x) + zonePerc, bar_index, array.get(sr_levs, x) + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
array.set(sr_linesL, x, line.new(bar_index - 355, array.get(sr_levs, x) - zonePerc, bar_index, array.get(sr_levs, x) - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
array.set(sr_linesF, x, linefill.new(array.get(sr_linesH, x), array.get(sr_linesL, x), line_col))
for x = 0 to array.size(sr_labels) - 1
label.delete(array.get(sr_labels, x))
if (not na(array.get(sr_levs, x)) and enableSR)
lab_loc = close >= array.get(sr_levs, x) ? label.style_label_up : label.style_label_down
lab_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
array.set(sr_labels, x, label.new(bar_index + label_loc, array.get(sr_levs, x), str.tostring(math.round_to_mintick(array.get(sr_levs, x))), color=lab_col , textcolor=#000000, style=lab_loc))
hlabel := enableSR ? label.new(bar_index + label_loc + math.round(math.sign(label_loc)) * 20, highestph, "High Level : " + str.tostring(highestph), color=hi_col, textcolor=#000000, style=label.style_label_down) : na
llabel := enableSR ? label.new(bar_index + label_loc + math.round(math.sign(label_loc)) * 20, lowestpl , "Low Level : " + str.tostring(lowestpl) , color=lo_col, textcolor=#000000, style=label.style_label_up ) : na
// Get components
rsi = ta.rsi(close, 28)
//rsiOb = rsi > 78 and rsi > ta.ema(rsi, 10)
//rsiOs = rsi < 27 and rsi < ta.ema(rsi, 10)
rsiOb = rsi > 65 and rsi > ta.ema(rsi, 10)
rsiOs = rsi < 35 and rsi < ta.ema(rsi, 10)
dHigh = securityNoRep(syminfo.tickerid, "D", high )
dLow = securityNoRep(syminfo.tickerid, "D", low )
dClose = securityNoRep(syminfo.tickerid, "D", close )
ema = ta.ema(close, 144)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep1(sym, res, src) =>
bool bull_ = na
bull_ := equal_tf(res) ? src : bull_
bull_ := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on) : bull_
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) + (timeframe.isseconds ? "S" : "") : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull_ := array.pop(bull_array)
array.clear(bull_array)
bull_
// === BASE FUNCTIONS ===
// Returns MA input selection variant, default to SMA if blank or typo.
variant(type, src, len, offSig, offALMA) =>
v1 = ta.sma(src, len) // Simple
v2 = ta.ema(src, len) // Exponential
v3 = 2 * v2 - ta.ema(v2, len) // Double Exponential
v4 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) // Triple Exponential
v5 = ta.wma(src, len) // Weighted
v6 = ta.vwma(src, len) // Volume Weighted
v7 = 0.0
sma_1 = ta.sma(src, len) // Smoothed
v7 := na(v7 ) ? sma_1 : (v7 * (len - 1) + src) / len
v8 = ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) // Hull
v9 = ta.linreg(src, len, offSig) // Least Squares
v10 = ta.alma(src, len, offALMA, offSig) // Arnaud Legoux
v11 = ta.sma(v1, len) // Triangular (extreme smooth)
// SuperSmoother filter
// 2013 John F. Ehlers
a1 = math.exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * math.cos(1.414 * 3.14159 / len)
c2 = b1
c3 = -a1 * a1
c1 = 1 - c2 - c3
v12 = 0.0
v12 := c1 * (src + nz(src )) / 2 + c2 * nz(v12 ) + c3 * nz(v12 )
type == 'EMA' ? v2 : type == 'DEMA' ? v3 : type == 'TEMA' ? v4 : type == 'WMA' ? v5 : type == 'VWMA' ? v6 : type == 'SMMA' ? v7 : type == 'HullMA' ? v8 : type == 'LSMA' ? v9 : type == 'ALMA' ? v10 : type == 'TMA' ? v11 : type == 'SSMA' ? v12 : v1
// security wrapper for repeat calls
reso(exp, use, res) =>
security_1 = request.security(syminfo.tickerid, res, exp, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
use ? security_1 : exp
// === /BASE FUNCTIONS ===
// === SERIES SETUP ===
closeSeries = variant(basisType, close , basisLen, offsetSigma, offsetALMA)
openSeries = variant(basisType, open , basisLen, offsetSigma, offsetALMA)
// === /SERIES ===
// Get Alternate resolution Series if selected.
closeSeriesAlt = reso(closeSeries, useRes, stratRes)
openSeriesAlt = reso(openSeries, useRes, stratRes)
//
lxTrigger = false
sxTrigger = false
leTrigger = ta.crossover (closeSeriesAlt, openSeriesAlt)
seTrigger = ta.crossunder(closeSeriesAlt, openSeriesAlt)
G_RISK = '■ ' + 'Risk Management'
//#region ———— <↓↓↓ G_RISK ↓↓↓> {
// ———————————
//Tooltip
T_LVL = '(%) Exit Level'
T_QTY = '(%) Adjust trade exit volume'
T_MSG = 'Paste JSON message for your bot'
//Webhook Message
O_LEMSG = 'Long Entry'
O_LXMSGSL = 'Long SL'
O_LXMSGTP1 = 'Long TP1'
O_LXMSGTP2 = 'Long TP2'
O_LXMSGTP3 = 'Long TP3'
O_LXMSG = 'Long Exit'
O_SEMSG = 'Short Entry'
O_SXMSGSL = 'Short SL'
O_SXMSGA = 'Short TP1'
O_SXMSGB = 'Short TP2'
O_SXMSGC = 'Short TP3'
O_SXMSGX = 'Short Exit'
// ——————————— | | | Line length guide |
i_lxLvlTP1 = input.float (0.2, 'Level TP1' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP1 = input.float (80.0, 'Qty TP1' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlTP2 = input.float (0.5, 'Level TP2' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP2 = input.float (10.0, 'Qty TP2' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlTP3 = input.float (7.0, 'Level TP3' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP3 = input.float (2, 'Qty TP3' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlSL = input.float (0.5, 'Stop Loss' , group = G_RISK,
tooltip = T_LVL)
i_sxLvlTP1 = i_lxLvlTP1
i_sxQtyTP1 = i_lxQtyTP1
i_sxLvlTP2 = i_lxLvlTP2
i_sxQtyTP2 = i_lxQtyTP2
i_sxLvlTP3 = i_lxLvlTP3
i_sxQtyTP3 = i_lxQtyTP3
i_sxLvlSL = i_lxLvlSL
G_MSG = '■ ' + 'Webhook Message'
i_leMsg = input.string (O_LEMSG ,'Long Entry' , group = G_MSG, tooltip = T_MSG)
i_lxMsgSL = input.string (O_LXMSGSL ,'Long SL' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP1 = input.string (O_LXMSGTP1,'Long TP1' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP2 = input.string (O_LXMSGTP2,'Long TP2' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP3 = input.string (O_LXMSGTP3,'Long TP3' , group = G_MSG, tooltip = T_MSG)
i_lxMsg = input.string (O_LXMSG ,'Long Exit' , group = G_MSG, tooltip = T_MSG)
i_seMsg = input.string (O_SEMSG ,'Short Entry' , group = G_MSG, tooltip = T_MSG)
i_sxMsgSL = input.string (O_SXMSGSL ,'Short SL' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP1 = input.string (O_SXMSGA ,'Short TP1' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP2 = input.string (O_SXMSGB ,'Short TP2' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP3 = input.string (O_SXMSGC ,'Short TP3' , group = G_MSG, tooltip = T_MSG)
i_sxMsg = input.string (O_SXMSGX ,'Short Exit' , group = G_MSG, tooltip = T_MSG)
i_src = close
G_DISPLAY = 'Display'
//
i_alertOn = input.bool (true, 'Alert Labels On/Off' , group = G_DISPLAY)
i_barColOn = input.bool (true, 'Bar Color On/Off' , group = G_DISPLAY)
// ———————————
// @function Calculate the Take Profit line, and the crossover or crossunder
f_tp(_condition, _conditionValue, _leTrigger, _seTrigger, _src, _lxLvlTP, _sxLvlTP)=>
var float _tpLine = 0.0
_topLvl = _src + (_src * (_lxLvlTP / 100))
_botLvl = _src - (_src * (_sxLvlTP / 100))
_tpLine := _condition != _conditionValue and _leTrigger ? _topLvl :
_condition != -_conditionValue and _seTrigger ? _botLvl :
nz(_tpLine )
// @function Similar to "ta.crossover" or "ta.crossunder"
f_cross(_scr1, _scr2, _over)=>
_cross = _over ? _scr1 > _scr2 and _scr1 < _scr2 :
_scr1 < _scr2 and _scr1 > _scr2
// ———————————
//
var float condition = 0.0
var float slLine = 0.0
var float entryLine = 0.0
//
entryLine := leTrigger and condition <= 0.0 ? close :
seTrigger and condition >= 0.0 ? close : nz(entryLine )
//
slTopLvl = i_src + (i_src * (i_lxLvlSL / 100))
slBotLvl = i_src - (i_src * (i_sxLvlSL / 100))
slLine := condition <= 0.0 and leTrigger ? slBotLvl :
condition >= 0.0 and seTrigger ? slTopLvl : nz(slLine )
slLong = f_cross(low, slLine, false)
slShort = f_cross(high, slLine, true )
//
= f_tp(condition, 1.2,leTrigger, seTrigger, i_src, i_lxLvlTP3, i_sxLvlTP3)
= f_tp(condition, 1.1,leTrigger, seTrigger, i_src, i_lxLvlTP2, i_sxLvlTP2)
= f_tp(condition, 1.0,leTrigger, seTrigger, i_src, i_lxLvlTP1, i_sxLvlTP1)
tp3Long = f_cross(high, tp3Line, true )
tp3Short = f_cross(low, tp3Line, false)
tp2Long = f_cross(high, tp2Line, true )
tp2Short = f_cross(low, tp2Line, false)
tp1Long = f_cross(high, tp1Line, true )
tp1Short = f_cross(low, tp1Line, false)
switch
leTrigger and condition <= 0.0 => condition := 1.0
seTrigger and condition >= 0.0 => condition := -1.0
tp3Long and condition == 1.2 => condition := 1.3
tp3Short and condition == -1.2 => condition := -1.3
tp2Long and condition == 1.1 => condition := 1.2
tp2Short and condition == -1.1 => condition := -1.2
tp1Long and condition == 1.0 => condition := 1.1
tp1Short and condition == -1.0 => condition := -1.1
slLong and condition >= 1.0 => condition := 0.0
slShort and condition <= -1.0 => condition := 0.0
lxTrigger and condition >= 1.0 => condition := 0.0
sxTrigger and condition <= -1.0 => condition := 0.0
longE = leTrigger and condition <= 0.0 and condition == 1.0
shortE = seTrigger and condition >= 0.0 and condition == -1.0
longX = lxTrigger and condition >= 1.0 and condition == 0.0
shortX = sxTrigger and condition <= -1.0 and condition == 0.0
longSL = slLong and condition >= 1.0 and condition == 0.0
shortSL = slShort and condition <= -1.0 and condition == 0.0
longTP3 = tp3Long and condition == 1.2 and condition == 1.3
shortTP3 = tp3Short and condition == -1.2 and condition == -1.3
longTP2 = tp2Long and condition == 1.1 and condition == 1.2
shortTP2 = tp2Short and condition == -1.1 and condition == -1.2
longTP1 = tp1Long and condition == 1.0 and condition == 1.1
shortTP1 = tp1Short and condition == -1.0 and condition == -1.1
// ——————————— {
//
if strategy.position_size <= 0 and longE and barstate.isconfirmed
strategy.entry(
'Long',
strategy.long,
alert_message = i_leMsg,
comment = 'LE')
if strategy.position_size > 0 and condition == 1.0
strategy.exit(
id = 'LXTP1',
from_entry = 'Long',
qty_percent = i_lxQtyTP1,
limit = tp1Line,
stop = slLine,
comment_profit = 'LXTP1',
comment_loss = 'SL',
alert_profit = i_lxMsgTP1,
alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.1
strategy.exit(
id = 'LXTP2',
from_entry = 'Long',
qty_percent = i_lxQtyTP2,
limit = tp2Line,
stop = slLine,
comment_profit = 'LXTP2',
comment_loss = 'SL',
alert_profit = i_lxMsgTP2,
alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.2
strategy.exit(
id = 'LXTP3',
from_entry = 'Long',
qty_percent = i_lxQtyTP3,
limit = tp3Line,
stop = slLine,
comment_profit = 'LXTP3',
comment_loss = 'SL',
alert_profit = i_lxMsgTP3,
alert_loss = i_lxMsgSL)
if longX
strategy.close(
'Long',
alert_message = i_lxMsg,
comment = 'LX')
//
if strategy.position_size >= 0 and shortE and barstate.isconfirmed
strategy.entry(
'Short',
strategy.short,
alert_message = i_leMsg,
comment = 'SE')
if strategy.position_size < 0 and condition == -1.0
strategy.exit(
id = 'SXTP1',
from_entry = 'Short',
qty_percent = i_sxQtyTP1,
limit = tp1Line,
stop = slLine,
comment_profit = 'SXTP1',
comment_loss = 'SL',
alert_profit = i_sxMsgTP1,
alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.1
strategy.exit(
id = 'SXTP2',
from_entry = 'Short',
qty_percent = i_sxQtyTP2,
limit = tp2Line,
stop = slLine,
comment_profit = 'SXTP2',
comment_loss = 'SL',
alert_profit = i_sxMsgTP2,
alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.2
strategy.exit(
id = 'SXTP3',
from_entry = 'Short',
qty_percent = i_sxQtyTP3,
limit = tp3Line,
stop = slLine,
comment_profit = 'SXTP3',
comment_loss = 'SL',
alert_profit = i_sxMsgTP3,
alert_loss = i_sxMsgSL)
if shortX
strategy.close(
'Short',
alert_message = i_sxMsg,
comment = 'SX')
// ———————————
c_tp = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.green
c_entry = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.blue
c_sl = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.red
p_tp1Line = plot (
condition == 1.0 or
condition == -1.0 ? tp1Line : na,
title = "TP Line 1",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_tp2Line = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 ? tp2Line : na,
title = "TP Line 2",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_tp3Line = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 or
condition == 1.2 or
condition == -1.2 ? tp3Line : na,
title = "TP Line 3",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_entryLine = plot (
condition >= 1.0 or
condition <= -1.0 ? entryLine : na,
title = "Entry Line",
color = c_entry,
linewidth = 1,
style = plot.style_linebr)
p_slLine = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 or
condition == 1.2 or
condition == -1.2 ? slLine : na,
title = "SL Line",
color = c_sl,
linewidth = 1,
style = plot.style_linebr)
fill(
p_tp3Line, p_entryLine,
color = leTrigger or seTrigger ? na :color.new(color.green, 90))
fill(
p_entryLine, p_slLine,
color = leTrigger or seTrigger ? na :color.new(color.red, 90))
//
plotshape(
i_alertOn and longE,
title = 'Long',
text = 'Long',
textcolor = color.white,
color = color.green,
style = shape.labelup,
size = size.tiny,
location = location.belowbar)
plotshape(
i_alertOn and shortE,
title = 'Short',
text = 'Short',
textcolor = color.white,
color = color.red,
style = shape.labeldown,
size = size.tiny,
location = location.abovebar)
plotshape(
i_alertOn and (longX or shortX) ? close : na,
title = 'Close',
text = 'Close',
textcolor = color.white,
color = color.gray,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
l_tp = i_alertOn and (longTP1 or shortTP1) ? close : na
plotshape(
l_tp,
title = "TP1 Cross",
text = "TP1",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longTP2 or shortTP2) ? close : na,
title = "TP2 Cross",
text = "TP2",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longTP3 or shortTP3) ? close : na,
title = "TP3 Cross",
text = "TP3",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longSL or shortSL) ? close : na,
title = "SL Cross",
text = "SL",
textcolor = color.white,
color = color.maroon,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
//
plot(
na,
title = "─── ───",
editable = false,
display = display.data_window)
plot(
condition,
title = "condition",
editable = false,
display = display.data_window)
plot(
strategy.position_size * 100,
title = ".position_size",
editable = false,
display = display.data_window)
//#endregion }
// ——————————— <↑↑↑ G_RISK ↑↑↑>
//#region ———— <↓↓↓ G_SCRIPT02 ↓↓↓> {
// @function Queues a new element in an array and de-queues its first element.
f_qDq(_array, _val) =>
array.push(_array, _val)
_return = array.shift(_array)
_return
var line a_slLine = array.new_line(1)
var line a_entryLine = array.new_line(1)
var line a_tp3Line = array.new_line(1)
var line a_tp2Line = array.new_line(1)
var line a_tp1Line = array.new_line(1)
var label a_slLabel = array.new_label(1)
var label a_tp3label = array.new_label(1)
var label a_tp2label = array.new_label(1)
var label a_tp1label = array.new_label(1)
var label a_entryLabel = array.new_label(1)
newEntry = longE or shortE
entryIndex = 1
entryIndex := newEntry ? bar_index : nz(entryIndex )
lasTrade = bar_index >= entryIndex
l_right = 10
line.delete(
f_qDq(a_slLine,
line.new(
entryIndex,
slLine,
last_bar_index + l_right,
slLine,
style = line.style_solid,
color = c_sl)))
line.delete(
f_qDq(a_entryLine,
line.new(
entryIndex,
entryLine,
last_bar_index + l_right,
entryLine,
style = line.style_solid,
color = color.blue)))
line.delete(
f_qDq(a_tp3Line,
line.new(
entryIndex,
tp3Line,
last_bar_index + l_right,
tp3Line,
style = line.style_solid,
color = c_tp)))
line.delete(
f_qDq(a_tp2Line,
line.new(
entryIndex,
tp2Line,
last_bar_index + l_right,
tp2Line,
style = line.style_solid,
color = c_tp)))
line.delete(
f_qDq(a_tp1Line,
line.new(
entryIndex,
tp1Line,
last_bar_index + l_right,
tp1Line,
style = line.style_solid,
color = c_tp)))
label.delete(
f_qDq(a_slLabel,
label.new(
last_bar_index + l_right,
slLine,
'SL: ' + str.tostring(slLine, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_sl)))
label.delete(
f_qDq(a_entryLabel,
label.new(
last_bar_index + l_right,
entryLine,
'Entry: ' + str.tostring(entryLine, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = color.blue)))
label.delete(
f_qDq(a_tp3label,
label.new(
last_bar_index + l_right,
tp3Line,
'TP3: ' + str.tostring(tp3Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
label.delete(
f_qDq(a_tp2label,
label.new(
last_bar_index + l_right,
tp2Line,
'TP2: ' + str.tostring(tp2Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
label.delete(
f_qDq(a_tp1label,
label.new(
last_bar_index + l_right,
tp1Line,
'TP1: ' + str.tostring(tp1Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
// ———————————
//
if longE or shortE or longX or shortX
alert(message = 'Any Alert', freq = alert.freq_once_per_bar_close)
if longE
alert(message = 'Long Entry', freq = alert.freq_once_per_bar_close)
if shortE
alert(message = 'Short Entry', freq = alert.freq_once_per_bar_close)
if longX
alert(message = 'Long Exit', freq = alert.freq_once_per_bar_close)
if shortX
alert(message = 'Short Exit', freq = alert.freq_once_per_bar_close)
//#endregion }
// ——————————— <↑↑↑ G_SCRIPT03 ↑↑↑>
Zero LineHere's a professional description for publishing your Zero Line indicator on TradingView:
Title:
Zero Line - Reference Level Indicator
Description:
Overview
A clean and simple indicator that displays a prominent horizontal line at the zero level on your chart. Essential for traders who need a clear visual reference point for price action, momentum oscillators, or custom strategies.
Key Features
Clear Visual Reference - Instantly identify when price or indicators cross the zero threshold
Customizable Appearance - Adjust color, line style, and thickness to match your chart setup
Non-Intrusive - Lightweight indicator that won't clutter your workspace
Universal Compatibility - Works with all timeframes and market types
Use Cases
Price Action Trading - Monitor when price moves above/below key baseline levels
Spread Trading - Track positive/negative spreads between assets
P&L Visualization - See profit/loss transitions at a glance
Mean Reversion - Identify deviation from equilibrium points
Multi-Indicator Analysis - Align multiple oscillators with a common reference
How to Use
Add the indicator to any chart
Customize the line appearance in settings if desired
Use as a visual anchor point for your analysis
Ideal For
Scalpers and day traders needing quick visual references
Swing traders monitoring momentum shifts
Algorithmic traders backtesting strategies
Anyone requiring a fixed reference point on their charts
London & NY Sessions (CET + Offset)Clearly visualize the London and New York trading sessions on your chart with automatic timezone adjustment. This indicator is designed for traders who want to track key market sessions and identify periods of high liquidity and volatility.
🎯 Key Features
Visual Session Marking: Highlights London (9:00-12:00 CET) and New York (15:30-19:30 CET) sessions with colored boxes
Timezone Offset: Adjust display times from CET baseline to any timezone (-12 to +12 hours)
Customizable Display:
Toggle each session on/off independently
Adjust session colors and transparency
Optional session labels with size control
Subtle background highlighting during active sessions
Flexible Session Times: Modify start/end times for each session (hours and minutes)
Alert System: Built-in alerts for session starts and ends
Clean Design: Non-intrusive overlay that works on all timeframes
📝 Use Cases
Session Trading: Trade during high-volume periods when major markets are open
Overlap Trading: Identify when sessions overlap for maximum volatility
Time Zone Management: Perfect for traders in different time zones who need to track CET-based sessions
Scalping & Day Trading: Know exactly when institutional traders are most active
News Trading: Align your trading with economic releases from London and New York
⚙️ How to Use
Add to chart: Apply indicator to any instrument and timeframe
Set your timezone: Use the "Hour Offset from CET" to match your local time
Example: -1 for UK (GMT), -6 for US EST, +7 for Bangkok
Customize appearance: Adjust colors, transparency, and labels to your preference
Set alerts: Configure alerts for session starts/ends to never miss key market hours
🔧 Default Settings
London: 9:00-12:00 CET (European morning session)
New York: 15:30-19:30 CET (US afternoon, capturing EU/US overlap)
Colors: Blue for London, Orange for New York
Display: Both sessions enabled with labels
💡 Pro Tips
The New York session timing captures the crucial EU/US overlap period
Sessions automatically adjust for daylight saving time when using CET
Works on all markets: Forex, Indices, Commodities, Crypto
Combine with volume indicators for confirmation of session activity
Zarattini Intra-day Threshold Bands (ZITB)This indicator implements the intraday threshold band methodology described in the research paper by Carlo Zarattini et al.
papers.ssrn.com
Overview:
Plots intraday threshold bands based on daily open/close levels.
Supports visualization of BaseUp/BaseDown levels and Threshold Upper/Lower bands.
Optional shading between threshold bands for easier interpretation.
Usage Notes / Limitations:
Originally studied on SPY (US equities), this implementation is adapted for NSE intraday market timing, specifically the NIFTY50 index.
Internally, 2-minute candles are used if the chart timeframe is less than 2 minutes.
Values may be inaccurate if the chart timeframe is more than 1 day.
Lookback days are auto-capped to avoid exceeding TradingView’s 5000-bar limit.
The indicator automatically aligns intraday bars across multiple days to compute average deltas.
For better returns, it is recommended to use this indicator in conjunction with VWAP and a volatility-based position sizing mechanism.
Can be used as a reference for Open Range Breakout (ORB) strategies.
Customizations:
Toggle plotting of base levels and thresholds.
Toggle shading between thresholds.
Line colors and styles can be adjusted in the Style tab.
Author:
Gokul Ramachandran – software architect, engineer, programmer. Interested in trading and investment. Currently trading and researching strategies that can be employed in NSE (Indian market).
Contact: (mailto:gokul4trading@gmail.com)
LinkedIn: www.linkedin.com
Intended for educational and research purposes only.