Dual Chain StrategyDual Chain Strategy - Technical Overview 
 How It Works: 
The Dual Chain Strategy is a unique approach to trading that utilizes Exponential Moving Averages (EMAs) across different timeframes, creating two distinct "chains" of trading signals. These chains can work  independently  or together, capturing both long-term trends and short-term price movements.
 Chain 1 (Longer-Term Focus): 
 Entry Signal:  The entry signal for Chain 1 is generated when the closing price crosses above the EMA calculated on a weekly timeframe. This suggests the start of a bullish trend and prompts a long position.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
 Exit Signal:  The exit signal is triggered when the closing price crosses below the EMA on a daily timeframe, indicating a potential bearish reversal.
exitLongChain1 = enableChain1 and ta.crossunder(src1, exitEMA1)
 Parameters:  Chain 1's EMA length is set to 10 periods by default, with the flexibility for user adjustment to match various trading scenarios.
 Chain 2 (Shorter-Term Focus): 
 Entry Signal:  Chain 2 generates an entry signal when the closing price crosses above the EMA on a 12-hour timeframe. This setup is designed to capture quicker, shorter-term movements.
bullishChain2 = enableChain2 and ta.crossover(src2, entryEMA2)
 Exit Signal:  The exit signal occurs when the closing price falls below the EMA on a 9-hour timeframe, indicating the end of the shorter-term trend.
exitLongChain2 = enableChain2 and ta.crossunder(src2, exitEMA2)
 Parameters:  Chain 2's EMA length is set to 9 periods by default, and can be customized to better align with specific market conditions or trading strategies.
 Key Features: 
 Dual EMA Chains:  The strategy's originality shines through its dual-chain configuration, allowing traders to monitor and react to both long-term and short-term market trends. This approach is particularly powerful as it combines the strengths of trend-following with the agility of momentum trading.
 Timeframe Flexibility:  Users can modify the timeframes for both chains, ensuring the strategy can be tailored to different market conditions and individual trading styles. This flexibility makes it versatile for various assets and trading environments.
 Independent Trade Logic:  Each chain operates independently, with its own set of entry and exit rules. This allows for simultaneous or separate execution of trades based on the signals from either or both chains, providing a robust trading system that can handle different market phases.
 Backtesting Period:  The strategy includes a configurable backtesting period, enabling thorough performance assessment over a historical range. This feature is crucial for understanding how the strategy would have performed under different market conditions.
time_cond = time >= startDate and time <= finishDate
 What It Does: 
The Dual Chain Strategy offers traders a distinctive trading tool that merges two separate EMA-based systems into one cohesive framework. By integrating both long-term and short-term perspectives, the strategy enhances the ability to adapt to changing market conditions. The originality of this script lies in its innovative dual-chain design, providing traders with a unique edge by allowing them to capitalize on both significant trends and smaller, faster price movements.
Whether you aim to capture extended market trends or take advantage of more immediate price action, the Dual Chain Strategy provides a comprehensive solution with a high degree of customization and strategic depth. Its flexibility and originality make it a valuable tool for traders seeking to refine their approach to market analysis and execution.
 How to Use the Dual Chain Strategy 
 Step 1: Access the Strategy 
Add the Script: Start by adding the Dual Chain Strategy to your TradingView chart. You can do this by searching for the script by name or using the link provided.
Select the Asset: Apply the strategy to your preferred trading pair or asset, such as #BTCUSD, to see how it performs.
 Step 2: Configure the Settings 
Enable/Disable Chains:
The strategy is designed with two independent chains. You can choose to enable or disable each chain depending on your trading style and the market conditions.
enableChain1 = input.bool(true, title='Enable Chain 1')
enableChain2 = input.bool(true, title='Enable Chain 2')
By default, both chains are enabled. If you prefer to focus only on longer-term trends, you might disable Chain 2, or vice versa if you prefer shorter-term trades.
Set EMA Lengths:
Adjust the EMA lengths for each chain to match your trading preferences.
Chain 1: The default EMA length is 10 periods. This chain uses a weekly timeframe for entry signals and a daily timeframe for exits.
len1 = input.int(10, minval=1, title='Length Chain 1 EMA', group="Chain 1")
Chain 2: The default EMA length is 9 periods. This chain uses a 12-hour timeframe for entries and a 9-hour timeframe for exits.
len2 = input.int(9, minval=1, title='Length Chain 2 EMA', group="Chain 2")
Customize Timeframes:
You can customize the timeframes used for entry and exit signals for both chains.
Chain 1:
Entry Timeframe: Weekly
Exit Timeframe: Daily
tf1_entry = input.timeframe("W", title='Chain 1 Entry Timeframe', group="Chain 1")
tf1_exit = input.timeframe("D", title='Chain 1 Exit Timeframe', group="Chain 1")
Chain 2:
Entry Timeframe: 12 Hours
Exit Timeframe: 9 Hours
tf2_entry = input.timeframe("720", title='Chain 2 Entry Timeframe (12H)', group="Chain 2")
tf2_exit = input.timeframe("540", title='Chain 2 Exit Timeframe (9H)', group="Chain 2")
Set the Backtesting Period:
Define the period over which you want to backtest the strategy. This allows you to see how the strategy would have performed historically.
startDate = input.time(timestamp('2015-07-27'), title="StartDate")
finishDate = input.time(timestamp('2026-01-01'), title="FinishDate")
 Step 3: Analyze the Signals 
Understand the Entry and Exit Signals:
Buy Signals: When the price crosses above the entry EMA, the strategy generates a buy signal.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
Sell Signals: When the price crosses below the exit EMA, the strategy generates a sell signal.
bearishChain2 = enableChain2 and ta.crossunder(src2, entryEMA2)
Review the Visual Indicators:
The strategy plots buy and sell signals on the chart with labels for easy identification:
BUY C1/C2 for buy signals from Chain 1 and Chain 2.
SELL C1/C2 for sell signals from Chain 1 and Chain 2.
This visual aid helps you quickly understand when and why trades are being executed.
 Step 4: Optimize the Strategy 
