Option Time ValueThis TradingView script calculates and visualizes the time value of an option (Call or Put) based on its market price and intrinsic value. The time value represents the premium paid for the option above its intrinsic value, and it is a key metric for analyzing the cost of holding an option.
This script is suitable for traders analyzing options on indices or stocks, such as the NIFTY 50, and supports both Call and Put options. By dynamically extracting the strike price and option type from the input symbol, it adapts seamlessly to the selected instrument.
Key Features:
Dynamic Instrument Selection:
Users can input the underlying asset (e.g., NSE:NIFTY) and the specific option instrument (e.g., NSE:NIFTY250327C24000 for a Call or NSE:NIFTY250327P24000 for a Put).
Automatic Option Type Detection:
The script detects whether the option is a Call or a Put by parsing the input symbol for the characters "C" (Call) or "P" (Put).
Dynamic Strike Price Extraction:
The strike price is dynamically extracted from the input option symbol, eliminating the need for hardcoding and reducing user errors.
Key Metrics Plotted:
Time Value: The premium paid above the intrinsic value, plotted in blue.
Intrinsic Value: The calculated intrinsic value of the option, plotted in green.
Seamless Integration:
Designed for ease of use and integration into existing TradingView setups.
Automatically adjusts to the timeframe and pricing data of the selected instruments.
Indicadores y estrategias
EMA X OverA simple indicator that plots two exponential moving averages (EMAs).
Upon a cross between the two EMAs, the chart will display a customizable marker. This marker may signal a change in direction of the price.
When a cross happened, wait for both EMAs to go in the same direction. The EMAs will both be in the same color when this happened.
When both EMAs are in the same color, look for the established trend.
Furthermore, when the price closes above or below the long EMA, the chart will also display a customizable marker.
Vertical Lines ExampleVertical Lines Example
timestamp: Used to create specific times for today (9:15 AM, 11:00 AM, and 1:00 PM).
isTodayAfterStart: Ensures that lines are drawn only after 9:15 AM.
line.new: Creates vertical lines at the specified times (11:00 AM and 1:00 PM).
style_dotted: Makes the lines dotted.
xloc.bar_time: Places the lines based on time on the chart.
Pi CycleIndicator Overview
The Pi Cycle Top Indicator has historically been effective in picking out the timing of market cycle highs within 3 days.
It uses the 111 day moving average (111DMA) and a newly created multiple of the 350 day moving average, the 350DMA x 2.
Note: The multiple is of the price values of the 350DMA, not the number of days.
For the past three market cycles, when the 111DMA moves up and crosses the 350DMA x 2 we see that it coincides with the price of Bitcoin peaking.
It is also interesting to note that 350 / 111 is 3.153, which is very close to Pi = 3.142. In fact, it is the closest we can get to Pi when dividing 350 by another whole number.
It once again demonstrates the cyclical nature of Bitcoin price action over long time frames. However, in this instance, it does so with a high degree of accuracy over Bitcoin's adoption phase of growth.
GG_EMA 50/200 Crossover with RSI StrategyThe script generates a long signal if the 50 ema crosses the 200 upwards and at the same time the RSI >50.
The script generates a short signal if the 50 ema crosses the 200 downwards and at the same time the RSI <50.
Hold Time With Percentage Drop Catastrophic ExitThis is a trading strategy developed for volatile markets. The system will look for breakouts in any market conditions with solid risk management in place. It incorporates a number of time-tested indicators that help it effectively balance capturing profit potential and controlling downside risk.
Key Features:
Breakout Detection Using Bands and Momentum Indicators:
Bollinger Bands: Finds possible breakout conditions where the price closes above the upper band amid periods of increased volatility.
MACD: This is for confirmation of momentum and trend alignment to increase the chances of successful breakouts. VWAP: This acts as an important level that ensures the price action is in the right intraday sentiment. Volatility and Volume Filters:
This strategy incorporates ATR for measuring market volatility and filtering out the strength of breakouts.
A relative volume filter ensures entry signals are well participated in by the market and filters low liquidity setups. Risk Management:
Minimum Holding Period: This prevents the strategy from prematurely exiting trades on minor pullbacks, allowing trends to form. The holding period is user-adjustable.
ATR-Based Emergency Exit: If the price falls by a certain percentage-a user input, such as 5%-from the entry price, calculated as a function of ATR, the position is immediately exited. This override prevents disastrous losses during turmoil.
Customizability:
Users can modify all the key parameters: Bollinger Band settings, holding periods, MACD configurations, ATR multipliers, and the percentage drop threshold. It also makes the strategy very versatile for different trading styles, instruments, and timeframes.
How It Works:
Entry Signals:
The strategy identifies a buy opportunity when the price breaks above the upper Bollinger Band with increasing ATR and volume, and MACD confirms bullish momentum. VWAP ensures that the price is above the average market sentiment level.
Minimum Holding Period:
Once a position is entered, the strategy enforces a minimum number of bars to hold before evaluating normal sell conditions. This rule prevents the strategy from prematurely exiting and ensures that trades have enough time to develop.
Emergency Exit:
If the price drops sharply-defined as a user-set percentage of the entry price, scaled by ATR-the strategy immediately exits, bypassing the minimum hold rule. This is protection against sudden and extreme losses under volatile conditions.
Exit Signals:
It further has a minimum holding period, after which it exits on its conditions under two indicators: MACD and VWAP, checking for loss of momentum or bearish conditions.
Use Case:
This will be a good approach for traders operating in volatile markets, focusing on breakout opportunities with strong risk management incorporated. It works well on intraday time frames but can be adapted to swing trading or longer-term strategies simply by adjusting the parameters.
Backtesting and Results:
Default settings are meant to return very realistic results in backtesting. Users should always test with the appropriate slippage, commission, and position sizing in relation to their actual trading environment.
Note:
This is an open-source script; for educational use only. Past performance is not indicative of future results. Traders should backtest/forward-test this idea before using it in live markets.
OPRA Option Ticker Parser + Implied VolAttempt at calculating implied vol of an US option using the OPRA feed. The goal is to see fixed strike vol. Need to check the result with other brokers, as I'm not strong in the Black–Scholes model.
Quick Response Indicator with Moving Averages//@version=5
indicator("Quick Response Indicator with Moving Averages", overlay=true)
// RSI Ayarları
rsiLength = input.int(14, title="RSI Length")
rsiOverbought = input.int(70, title="RSI Overbought Level")
rsiOversold = input.int(30, title="RSI Oversold Level")
rsiSource = input.source(close, title="RSI Source")
// Hareketli Ortalamalar (SMA ve EMA) Ayarları
smaLength = input.int(50, title="SMA Length")
emaLength = input.int(9, title="EMA Length")
smaSource = input.source(close, title="SMA Source")
emaSource = input.source(close, title="EMA Source")
// RSI Hesaplaması
rsiValue = ta.rsi(rsiSource, rsiLength)
// SMA ve EMA Hesaplamaları
smaValue = ta.sma(smaSource, smaLength)
emaValue = ta.ema(emaSource, emaLength)
// Al ve Sat sinyalleri
longSignal = rsiValue < rsiOversold and close > emaValue
shortSignal = rsiValue > rsiOverbought and close < emaValue
// Long ve Short sinyalleri için uyarılar
alertcondition(longSignal, title="Long Signal", message="RSI < Oversold and Close > EMA. Long Signal!")
alertcondition(shortSignal, title="Short Signal", message="RSI > Overbought and Close < EMA. Short Signal!")
// Sinyalleri grafikte gösterme
plotshape(series=longSignal, location=location.belowbar, color=color.green, style=shape.labelup, title="Long Signal", text="Long")
plotshape(series=shortSignal, location=location.abovebar, color=color.red, style=shape.labeldown, title="Short Signal", text="Short")
// SMA ve EMA'yı grafikte gösterme
plot(smaValue, color=color.blue, title="SMA", linewidth=2)
plot(emaValue, color=color.orange, title="EMA", linewidth=2)
// RSI'yı grafikte gösterme
plot(rsiValue, color=color.blue, title="RSI")
hline(rsiOverbought, "Overbought", color=color.red)
hline(rsiOversold, "Oversold", color=color.green)
Key Features:
RSI (Relative Strength Index):
RSI is used to identify overbought or oversold conditions in the market.
When RSI is above 70, it signals overbought conditions, and when RSI is below 30, it indicates oversold conditions.
These levels can help generate trading signals. For example, an oversold condition (RSI < 30) paired with price above EMA may trigger a Long (Buy) signal. Conversely, an overbought condition (RSI > 70) with price below EMA could trigger a Short (Sell) signal.
Moving Averages:
SMA (Simple Moving Average): A 50-period moving average that represents the simple average of the closing prices over a defined period.
EMA (Exponential Moving Average): A 9-period moving average that gives more weight to recent prices, making it more responsive to price changes.
The indicator uses EMA to determine the trend direction, and SMA is used for a longer-term trend indication.
Buy (Long) and Sell (Short) Signals:
Long Signal (Buy): A long signal is generated when RSI is below 30 (oversold) and the current price is above the EMA, indicating a potential upward movement.
Short Signal (Sell): A short signal is generated when RSI is above 70 (overbought) and the current price is below the EMA, indicating a potential downward movement.
Plotting on the Chart:
The SMA, EMA, and RSI are plotted on the chart to give you a visual indication of trend and market conditions.
Long and Short signals are displayed on the chart as green and red arrows, respectively, to help you spot potential entry and exit points quickly.
Alerts:
Alerts are set for Long and Short signals using the alertcondition function. You can use these alerts to notify you when the indicator generates a trade signal.
Advantages of the Indicator:
Quick Response: By combining RSI with EMA and SMA, this indicator allows you to react quickly to market movements and make rapid trading decisions.
Simplified Strategy: The strategy focuses on using moving averages for trend direction and RSI for identifying overbought/oversold conditions, making it ideal for traders who prefer faster results.
Visual Guidance: The clear visual representation of the moving averages, RSI, and trade signals on the chart makes it easy to follow and act on market trends.
MA 20, 50, 200//@version=5
indicator("MA 20, 50, 200", overlay=true)
// Calculate the 20-period, 50-period, and 100-period Simple Moving Averages
ma20 = ta.sma(close, 20)
ma50 = ta.sma(close, 50)
ma200 = ta.sma(close, 200)
// Plot the moving averages on the chart
plot(ma20, color=color.green, linewidth=2, title="MA 20")
plot(ma50, color=color.blue, linewidth=2, title="MA 50")
plot(ma200, color=color.red, linewidth=2, title="MA 200")
This function plots each of the moving averages on the chart.
The color parameter sets the color for each SMA:
MA 20 is plotted in green
MA 50 is plotted in blue
MA 200 is plotted in red
3 Volume Weighted Moving Average -trend-Macd (MTF)3 Volume Weighted Moving Average -trend-Macd (MTF)
ATR Stop-Loss CalculatorATR (Average True Range) kullanarak long ve short işlemleri için stop-loss seviyelerini hesaplar ve grafikte gösterir. Ayrıca Sağ üst köşede stop-loss seviyelerini bir tablo olarak görüntüler. Ayarlanabilir parametreler sayesinde esnek ve kullanıcı dostu bir araçtır.
Özellikler:
ATR'ye dayalı long ve short stop-loss seviyeleri.
Sağ üst köşede stop-loss seviyelerini gösteren tablo.
Kullanıcı tarafından özelleştirilebilir ATR uzunluğu, çarpanı ve hareketli ortalama uzunlukları.
Filtered ATR with EMA OverlayFiltered ATR with EMA Overlay is an advanced volatility indicator designed to provide a more accurate representation of market conditions by smoothing the standard Average True Range (ATR). This is achieved by filtering out extreme price movements and abnormal bars that can distort traditional ATR calculations.
The indicator applies an Exponential Moving Average (EMA) to the filtered ATR, creating a dual-layered system that highlights periods of increased or decreased volatility.
Key Features:
Filtered ATR: Filters out extreme bars, reducing noise and making the ATR line more reliable.
EMA Overlay: An EMA (default period of 10) is applied to the filtered ATR, allowing traders to track average volatility trends.
Volatility Signals:
Filtered ATR > EMA(10): Indicates higher-than-average volatility. This often correlates with trend breakouts or strong price movements.
Filtered ATR < EMA(10): Suggests reduced volatility, signaling potential consolidation or sideways price action.
Parameters:
atrLength (Default: 5):
The number of bars used to calculate the ATR. A shorter period (e.g., 3-5) responds faster to price changes, while a longer period (e.g., 10-14) provides smoother results.
multiplier (Default: 1.8):
Controls the sensitivity of the filter. A lower multiplier (e.g., 1.5) filters out more bars, resulting in smoother ATR. Higher values (e.g., 2.0) allow more bars to pass through, retaining more price volatility.
maxIterations (Default: 20):
The maximum number of bars processed to detect abnormal values. Increasing this may improve accuracy at the cost of performance.
ema10Period (Default: 10):
The period for the Exponential Moving Average applied to the filtered ATR. Shorter periods provide faster signals, while longer periods give smoother, lagging signals.
Trading Strategies:
1. Breakout Strategy:
When filtered ATR crosses above EMA(10):
Enter long positions when price breaks above a key resistance level.
Higher volatility suggests strong price action and momentum.
When filtered ATR drops below EMA(10):
Exit positions or tighten stop-loss orders as volatility decreases.
Lower volatility may indicate consolidation or trend exhaustion.
2. Trend Following Strategy:
Use the filtered ATR line to track overall volatility.
If filtered ATR consistently stays above EMA: Hold positions or add to trades.
If filtered ATR remains below EMA: Reduce position size or stay out of trades.
3. Mean Reversion Strategy:
When filtered ATR spikes significantly above EMA, it may indicate market overreaction.
Look for price to revert to the mean once ATR returns below the EMA.
4. Stop-Loss Adjustment:
As volatility increases (ATR above EMA), widen stop-loss levels to avoid being stopped out by random fluctuations.
In low volatility (ATR below EMA), tighten stop-losses to minimize losses during low activity periods.
Benefits:
Reduced Noise: By filtering abnormal bars, the indicator provides cleaner signals.
Better Trend Detection: EMA smoothing highlights volatility trends.
Adaptable: The indicator can be customized for scalping, day trading, or swing trading.
Intuitive Visualization: Traders can visually see volatility shifts and adjust strategies in real-time.
Best Practices:
Timeframes: Works effectively on all timeframes, but higher timeframes (e.g., 1H, 4H, Daily) yield more reliable signals.
Markets: Suitable for forex, crypto, stocks, and commodities.
Combining Indicators: Use in combination with RSI, Moving Averages, Bollinger Bands, or price action analysis for stronger signals.
How It Works (Under the Hood):
The script calculates the Daily Range (High - Low) for each bar.
The largest and smallest bars are filtered out if their difference exceeds the multiplier (default 1.8).
The remaining bars are averaged to generate the filtered ATR.
An EMA(10) is then applied to the filtered ATR for smoother visualization.
Filtered ATR with EMA OverlayFiltered ATR with EMA Overlay is an advanced volatility indicator designed to provide a more accurate representation of market conditions by smoothing the standard Average True Range (ATR). This is achieved by filtering out extreme price movements and abnormal bars that can distort traditional ATR calculations.
The indicator applies an Exponential Moving Average (EMA) to the filtered ATR, creating a dual-layered system that highlights periods of increased or decreased volatility.
Key Features:
Filtered ATR: Filters out extreme bars, reducing noise and making the ATR line more reliable.
EMA Overlay: An EMA (default period of 10) is applied to the filtered ATR, allowing traders to track average volatility trends.
Volatility Signals:
Filtered ATR > EMA(10): Indicates higher-than-average volatility. This often correlates with trend breakouts or strong price movements.
Filtered ATR < EMA(10): Suggests reduced volatility, signaling potential consolidation or sideways price action.
Parameters:
atrLength (Default: 5):
The number of bars used to calculate the ATR. A shorter period (e.g., 3-5) responds faster to price changes, while a longer period (e.g., 10-14) provides smoother results.
multiplier (Default: 1.8):
Controls the sensitivity of the filter. A lower multiplier (e.g., 1.5) filters out more bars, resulting in smoother ATR. Higher values (e.g., 2.0) allow more bars to pass through, retaining more price volatility.
maxIterations (Default: 20):
The maximum number of bars processed to detect abnormal values. Increasing this may improve accuracy at the cost of performance.
ema10Period (Default: 10):
The period for the Exponential Moving Average applied to the filtered ATR. Shorter periods provide faster signals, while longer periods give smoother, lagging signals.
Trading Strategies:
1. Breakout Strategy:
When filtered ATR crosses above EMA(10):
Enter long positions when price breaks above a key resistance level.
Higher volatility suggests strong price action and momentum.
When filtered ATR drops below EMA(10):
Exit positions or tighten stop-loss orders as volatility decreases.
Lower volatility may indicate consolidation or trend exhaustion.
2. Trend Following Strategy:
Use the filtered ATR line to track overall volatility.
If filtered ATR consistently stays above EMA: Hold positions or add to trades.
If filtered ATR remains below EMA: Reduce position size or stay out of trades.
3. Mean Reversion Strategy:
When filtered ATR spikes significantly above EMA, it may indicate market overreaction.
Look for price to revert to the mean once ATR returns below the EMA.
4. Stop-Loss Adjustment:
As volatility increases (ATR above EMA), widen stop-loss levels to avoid being stopped out by random fluctuations.
In low volatility (ATR below EMA), tighten stop-losses to minimize losses during low activity periods.
Benefits:
Reduced Noise: By filtering abnormal bars, the indicator provides cleaner signals.
Better Trend Detection: EMA smoothing highlights volatility trends.
Adaptable: The indicator can be customized for scalping, day trading, or swing trading.
Intuitive Visualization: Traders can visually see volatility shifts and adjust strategies in real-time.
Best Practices:
Timeframes: Works effectively on all timeframes, but higher timeframes (e.g., 1H, 4H, Daily) yield more reliable signals.
Markets: Suitable for forex, crypto, stocks, and commodities.
Combining Indicators: Use in combination with RSI, Moving Averages, Bollinger Bands, or price action analysis for stronger signals.
How It Works (Under the Hood):
The script calculates the Daily Range (High - Low) for each bar.
The largest and smallest bars are filtered out if their difference exceeds the multiplier (default 1.8).
The remaining bars are averaged to generate the filtered ATR.
An EMA(10) is then applied to the filtered ATR for smoother visualization.
NAG_SMA IndicatorHi All,
This is SMA indicator with multiple SMA values.
You can select SMA as per your strategy.
Regards,
Nilesh Ghadshi
@nghadshi2389
AmirAli ShiraniBacktest within Specific Date Range . This is a test for understanding it work or not
6 Moving Average SimpleYou can display 6 SMAs. It’s simple, so feel free to adjust it as you like. Your support would be a great motivator for creating new indicators.
6本のSMAを表示できます。
シンプルですので、ご自由に調整してください。
応援頂けると新たなインジケーター作成の糧になります。
Nahum - ZLSMA for Telegram [Nahum81]Este indicador ZLSMA (Zero Lag Least Squares Moving Average) proporciona una media móvil con un retraso casi nulo, lo que permite identificar la dirección de la tendencia de forma instantánea.
Características:
Alertas de Telegram: Recibe notificaciones en tiempo real en tu Telegram cuando se produzcan señales de compra o venta.
Integración con Telegram: Conéctate fácilmente a tu cuenta de Telegram para recibir alertas.
Configuración personalizable: Ajusta los parámetros del indicador y las alertas a tu estrategia de trading.
Advertencia:
Este indicador debe usarse con precaución.
Se recomienda contactar al desarrollador (@Nahum81) para comprender completamente la estrategia y su uso adecuado.
El trading implica riesgos y este indicador no garantiza ganancias.
Nahum - ZLSMA for Telegram [Nahum81]Este indicador ZLSMA (Zero Lag Least Squares Moving Average) proporciona una media móvil con un retraso casi nulo, lo que permite identificar la dirección de la tendencia de forma instantánea.
Características:
Alertas de Telegram: Recibe notificaciones en tiempo real en tu Telegram cuando se produzcan señales de compra o venta.
Integración con Telegram: Conéctate fácilmente a tu cuenta de Telegram para recibir alertas.
Configuración personalizable: Ajusta los parámetros del indicador y las alertas a tu estrategia de trading.
Advertencia:
Este indicador debe usarse con precaución.
Se recomienda contactar al desarrollador (@Nahum81) para comprender completamente la estrategia y su uso adecuado.
El trading implica riesgos y este indicador no garantiza ganancias.
Garrys Pair DifferenceFirst pair should be futures, second pair is spot
Plots extents and when the extents have a higher high or lower low it plots a circle
ST+SQZMOM v.3// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © syahdan modifying LazyBear script and many sources
//======================================================================================================================
//@version=6
indicator('ST+SQZMOM v.3', overlay = true, max_lines_count = 40)
import TradingView/ta/9
//======================================================================================================================
//groups
Alerts = 'alert'
Supertrend = 'supertrend'
SqzMom = 'sqzMom'
Sma = 'ma'
TS = 'tp/sl'
// Input switches for alerts
alertTrendChange = input.bool(true, title='Enable Trend Change Alert', group = Alerts)
alertSQZMOM = input.bool(true, title='Enable SQZMOM Alerts', group = Alerts)
// Supertrend Inputs
atrPeriod = input.int(10, 'ATR Length', minval = 1, group = Supertrend)
factor = input.float(2.5, 'Factor', minval = 0.01, step = 0.01, group = Supertrend)
// Squeeze Momentum Indicator Inputs
sources = input(close, 'Source', group = SqzMom)
bbLength = input.int(20, 'Bollinger Bands Length', minval = 1, group = SqzMom)
bbMult = input.float(2, 'Bollinger Bands MultFactor', step = 0.25, group = SqzMom)
kcLength = input(20, 'Keltner\'s Channel Length', group = SqzMom)
kcMult = input.float(1.5, 'Keltner\'s Channel MultFactor', step = 0.25, group = SqzMom)
useTrueRange = input(true, 'Use TrueRange (Keltner\'s Channel)', group = SqzMom)
addSignal = input.bool(false, title = 'add Signal to Calculate direction', group = SqzMom)
signalLength = input(5, 'Signal Length', group = SqzMom)
tooltip_sqz = 'show momentum direction, BB band and KC band'
showBB = input.bool(false, 'show BBand', tooltip = tooltip_sqz, group = SqzMom)
showKC = input.bool(false, 'show keltner channel', tooltip = tooltip_sqz, group = SqzMom)
showDir= input.bool(false, 'show squeeze direction', tooltip = tooltip_sqz, group = SqzMom)
// Customizable thresholds
lowerThreshold = input(-1.0, title = 'Lower Threshold', group = SqzMom)
upperThreshold = input(1.0, title = 'Upper Threshold', group = SqzMom)
// SMA Input settings
lengthMA = input(200, title="MA Period", group = Sma)
showMA = input.bool(true, title="Show MA", group = Sma)
addsave = input.bool(true, title = 'add MA as filter', group = Alerts)
// Hardcoded tp + sl multipliers
targetMultiplier1 = input.int(1, 'TP1 multiply', minval = 1, group = TS)
targetMultiplier2 = input.int(2, 'TP2 multiply', minval = 2, group = TS)
targetMultiplier3 = input.int(3, 'TP3 multiply', minval = 3, group = TS)
stopLossMultiplier = input.int(3, 'SL multiply', minval = 3, group = TS)
//======================================================================================================================
// Calculate Supertrend
= ta.supertrend(factor, atrPeriod)
// Plot the Supertrend line
plot(supertrend, color = direction < 0 ? color.green : color.red, title = 'ST', style = plot.style_stepline_diamond)
// Determine if the trend is up or down
upTrend = direction < 0
downTrend = direction > 0
// Track previous trend state
var int previousDirection = na
previousDirection := upTrend ? 1 : -1
// Calculate ATR for targets and stop loss
atrValue = ta.atr(atrPeriod)
// Initialize target and stop loss levels
var float entryPrice = na
var float targetLevel1 = na
var float targetLevel2 = na
var float targetLevel3 = na
var float stopLossLevel = na
// Initialize counters for lines and labels
var int count_up = 0
var int count_down = 0
// Initialize a new variable to track if new lines and labels are drawn
var bool newLinesDrawn = false
// Calculate BB
basis = ta.sma(sources, bbLength)
dev = bbMult * ta.stdev(sources, bbLength)
bbUpper = basis + dev
bbLower = basis - dev
// Calculate KC
ma = ta.sma(sources, kcLength)
trRange = useTrueRange ? ta.tr : high - low
rangema = ta.sma(trRange, kcLength)
kcUpper = ma + rangema * kcMult
kcLower = ma - rangema * kcMult
sqzOn = bbLower > kcLower and bbUpper < kcUpper
sqzOff = bbLower < kcLower and bbUpper > kcUpper
noSqz = sqzOn == false and sqzOff == false
val = ta.linreg(sources - math.avg(math.avg(ta.highest(high, kcLength), ta.lowest(low, kcLength)), ta.sma(sources, kcLength)), kcLength, 0)
signal = ta.sma(val, signalLength)
dir = not addSignal ? val : val - signal
// Calculate SMA
MA = ta.sma(sources,lengthMA)
saveEntryBuy = addsave ? MA < close : false
saveEntrySell = addsave ? MA > close : false
//======================================================================================================================
// Plot SMA
plot(showMA ? MA : na, color=color.white, linewidth=2, title='MA')
triangUp = sqzOff and dir > dir and dir >= upperThreshold
triangDown = sqzOff and dir < dir and dir <= lowerThreshold
triangUpR = sqzOff and dir < dir and dir >= upperThreshold
triangDownR = sqzOff and dir > dir and dir <= lowerThreshold
insideThreshold = sqzOff and upperThreshold > dir and dir > lowerThreshold
// Calculate target and stop loss levels
if upTrend and triangUp
entryPrice := close
targetLevel1 := close + atrValue * targetMultiplier1
targetLevel2 := close + atrValue * targetMultiplier2
targetLevel3 := close + atrValue * targetMultiplier3
stopLossLevel := close - atrValue * stopLossMultiplier
count_up := count_up + 1
count_down := 0
else if downTrend and triangDown
entryPrice := close
targetLevel1 := close - atrValue * targetMultiplier1
targetLevel2 := close - atrValue * targetMultiplier2
targetLevel3 := close - atrValue * targetMultiplier3
stopLossLevel := close + atrValue * stopLossMultiplier
count_down := count_down + 1
count_up := 0
// Plotting Squeeze Momentum Indicator
plotshape(sqzOn or noSqz, 'In Squeeze', shape.square, location.top, color=sqzOn or noSqz ? color.new(color.orange, 0) : color.new(color.white, 0))
plotshape(triangUp or triangUpR, 'Squeeze Release UpTrend', shape.triangleup, location.top, color=triangUp ? color.new(color.green, 0) : color.new(color.yellow, 0))
plotshape(triangDown or triangDownR, 'Squeeze Release DownTrend', shape.triangledown, location.top, color=triangDown ? color.new(color.red, 0) : color.new(color.yellow, 0))
plotshape(insideThreshold, 'inside threshold', shape.diamond, location.top, color.new(color.white, 0) )
// Draw lines and labels for targets and stop loss
var line stopLossLine = na
var line entryLine = na
var line targetLine1 = na
var line targetLine2 = na
var line targetLine3 = na
var label stopLossLabel = na
var label entryLabel = na
var label targetLabel1 = na
var label targetLabel2 = na
var label targetLabel3 = na
// Clear previous lines and labels if a new trend is confirmed
if upTrend and triangUp and count_up == 1
// Clear previous lines and labels
line.delete(stopLossLine)
line.delete(entryLine)
line.delete(targetLine1)
line.delete(targetLine2)
line.delete(targetLine3)
label.delete(stopLossLabel)
label.delete(entryLabel)
label.delete(targetLabel1)
label.delete(targetLabel2)
label.delete(targetLabel3)
// Draw new lines + 10 bars into the future
stopLossLine := line.new(bar_index, stopLossLevel, last_bar_index + 10, stopLossLevel, color = color.red, width = 2)
entryLine := line.new(bar_index, close, last_bar_index + 10, close, color = color.green, width = 2)
targetLine1 := line.new(bar_index, targetLevel1, last_bar_index + 10, targetLevel1, color = color.blue, width = 2)
if saveEntryBuy
targetLine2 := line.new(bar_index, targetLevel2, last_bar_index + 10, targetLevel2, color = color.blue, width = 2)
targetLine3 := line.new(bar_index, targetLevel3, last_bar_index + 10, targetLevel3, color = color.blue, width = 2)
// Set the newLinesDrawn flag to true
newLinesDrawn := true
// Draw new labels with three decimal places
stopLossLabel := label.new(last_bar_index + 10, stopLossLevel, 'SL: ' + str.tostring(stopLossLevel, '#.###'), style = label.style_label_left, color = color.red, textcolor = color.white)
entryLabel := label.new(last_bar_index + 10, close, 'Entry: ' + str.tostring(close, '#.###'), style = label.style_label_left, color = color.green, textcolor = color.white)
targetLabel1 := label.new(last_bar_index + 10, targetLevel1, 'TP 1: ' + str.tostring(targetLevel1, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
if saveEntryBuy
targetLabel2 := label.new(last_bar_index + 10, targetLevel2, 'TP 2: ' + str.tostring(targetLevel2, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
targetLabel3 := label.new(last_bar_index +10, targetLevel3, 'TP 3: ' + str.tostring(targetLevel3, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
if downTrend and triangDown and count_down == 1
// Clear previous lines and labels
line.delete(stopLossLine)
line.delete(entryLine)
line.delete(targetLine1)
line.delete(targetLine2)
line.delete(targetLine3)
label.delete(stopLossLabel)
label.delete(entryLabel)
label.delete(targetLabel1)
label.delete(targetLabel2)
label.delete(targetLabel3)
// Draw new lines + 10 bars into the future
stopLossLine := line.new(bar_index, stopLossLevel, last_bar_index + 10, stopLossLevel, color = color.red, width = 2)
entryLine := line.new(bar_index, close, last_bar_index + 10, close, color = color.green, width = 2)
targetLine1 := line.new(bar_index, targetLevel1, last_bar_index + 10, targetLevel1, color = color.blue, width = 2)
if saveEntrySell
targetLine2 := line.new(bar_index, targetLevel2, last_bar_index + 10, targetLevel2, color = color.blue, width = 2)
targetLine3 := line.new(bar_index, targetLevel3, last_bar_index + 10, targetLevel3, color = color.blue, width = 2)
// Set the newLinesDrawn flag to true
newLinesDrawn := true
// Draw new labels with three decimal places
stopLossLabel := label.new(last_bar_index + 10, stopLossLevel, 'SL: ' + str.tostring(stopLossLevel, '#.###'), style = label.style_label_left, color = color.red, textcolor = color.white)
entryLabel := label.new(last_bar_index + 10, close, 'Entry: ' + str.tostring(close, '#.###'), style = label.style_label_left, color = color.green, textcolor = color.white)
targetLabel1 := label.new(last_bar_index + 10, targetLevel1, 'TP 1: ' + str.tostring(targetLevel1, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
if saveEntrySell
targetLabel2 := label.new(last_bar_index + 10, targetLevel2, 'TP 2: ' + str.tostring(targetLevel2, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
targetLabel3 := label.new(last_bar_index + 10, targetLevel3, 'TP 3: ' + str.tostring(targetLevel3, '#.###'), style = label.style_label_left, color = color.blue, textcolor = color.white)
// Plot momentum strength/direction
plotarrow(showDir ? dir : na, 'Momentum Strength/Direction', color.new(color.aqua, 50), color.new(color.orange, 50), show_last = 500)
plot(showBB ? bbUpper : na, 'BBUpper', color.new(color.blue, 25), show_last = 500)
plot(showBB ? bbLower : na, 'BBLower', color.new(color.blue, 25), show_last = 500)
plot(showKC ? kcUpper : na, 'KCUpper', color.new(color.red, 25), show_last = 500)
plot(showKC ? kcLower : na, 'KCLower', color.new(color.red, 25), show_last = 500)
//======================================================================================================================
// Trigger alert when squeeze is released
if sqzOn and not sqzOn
alert('Squeeze On : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if sqzOff and not sqzOff // Only trigger alert if the squeeze was previously on
alert('Squeeze Off : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if triangDown and not triangDown // Only trigger alert if the squeeze was previously on
alert('Weak TrendDown or Reverse : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if triangUp and not triangUp // Only trigger alert if the squeeze was previously on
alert('Weak TrendUp or Reverse : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if insideThreshold and not insideThreshold //trigger when entering threshold channel
alert('inside threshold : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if triangUpR and triangUp
alert('Trend Up Cont : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
if triangDownR and triangDown
alert('Trend Down Cont : '+ syminfo.tickerid + ' | ' + timeframe.period, alert.freq_once_per_bar_close)
// Alert for trend change when new lines and labels are drawn
if newLinesDrawn
saveEntry = addsave ? 'safe' : 'adrenaline'
trendType = upTrend ? 'Buy' : 'Sell'
stopLossValue = str.tostring(stopLossLevel, '#.###')
entryValue = str.tostring(close, '#.###')
targetValue1 = str.tostring(targetLevel1, '#.###')
targetValue2 = saveEntryBuy or saveEntrySell ? str.tostring(targetLevel2, '#.###') : '---'
targetValue3 = saveEntryBuy or saveEntrySell ? str.tostring(targetLevel3, '#.###') : '---'
alertMessage = 'Mode : '+ saveEntry +' ' +
'Pair : ' + syminfo.tickerid + ' | ' + timeframe.period + ' ' +
'Trend : ' + trendType + ' ' +
'SL : ' + stopLossValue + ' ' +
'Ent : ' + entryValue + ' ' +
'TP1 : ' + targetValue1 + ' ' +
'TP2 : ' + targetValue2 + ' ' +
'TP3 : ' + targetValue3
if alertTrendChange
alert(alertMessage, alert.freq_once_per_bar_close)
// Reset the newLinesDrawn flag
newLinesDrawn := false