Backtest Results:
Review the strategy’s performance over the backtesting period. Look at key metrics like net profit, drawdown, and trade statistics to evaluate its effectiveness.
Adjust the EMA lengths, timeframes, and other settings to see how changes affect the strategy’s performance.
Customize for Live Trading:
Once satisfied with the backtest results, you can apply the strategy settings to live trading. Remember to continuously monitor and adjust as needed based on market conditions.
 Step 5: Implement Risk Management 
Use Realistic Position Sizing:
Keep your risk exposure per trade within a comfortable range, typically between 1-2% of your trading capital.
Set Alerts:
Set up alerts for buy and sell signals, so you don’t miss trading opportunities.
Paper Trade First:
Consider running the strategy in a paper trading account to understand its behavior in real market conditions before committing real capital.
 This dual-layered approach offers a distinct advantage: it enables the strategy to adapt to varying market conditions by capturing both broad trends and immediate price action without one chain's activity impacting the other's decision-making process. The independence of these chains in executing transactions adds a level of sophistication and flexibility that is rarely seen in more conventional trading systems, making the Dual Chain Strategy not just unique, but a powerful tool for traders seeking to navigate complex market environments. 
"the script" için komut dosyalarını ara
Three Drive Pattern Detector [LuxAlgo]The  Three Drives Pattern Detector  indicator focuses on detecting and displaying completed  Three Drives  patterns on the user chart. This harmonic pattern is characterized by successive higher highs / lower lows following specific ratios.
The script uses a multi-length swing detection approach, as well as adjusting ratios to ensure flexibility and a maximum number of visible  Three Drives  patterns.
🔶  USAGE 
  
The bullish/bearish  Three Drives  pattern is commonly interpreted as a reversal pattern and is characterized by three extensions (drives) and two intermediary retracements creating consecutive higher lows (for a bullish case) or lower highs (for a bearish case).
  
The multi-length swing detection approach taken by the indicator allows for detecting shorter-term alongside medium/longer-term patterns simultaneously, allowing to increase in the amount of detected patterns.
  
Users can set a  Minimum Swing length  (for example 2) and a  Maximum Swing length  (for example 100) which defines the range of the swing point detection length, higher values for these settings will detect longer-term Three-Drives patterns, while a larger range will allow for the detection of a larger number of patterns.
  
Sometimes multiple dashed lines as the last segment can be observed. This means multiple  Three Drives  patterns sharing multiple swing points have formed, with only the last segment being different.
🔹  Retracement/Extension Ratios 
  
The  Three Drives  pattern often associates the retracement/extension to Fibonacci ratios of respectively 0.618/1.272.
Some sources specify a maximum retracement/extension level of 0.786/1.618, which means the retracement should be within the 0.618-0.786 range and the extension between 1.272-1.618.
Since finding a pattern where the retracement/extension is precisely at the 0.618/1.272 levels, or even between 0.618-0.786/1.272-1.618 is rare, the script allows users to adjust those ratios, which ensures more flexibility. Depending on the widening/tightening of the ratios, allowing users to find more patterns (but potentially less valid) or more valid (but fewer patterns).
  
In the example above, " Show Ratios " is set to " Ratios With Margin ", showing the ideal retracement/extension level together with the margin, while in the example below, " Show Ratios " is set to " Ratios ", which shows only a line where the price should ideally reverse.  
  
While setting the ratios wider will result in more frequent but less valid patterns, it can also create good trading opportunities. 
  
🔹  Best Practices 
The indicator doesn't include Stop Loss (SL) or Take Profit (TP) levels, however, the 1.618 Fibonacci Extension level of the last leg can commonly be used as stop loss. 
Typical Take Profit areas include:
 
 Starting point of the pattern
 Each retracement level (2x)
 The 0.618 retracement level of the complete pattern
 
  
In the above bullish examples, the price was lower than the lowest point of the pattern. The price reversed and attained all TP levels without hitting the SL level.
  
In the above bearish example, the price went above the highest point of the pattern but did not hit the SL level, after which two TP levels were hit. Then, the price quickly went up, just missing the SL level before it came back down again, hitting the last 2 TP levels.
  
This example shows that other Fibonacci levels an also be effective when combined with the Three Drives pattern, even in the longer term.
🔶  DETAILS 
🔹  Multi Length 
The core of this publication is the multi-length swing detection. To ensure the maximum amount of  Three Drives  patterns are found, up to 99 different swing length periods can be used to detect swing points which are then tested for valid patterns.
  
Using a wider variety of swing points also ensures that patterns visible only with specific Swing settings can be found on the same chart without the user needing to constantly adjust the Swing settings to find other patterns.
The user only needs to set the desired minimum and maximum Swing Length.
  
In this case, swing detection using swing Lengths from 3 to 100 (97 different) are computed and evaluated for patterns. Three different patterns were found on the same chart, with swing lengths 3, 4, and 6.
 Note:  The  Maximum Swing length  should be equal to or higher than the  Minimum Swing Length . If the maximum value is lower than the minimum, the script will automatically take the minimum value as the maximum to prevent errors.
🔹  Width Margin % 
  
Users can filter out patterns based on the duration of each extension/retracement segment. When the users want segments of the detected patterns to be of a similar duration, the width percentage should be set lower. When the focus is on detecting more patterns the width percentage can be set higher.
🔹  Retracement/Extension Settings 
  
 
 Show Ratios , set to  Ratios , show the ideal Fibonacci retracement/extension level, while  Ratios With Margin  (example below) show the additional margins for retracement/extension.
 The upper and lower limits can be visualized while hovering over the calculated ratio label.
 The dashed line shows an older pattern, where the last leg has been updated.
 
  
🔹  Last Known Pattern 
  
The included dashboard highlights the date of the most recently detected pattern; the text will show " None " if no pattern is found.
🔹  Calculated Bars 
The "Calculated Bars" setting makes use of the recently introduced  calc_bars_count  parameter, making it possible to effectively reduce the number of historical bars during the computation of the script, which significantly improves the loading speed of the script.
Users wishing to see the most recent patterns can set this setting to 1000 for example, where only the most recent 1000 bars are used to find patterns. If every bar must be used for pattern detection, set " Calculated bars " at 0.
🔶  SETTINGS 
 
 Minimum Swing Length: Minimum length used for the swing detection.
 Maximum Swing Length: Maximum length used for the swing detection.
 Retracement: Range of required ratios used for testing retracements. 
 Extension: Range of required ratios used for testing extensions.
 Width Margin: Influences the symmetry of the pattern; with a higher number allowing for less symmetry.
  
🔹  Style 
 
 Text Size: Text size of the ratio labels.
 Show Ratios: Show the ideal ratio, upper/lower limit of ratios, or none.
  
🔹  Dashboard 
 
 Show Dashboard: Toggle dashboard which shows the date of the last found pattern.
 Location: Location of the dashboard on the chart.
 Size: Text size.
  
🔹  Calculation 
 
 Calculated Bars: Allows the usage of fewer bars for performance/speed improvement.
  
Prometheus Black-Scholes Option PricesThe Black-Scholes Model is an option pricing model developed my Fischer Black and Myron Scholes in 1973 at MIT. This is regarded as the most accurate pricing model and is still used today all over the world. This script is a simulated Black-Scholes model pricing model, I will get into why I say simulated.
 What is an option? 
An option is the right, but not the obligation, to buy or sell 100 shares of a certain stock, for calls or puts respective, at a certain price, on a certain date (assuming European style options, American options can be exercised early). The reason these agreements, these  contracts  exist is to provide traders with leverage. Buying 1 contract to represent 100 shares of the underlying, more often than not, at a cheaper price. That is why the price of the option, the  premium , is a small number. If an option costs $1.00 we pay $100.00 for it because 100 shares * 1 dollar per share = 100 dollars for all the shares. When a trader purchases a call on stock XYZ with a strike of $105 while XYZ stock is trading at $100, if XYZ stock moves up to $110 dollars before expiration the option has $5 of intrinsic value. You have the right to buy something at $105 when it is trading at $110. That agreement is way more valuable now, as a result the options premium would increase. That is a quick overview about how options are traded, let's get into calculating them.
 Inputs for the Black-Scholes model 
To calculate the price of an option we need to know 5 things:
Current Price of the asset
Strike Price of the option
Time Till Expiration
Risk-Free Interest rate
Volatility
The price of a European call option 𝐶 is given by:
𝐶 = 𝑆0 * Φ(𝑑1) − 𝐾 * 𝑒^(−𝑟 * 𝑇) * Φ(𝑑2)
where:
𝑆0 is the current price of the underlying asset.
𝐾 is the strike price of the option.
𝑟 is the risk-free interest rate.
𝑇 is the time to expiration.
Φ is the cumulative distribution function of the standard normal distribution.
𝑑1 and 𝑑2 are calculated as:
𝑑1 = (ln(𝑆0 / 𝐾) + (𝑟 + (𝜎^2 / 2)) * 𝑇) / (𝜎 * sqrt(𝑇)) 
𝑑2= 𝑑1 - (𝜎 * sqrt(𝑇)) 
𝜎 is the volatility of the underlying asset.
The price of a European put option 𝑃 is given by:
𝑃 = 𝐾 * 𝑒^(−𝑟 * 𝑇) * Φ(−𝑑2) − 𝑆0 * Φ(−𝑑1)
where 𝑑1 and 𝑑2 are as defined above.
Key Assumptions of the Black-Scholes Model
The price of the underlying asset follows a lognormal distribution.
There are no transaction costs or taxes.
The risk-free interest rate and volatility of the underlying asset are constant.
The underlying asset does not pay dividends during the life of the option.
The markets are efficient, meaning that all known information is already reflected in the prices.
Options can only be exercised at expiration (European-style options).
 Understanding the Script 
  
Here I have arrows pointing to specific spots on the table. They point to  Historical Volatility  and  Inputted DTE .  Inputted DTE  is a value the user may input to calculate premium for options that expire in that many days.  Historical Volatility , is the value calculated by this code. 
 length = 252 // One year of trading days
hv = ta.stdev(math.log(close / close ), length) * math.sqrt(365) 
And then made daily like the Black-Scholes model needs from this step in the code.
 hv_daily = request.security(syminfo.tickerid, "1D", hv) 
The user has the option to input their own volatility to the Script. I will get into why that may be advantageous in a moment. If the user chooses to do so the Script will change which value it is using as so.
 hv_in_use = which_sig == false ? hv_daily : sig 
  
There is a lot going on in this image but bare with me, it will all make sense by the end. The column to the far left of both the green and maroon colored columns represent the strike price of the contract, if the numbers are white that means the contract is out of the money, gray means in the money. If you remember from the calculation this represents the price to buy or sell shares at, for calls or puts respective. The column second from the left shows a value for  Simulated Market Price . This is a necessary part of this script so we can show changes in implied volatility. See, when we go to our brokerages and look at options prices, sure the price was calculated by a pricing model, but that is rarely the true price of the model. Market participant sentiment affects this value as their estimates for future volatility,  Implied Volatility  changes. 
For example, if a call option is supposed to be worth $1.00 from the pricing model, however everyone is bullish on the stock and wants to buy calls, the premium may go to $1.20 from $1.00 because participants juice up the  Implied Volatility . Higher  Implied Volatility  generally means higher premium, given enough time to expiration. Buying an option at $0.80 when it should be worth $1.00 due to changes in sentiment is a big part of the Quant Trading industry.
Of course I don't have access to an actual exchange so get prices, so I modeled participant decisions by adding or subtracting a small random value on the "perfect premium" from the Black-Scholes model, and solving for implied volatility using the Newton-Raphson method.
It is like when we have  speed = distance / time  if we know  speed  and  time , we can solve for  distance . 
This is what models the changing  Implied Volatility  in the table. The other column in the table, 3rd from the left, is the Black-Scholes model price without the changes of a random number. Finally, the 4th column from the left is that  Implied Volatility  value we calculated with the modified option price. 
 More on Implied Volatility 
 Implied Volatility  represents the future expected volatility of an asset. As it is the value in the future it is not know like Historical Volatility, only projected. We provide the user with the option to enter their own  Implied Volatility  to start with for better modeling of options close to expiration. If you want to model options 1 day from expiration you will probably have to enter a higher  Implied Volatility  so that way the prices will be higher. Since the underlying is so close to expiration they are traded so much and traders manipulate their  Implied Volatility , increasing their value. Be safe while trading these!
Thank you all for clicking on my indicator and reading this description! Happy coding, Happy trading, Be safe!
Good reference: www.investopedia.com
Supports & Resistances [UAlgo]The "Supports & Resistances  " indicator is designed to identify and visualize key support and resistance levels on the price chart. It utilizes the Average True Range (ATR) and Pivot Points to define the boundaries of S & R zones and considers historical price action to assess the strength of these zones.
 🔶 How to Obtain Zones 
The script continuously analyzes the price action and identifies potential support and resistance zones based on the following criteria:
 Zone Creation:  For swing highs, a zone is created with the high price at the zone length as the top and the top minus the Average True Range (ATR) as the bottom. Conversely, for swing lows, the zone is created with the low price at the zone length as the bottom and the low plus the ATR as the top.
  
 Zone Strength Calculation:  The script iterates through historical bars within the zone and counts how many times the price (low for support, high for resistance) touched but failed to break entirely through the zone. This count is assigned as the zone's "strength".
 Zone Display and Removal:  It identifying zones by assigning a "strength" value based on how many times the price has approached but failed to break the zone. This helps prioritize stronger potential support/resistance levels. Only zones exceeding the defined "strength threshold" are visually displayed on the chart. Weaker zones or those broken by price are automatically removed.
  
 🔶 Parameters 
 Zone Length:  Traders can adjust S & R detection sensitivity, length to be used to find pivot points.
 Strength Threshold:  Set the minimum number of times the price needs to touch but fail to break a zone for it to be considered "strong" and displayed.
 Visual Settings:  Tailor the appearance of the support/resistance zones by defining separate colors and text size for borders, backgrounds, and zone text.
 🔶 Disclaimer 
The "Supports & Resistances  " indicator is provided for educational and informational purposes only.
It should not be considered as financial advice or a recommendation to buy or sell any financial instrument.
The use of this indicator involves inherent risks, and users should employ their own judgment and conduct their own research before making any trading decisions. Past performance is not indicative of future results.
 🔷 Related Scripts 
 Support and Resistance with Signals  
  
 ATR Based Support and Resistance Zones  
 
Fibonacci Period Range [UkutaLabs]█ OVERVIEW
The Fibonacci Period Range Indicator is a powerful trading tool that draws levels of support and resistance that are based on key Fibonacci levels. The script will identify the high and low of a range that is specified by the user, then draw several levels of support and resistance based on Fibonacci levels.
The script will also draw extension levels outside of the specified range that are also based on Fibonacci levels. These extension levels can be turned off in the indicator settings.
Each level is also labelled to help traders understand what each line represents. These labels can be turned off in the indicator settings. 
The purpose of this script is to simplify the trading experience of users by giving them the ability to customize the time period that is identified, then draw levels of support and resistance that are based on the price action during this time.
█ USAGE
In the indicator settings, the user has access to a setting called Session Range. This gives users control over the range that will be used.
The script will then identify the high and low of the range that was specified and draw several levels of support and resistance based on Fibonacci levels between this range. The user can also choose to have extension levels that display more levels outside of the range.
These lines will extend until the end of the current trading day at 5:00 pm EST.
█ SETTINGS
Configuration
• Display Mode: Determines the number of days that will be displayed by the script.
• Show Labels: Determines whether or not identifying labels will be displayed on each line.
• Font Size: Determines the text size of labels.
• Label Position: Determines the justification of labels.
• Extension Levels: Determines whether or not extension levels will be drawn outside of the high and low of the specified range.
Session
• Session Range: Determines the time period that will be used for calculations.
• Timezone Offset (+/-): Determines how many hours the session should be offset by.
Speedometer RevisitedSpeedometer Revisited is a new way to draw custom metric speedometers and is intended to be a utility for other coders to use.
@rumpypumpydumpy originally introduced the Speedometer Toolkit in version 4 of Pine Script. Since then, Pine Script has been updated to version 5, introducing some amazing new features such as polylines and chart.points. This indicator is an example of what can be done with these newer features.
The indicator starts off with a handful of functions that will be used to create the drawings. Notes are left throughout the code explaining what each line of the functions does. My goal was to make these functions user-friendly and somewhat easy to understand. I then demonstrate two examples: one speedometer with five segments and another with three.
The  first example  demonstrates how to visually represent the analysts' ratings for a stock using the built-in syminfo.recommendations. The speedometer is divided into five segments, each representing a different level of analyst recommendation: strong sell, sell, hold, buy, and strong buy.
Each segment is drawn using a polyline from the createSeg function, with colors assigned as follows: 
 
 Red for 'Strong Sell' 
 Maroon for 'Sell'
 Yellow for 'Hold'
 Green for 'Buy'
 Lime for 'Strong Buy'
 
The script identifies the maximum value among the analyst ratings, calculates the midpoint of the corresponding segment, and draws a needle pointing to this midpoint.
The  second example  employs the speedometer design to display market sentiment through the put-call ratio. The put-call ratio is a gauge of investor sentiment, where values above 1 indicate a bearish sentiment (more puts being bought relative to calls), and values below 1 suggest a bullish outlook (more calls being bought relative to puts).
The speedometer is divided into three segments, reflecting different ranges of the put-call ratio: 
 
 Red for a ratio greater than 1 (bearish sentiment) 
 Yellow for a ratio between 0.8 and 1 (neutral to bearish sentiment) 
 Lime for a ratio less than 0.8 (bullish sentiment)
 
Depending on the value of the put-call ratio, the script calculates which segment the current value falls into and determines the appropriate segment number. The script calculates the midpoint of the selected segment and draws a needle pointing to this value.
Both examples show how the speedometer can be used as a visual indicator of certain market conditions, helping traders quickly recognize trends and adjust their strategies accordingly.
A big thanks to @rumpypumpydumpy for his original Speedometer Toolbox. I hope this take on it can be useful for other coders. 
NVT Z-ScoreNVT Z-Score Script:
Data Source and Calculation: This script calculates the NVT ratio by dividing the market cap (assumed from QUANDL data) by a 90-day MA of the transaction volume (also from QUANDL), similar to the NVTS calculation. However, the adaptation lies in further analyzing the NVT ratio through a Z-score approach, not explicitly described in the original NVTS methodology.
Z-Score Analysis: The script calculates the mean and standard deviation of the NVT ratio over a user-defined period (daysForMean, defaulting to 180 days) and then computes the Z-score of the current NVT ratio relative to this historical data. This Z-score analysis introduces a standardized way of understanding the NVT ratio's deviation from its historical average, offering a nuanced view of market valuation states.
Visualization and Dynamic Zones: The visualization emphasizes Z-score-based dynamic zones (green, yellow, and red), determined by the stdDevMultiplier. These zones are plotted and filled on the chart, providing visual cues for interpreting the NVT ratio's current state in relation to its historical norm. This aspect significantly differs from the traditional NVTS approach by directly incorporating the concept of standard deviation and Z-scores into the analysis.
TrendLine Toolkit w/ Breaks (Real-Time)The TrendLine Toolkit script introduces an innovating capability by extending the conventional use of trendlines beyond price action to include oscillators and other technical indicators. This tool allows traders to automatically detect and display trendlines on any TradingView built-in oscillator or community-built script, offering a versatile approach to trend analysis. With breakout detection and real-time alerts, this script enhances the way traders interpret trends in various indicators.
🔲  Methodology 
Trendlines are a fundamental tool in technical analysis used to identify and visualize the direction and strength of a price trend. They are drawn by connecting two or more significant points on a price chart, typically the highs or lows of consecutive price movements (pivots).
 Drawing Trendlines: 
 
 Uptrend Line -  Connects a series of higher lows. It signals an upward price trend.
 Downtrend Line -  Connects a series of lower highs. It indicates a downward price trend.
 
 Support and Resistance: 
 
 Support Line -  A trendline drawn under rising prices, indicating a level where buying interest is historically strong.
 Resistance Line -  A trendline drawn above falling prices, showing a level where selling interest historically prevails.
 
 Identification of Trends: 
 
 Uptrend -  Prices making higher highs and higher lows.
 Downtrend -  Prices making lower highs and lower lows.
 Sideways (or Range-bound) -  Prices moving within a horizontal range.
 
A trendline helps confirm the existence and direction of a trend, providing guidance in aligning with the prevailing market sentiment. Additionally, they are usually paired with breakout analysis, a breakout occurs when the price breaches a trendline. This signals a potential change in trend direction or an acceleration of the existing trend.
The script adapts this methodology to oscillators and other indicators. Instead of relying on price pivots, which can only be detected in retrospect, the script utilizes a trailing stop on the oscillator to identify potential swings in real-time, you may find more info about it  here (SuperTrend toolkit) . We detect swings or pivots simply by testing for crosses between the indicator and its trailing stop.
 
type oscillator
    float o = Oscillator    Value
    float s = Trailing Stop Value
oscillator osc = oscillator.new()
bool l = ta.crossunder(osc.o, osc.s) => Utilized as a formed high
bool h = ta.crossover (osc.o, osc.s) => Utilized as a formed low
 
This approach enables the algorithm to detect trendlines between consecutive pivot highs or lows on the oscillator itself, providing a dynamic and immediate representation of trend dynamics.
🔲  Breakout Detection 
The script goes beyond trendline creation by incorporating breakout detection directly within the oscillator. After identifying a trendline, the algorithm continuously monitors the oscillator for potential breakouts, signaling shifts in market sentiment.
  
🔲  Setup Guide  
A simple example on one of my public scripts,  Z-Score Heikin-Ashi Transformed 
  
  
  
🔲  Settings  
 
 Source -  Choose an oscillator source of which to base the Toolkit on.
 Zeroing -  The Mid-Line value of the oscillator, for example RSI & MFI use 50.
 Sensitivity -  Calibrates the Sensitivity of which TrendLines are detected, higher values result in more detections.
 
🔲  Alerts  
 
 Bearish TrendLine 
 Bullish TrendLine 
 Bearish Breakout 
 Bullish Breakout 
As well as the option to trigger 'any alert' call.
 
By integrating trendline analysis into oscillators, this Toolkit enhances the capabilities of technical analysis, bringing a dynamic and comprehensive approach to identifying trends, support/resistance levels, and breakout signals across various indicators.
Fusion Traders - RSI Overbought/Oversold + Divergence IndicatorFusion Traders - RSI Overbought/Oversold + Divergence Indicator - new version
This indicator has lots of various add ons.
RSI overbought / oversold with changeable inputs
Divergence indicator
DESCRIPTION:
This script combines the Relative Strength Index ( RSI ), Moving Average and Divergence indicator to make a better decision when to enter or exit a trade.
- The Moving Average line (MA) has been made hidden by default but enhanced with an RSIMA cloud.
- When the RSI is above the selected MA it turns into green and when the RSI is below the select MA it turns into red.
- When the RSI is moving into the Overbought or Oversold area, some highlighted areas will appear.
- When some divergences or hidden divergences are detected an extra indication will be highlighted.
- When the divergence appear in the Overbought or Oversold area the more weight it give to make a decision.
- The same colour pallet has been used as the default candlestick colours so it looks familiar.
HOW TO USE:
The prerequisite is that we have some knowledge about the Elliot Wave Theory, the Fibonacci Retracement and the Fibonacci Extension tools.
We are hoping you like this indicator and added to your favourite indicators. If you have any question then comment below, and I'll do my best to help.
FEATURES:
• You can show/hide the RSI .
• You can show/hide the MA.
• You can show/hide the lRSIMA cloud.
• You can show/hide the Stoch RSI cloud.
• You can show/hide and adjust the Overbought and Oversold zones.
• You can show/hide and adjust the Overbought Extended and Oversold Extended zones.
• You can show/hide the Overbought and Oversold highlighted zones.
HOW TO GET ACCESS TO THE SCRIPT:
• Favorite the script and add it to your chart.
Squeeze & Release [AlgoAlpha]Introduction: 
💡The Squeeze & Release by AlgoAlpha is an innovative tool designed to capture price volatility dynamics using a combination of EMA-based calculations and ATR principles. This script aims to provide traders with clear visual cues to spot potential market squeezes and release scenarios. Hence it is important to note that this indicator shows information on volatility, not direction.
 Core Logic and Components: 
🔶EMA Calculations: The script utilizes the Exponential Moving Average (EMA) in multiple ways to smooth out the data and provide indicator direction. There are specific lengths for the EMAs that users can modify as per their preference.
🔶ATR Dynamics: Average True Range (ATR) is a core component of the script. The differential between the smoothed ATR and its EMA is used to plot the main line. This differential, when represented as a percentage of the high-low range, provides insights into volatility.
🔶Squeeze and Release Detection: The script identifies and highlights squeeze and release scenarios based on the crossover and cross-under events between our main line and its smoothed version. Squeezes are potential setups where the market may be consolidating, and releases indicate a potential breakout or breakdown.
🔶Hyper Squeeze Detection: A unique feature that detects instances when the main line is rising consistently over a user-defined period. Hyper squeeze marks areas of extremely low volatility.
  
 Visual Components: 
The main line (ATR-based) changes color depending on its position relative to its EMA.
A middle line plotted at zero level which provides a quick visual cue about the main line's position. If the main line is above the zero level, it indicates that the price is squeezing on a longer time horizon, even if the indicator indicates a shorter-term release.
"𝓢" and "𝓡" characters are plotted to represent 'Squeeze' and 'Release' scenarios respectively.
  
Standard Deviation Bands are plotted to help users gauge the extremity and significance of the signal from the indicator, if the indicator is closer to either the upper or lower deviation bands, this means that statistically, the current value is considered to be more extreme and as it is further away from the mean where the indicator is oscillating at for the majority of the time. Thus indicating that the price has experienced an unusual amount or squeeze or release depending on the value of the indicator.
  
 Usage Guidelines: 
☝️Traders can use the script to:
 
 Identify potential consolidation (squeeze) zones.
 Gauge potential breakout or breakdown scenarios (release).
 Fine-tune their entries and exits based on volatility.
 Adjust the various lengths provided in the input for better customization based on individual trading styles and the asset being traded.
41-80 F&O MA ScreenerThis Pine Script is a TradingView indicator named "41-80-F&O EMA Screener." It calculates and displays four moving averages (MA1, MA2, MA3, and MA4) and the Relative Strength Index (RSI) on a chart. The script generates buy and short signals based on certain conditions involving the moving averages and RSI. Additionally, it includes a screener section that displays a table of symbols with buy and short signals.
Here's a breakdown of the key components:
Moving Averages (MAs):
MA1: Simple Moving Average with length len1 (green line).
MA2: Simple Moving Average with length len2 (red line).
MA3: Simple Moving Average with length len3 (orange line).
MA4: Simple Moving Average with length len4 (black line).
Relative Strength Index (RSI):
The RSI is calculated with a length of rsiLengthInput and a source specified by rsiSourceInput.
Conditions for Buy and Short Signals:
Buy Signal: When MA1 is above MA2 and MA3, and RSI is above 50.
Short Signal: When MA1 is below MA2 and MA3, and RSI is below 50.
Signal Plots:
Buy signals are plotted as "B" below the corresponding bars.
Short signals are plotted as "S" above the corresponding bars.
Background Coloring:
Bars are colored based on their opening and closing prices.
Screener Section:
The script defines a watchlist (gticker) with 40 predefined symbols.
It then calls the getSignal function for each symbol to identify buy and short signals.
The results are displayed in a table with long signals in green and short signals in red.
Table Theming:
The script allows customization of the table's background, frame, and text colors, as well as the text size.
The table's location on the chart can also be customized.
Please note that the script uses the Mozilla Public License 2.0. Make sure to review and comply with the terms of this license if you plan to use or modify the script.
Candle size in pipsDescription 
Enhance your trading strategy with precision using this script, designed to measure the range of a candle from wick to wick in pips. Whether you're implementing a specific pip requirement within a candle for your strategy, or simply seeking to better understand market dynamics, this tool provides valuable insights. The script is calculating the amount of pips between the high and the low then compares it to the minimal size you declared. If the amount of pips is more or equal to minimal size it will show the label.
 Features 
Alert Functionality: Opt to receive alerts by checking the checkbox (default: false).
Customizable Pip Threshold: Tailor the script to your needs by setting the minimum required pips to display on the screen (default: 12).
Different shape: circle, triangle up, triangle down, none
 How to Use 
Personalize your trading approach by integrating this script with your preferred strategy. For instance, in my strategy involving a 3M continuation, I leverage this tool to determine the pip count of the M15 candle before making entry decisions.
 Note: Ensure you understand your strategy's requirements and adjust the script settings accordingly for optimal result s.
Feel free to reach out if you have any questions or require further assistance in maximizing the utility of this script.
COT MCIThe COT MCI script is a market indicator based on the data from the Commitment of Traders Reports.
Integration of COT Report Data:
The script sources COT data from futures contracts, including:
Treasury Bonds (ZB), Dollar Index (DX), 10-Year Treasury Notes (ZN)
Commodities like Soybeans (ZS), Soy Meal (ZM), Soy Oil (ZL), Corn (ZC), Wheat (ZW), Kansas City Wheat (KE), Pork (HE), Cattle (LE)
Precious Metals such as Gold (GC), Silver (SI), Palladium (PA), Platinum (PL)
Industrial Metals like Copper (HG), Aluminum (AUP), Steel (HRC)
Energy Products like Crude Oil (CL), Heating Oil (HO), Gasoline (RB), Natural Gas (NG), Brent Crude (BB)
Currencies such as AUD (6A), GBP (6B), CAD (6C), EUR (6E), JPY (6J), CHF (6S), NZD (6N), BRL (6L), MXN (6M), RUB (6R), ZAR (6Z)
Others: Sugar (SB), Coffee (KC), Cocoa (CC), Cotton (CT), Ethanol (EH), Rice (ZR), Oats (ZO), Whey (DC), Orange Juice (OJ), Lumber (LBS), Livestock (GF), E-mini S&P 500 (ES), E-mini Russell 2000 (RTY), E-mini Dow Jones (YM), E-mini NASDAQ-100 (NQ), VIX Futures (VX), S&P 500 (SP), DJIA (DJIA)
Cryptocurrencies such as Bitcoin (BTC) and Ethereum (ETH)
Functions and Logic of the Script:
COT Calculation: Determines the net positions for commercial actors and large speculators. Also Available are short and long positions of commercials or large speculators.
Position Change Analysis: Analyzes the percentage changes in net positions and open interest data over a period of 6 weeks (Weekly Chart).
Average Value Calculation: Determines short-term and long-term trend averages.
Trend Analysis: Buy and sell signals (represented in colors) are based on linear regressions and average calculations.
Usage and Application Examples:
Ideal for traders looking for a detailed analysis of market dynamics and position changes in the futures market. Suitable for decision-making in transaction timing and assessing market sentiment.
Usage Notes:
Users should be familiar with the interpretation of COT data and basic concepts of futures trading. Particularly suitable for medium to long-term trading strategies.
Intersection Value FunctionsWinning entry for the first Pinefest contest. The challenge required providing three functions returning the intersection value between two series  source1  and  source2  in the event of a cross, crossunder, and crossover.
Feel free to use the code however you like.
🔶  CHALLENGE FUNCTIONS 
🔹 crossValue() 
 
//@function Finds intersection value of 2 lines/values if any cross occurs - First function of challenge -> crossValue(source1, source2)
//@param    source1 (float) source value 1 
//@param    source2 (float) source value 2
//@returns  Intersection value
 
example:
 
value = crossValue(close, close )
 
🔹 crossoverValue() 
 
//@function Finds intersection value of 2 lines/values if crossover occurs - Second function of challenge -> crossoverValue(source1, source2) 
//@param    source1 (float) source value 1 
//@param    source2 (float) source value 2
//@returns  Intersection value
 
example:
 
value = crossoverValue(close, close )
 
🔹 crossunderValue() 
 
//@function Finds intersect of 2 lines/values if crossunder occurs - Third function of challenge -> crossunderValue(source1, source2) 
//@param    source1 (float) source value 1 
//@param    source2 (float) source value 2
//@returns  Intersection value
 
example:
 
value = crossunderValue(close, close )
 
🔶  DETAILS 
A series of values can be displayed as a series of points, where the point location highlights its value, however, it is more common to connect each point with a line to have a continuous aspect.
  
A line is a geometrical object connecting two points, each having  y  and  x  coordinates. A line has a slope controlling its steepness and an intercept indicating where the line crosses an axis. With these elements, we can describe a line as follows:
 
slope × x + intercept
 
  
A cross between two series of values occurs when one series is greater or lower than the other while its previous value isn't.
  
We are interested in finding the "intersection value", that is the value where two crossing lines are equal. This problem can be approached via linear interpolation.
A simple and direct approach to finding our intersection value is to find the common scaling factor of the slopes of the lines, that is the multiplicative factor that multiplies both lines slopes such that the resulting points are equal. 
Given:
 
A = Point A1 + m1 × scaling_factor
B = Point B1 + m2 × scaling_factor
 
where  scaling_factor  is the common scaling factor, and  m1  and  m2  the slopes:
 
m1 = Point A2 - Point A1
m2 = Point B2 - Point B1
 
In our cases, since the horizontal distance between two points is simply 1, our lines slopes are equal to their vertical distance (rise).
Under the event of a cross, there exists a  scaling_factor  satisfying  A = B , which allows us to directly compute our intersection value. The solution is given by:
 
scaling_factor = (B1 - A1)/(m1 - m2)
 
As such our intersection value can be given by the following equivalent calculations:
 
(1) A1 + m1 × (B1 - A1)/(m1 - m2)
(2) B1 + m2 × (B1 - A1)/(m1 - m2)
(3) A2 - m2 × (A2 - B2)/(m1 - m2)
(4) B2 - m2 × (A2 - B2)/(m1 - m2)
 
The proposed functions use the third calculation.
  
This approach is equivalent to expressions using the classical line equation, with:
 
slope1 × x + intercept1 = slope2 × x + intercept2
 
By solving for  x , the intersection point is obtained by evaluating any of the line equations for the obtained  x  solution.
🔶  APPLICATIONS 
The intersection point of two crossing lines might lead to interesting applications and creations, in this section various information/tools derived from the proposed calculations are presented.
This supplementary material is available within the script.
🔹 Intersections As Support/Resistances 
  
The script allows extending the lines of the intersection value when a cross is detected, these extended lines could have applications as support/resistance lines.
🔹 Using The Scaling Factor 
The core of the proposed calculation method is the common scaling factor, which can be used to return useful information, such as the position of the cross relative to the  x  coordinates of a line.
  
The above image highlights two moving averages (in green and red), the cross-interval areas are highlighted in blue, and the intersection point is highlighted as a blue line.
The pane below shows a bar plot displaying:
 1 - scaling factor = 1 -  
Values closer to 1 indicate that the cross location is closer to  x2  (the right coordinate of the lines), while values closer to 0 indicate that the cross location is closer to  x1 .
🔹 Intersection Matrix 
The main proposed functions of this challenge focus on the crossings between two series of values, however, we might be interested in applying this over a collection of series.
  
We can see in the image above how the lines connecting two points intersect with each other, we can construct a  matrix  populated with the intersection value of two corresponding lines. If  (X, Y)  represents the intersection value between lines  X  and  Y  we have the following matrix:
 
       | Line A | Line B | Line C | Line D |
-------|--------|--------|--------|--------|
Line A |        | (A, B) | (A, C) | (A, D) |
Line B | (B, A) |        | (B, C) | (B, D) |
Line C | (C, A) | (C, B) |        | (C, D) |
Line D | (D, A) | (D, B) | (D, C) |        |
 
We can see that the upper triangular part of this matrix is redundant, which is why the script does not compute it. This function is provided in the script as  intersectionMatrix :
 
//@function Return the N * N intersection matrix from an array of values
//@param    array_series (array) array of values, requires an array supporting historical referencing
//@returns  (matrix) Intersection matrix showing intersection values between all array entries
 
In the script, we create an intersection matrix from an array containing the outputs of simple moving averages with a period in a specific user set range and can highlight if a simple moving average of a certain period crosses with another moving average with a different period, as well as the intersection value.
  
🔹 Magnification Glass 
Crosses on a chart can be quite small and might require zooming in significantly to see a detailed picture of them. Using the obtained scaling factor allows reconstructing crossing events with an higher resolution.
  
A simple supplementary  zoomIn  function is provided to this effect:
 
//@function Display an higher resolution representation of intersecting lines
//@param    source1      (float) source value 1
//@param    source2      (float) source value 2
//@param    css1         (color) color of source 1 line
//@param    css2         (color) color of source 2 line
//@param    intersec_css (color) color of intersection line
//@param    area_css     (color) color of box area
 
Users can obtain a higher resolution by modifying the provided "Resolution" setting.
The function returns a higher resolution representation of the most recent crosses between two input series, the intersection value is also provided.
New York Sessions Morning, Lunch and afternoon. AMKDescription
The script is designed to highlight the New York Stock Exchange's trading day, broken down into three specific sub-sessions: morning, lunchtime, and afternoon. Each sub-session is color-coded to provide an immediate visual cue about which portion of the trading day is currently active. Additionally, this script allows the user to adjust the time zone offset, making it adaptable for traders in different time zones around the world.
Originality
While there are scripts that highlight the entire trading day or specific market hours, this script adds granularity by breaking down the New York trading session into its typical behavioral parts: the morning rush, the lunchtime lull, and the afternoon action. The addition of an adjustable time zone offset is a unique feature that makes the tool more versatile and accommodating to a global user base.
Usefulness
The ability to visualize these different trading sessions can be valuable for various types of traders:
Day Traders: The script helps to immediately identify which session they are in, aiding in their trading strategy as market behavior can vary between these periods.
Swing Traders: They may use these sub-sessions to time their entries or exits, especially if they're based in different time zones.
Market Analysts: The color-coded sessions provide a quick way to analyze the historical performance and volatility of an asset during different trading periods.
Global Traders: The time zone adjustment feature makes it easy for traders outside of the Eastern Time Zone to customize the script according to their local time, increasing its utility across different markets.
Educational Purpose: For new traders, this could serve as an educational tool to understand the typical behavior of the stock market at different times of the day.
So, whether you're timing an intraday entry or looking for patterns tied to specific market sessions, this script offers a straightforward, visual way to keep track of where you are in the trading day.
Liquidation Estimates (Real-Time) [LuxAlgo]The  Liquidation Estimates (Real-Time)  experimental indicator attempts to highlight real-time long and short liquidations on all timeframes. Here with liquidations, we refer to the process of forcibly closing a trader's position in the market.
By analyzing liquidation data, traders can gauge market sentiment, identify potential support and resistance levels, identify potential trend reversals, and make informed decisions about entry and exit points.
 🔶 USAGE 
  
Liquidation refers to the process of forcibly closing a trader's position. It occurs when a trader's margin account can no longer support their open positions due to significant losses or a lack of sufficient margin to meet the maintenance requirements.
  
Liquidations can be categorized as either a long liquidation or a short liquidation. A long liquidation is a situation where long positions are being liquidated, while short liquidation is a situation where short positions are being liquidated.
The green bars indicate long liquidations – meaning the number of long positions liquidated in the market. Typically, long liquidations occur when there is a sudden drop in the asset price that is being traded. This is because traders who were bullish on the asset and had opened long positions on the same will now face losses since the market has moved against them.
Similarly, the red bars indicate short liquidations – meaning the number of short positions liquidated in the futures market. Short liquidations occur when there is a sudden spike in the price of the asset that is being traded. This is because traders who were bearish on the asset and had opened short positions will now face losses since the market has moved against them.
  
Liquidation patterns or clusters of liquidations could indicate potential trend reversals.
🔹 Dominance 
Liquidation dominance (Difference) displays the difference between long and short liquidations, aiming to help identify the dominant side.
  
🔹 Total Liquidations 
Total liquidations display the sum of long and short liquidations.
  
🔹 Cumulative Liquidations 
Cumulative liquidations are essentially the cumulative sum of the difference between short and long liquidations aiming to confirm the trend and the strength of the trend. 
  
 🔶 DETAILS 
It's important to note that liquidation data is not provided on the Trading View's platform or can not be fetched from anywhere else. 
Yet we know that the liquidation data is closely tied in with trading volumes in the market and the movement in the underlying asset’s price. As a result, this script analyzes available data sources extracts the required information, and presents an educated estimate of the liquidation data. 
The data presented does not reflect the actual individual quantitative value of the liquidation data, traders and analysts shall look to the changes over time and the correlation between liquidation data and price movements.
The script's output with the default option values has been visually checked/compared with the liquidation chart presented on coinglass.com. 
 🔶 SETTINGS 
 🔹Liquidations Input 
 
 Mode: defines the presentation of the liquidations chart. Details are given in the tooltip of the option.  
 Longs Reference Price: defines the base price in calculating long liquidations.   
 Shorts Reference Price: defines the base price in calculating short liquidations.
 
 🔶 RELATED SCRIPTS 
 Liquidation-Levels 
 Liquidity-Sentiment-Profile 
 Buyside-Sellside-Liquidity















