Daily Single Trade [SMRT Algo]The Daily Single Trade Indicator by SMRT Algo is a powerful yet simple tool designed for traders who value precision, discipline, and a focus on high-quality trade setups. With a unique approach, this indicator identifies just one signal daily, making it ideal for traders who prefer a structured and stress-free trading routine.
Please note that this indicator only works for timeframes below 1H.
 Key Features: 
 
  Market Open & Pre-Market Analysis: The indicator focuses on the market’s opening range and identifies breakout opportunities based on price action during these critical periods.
  Customizable Risk-Reward Ratio: Plan your trades with precision by setting your desired RR, ensuring that your take-profit (TP) levels are multiples of your stop-loss (SL). Stop loss is not shown with this indicator.
  Price Offset for SL: Add a customizable buffer to your SL and TP levels. This offset accounts for market volatility, reducing the chances of premature stop-outs while maintaining alignment with your trading plan. 
Increasing this value will lead to a greater invisible stop loss, which will increase the TP size. The opposite is occurs when decreasing this value (less than 0). If you set it as 2.5 for example for TSLA: price is 340 and SL is 330 for example, SL becomes 327.5. This calculation will then be applied to calculate the TP.
In simple terms, if the offset is positive, SL becomes larger, TP becomes larger as well.
  Exit Point Visibility: Display exit points on your chart to better visualize trade targets and stop levels.
  Adjustable Market Open Time: Easily modify the market open hour and minute to suit your asset’s trading session. For example, U.S. stock traders can set the market open time to 9:30 AM EST (UTC-5).
 
  
  
By providing a single signal each day, the indicator minimizes overtrading and keeps your focus on the best opportunities.
With predefined SL, TP, and RR settings, the indicator fosters disciplined trading, reducing the influence of emotional decision-making. Whether you’re trading stocks, indices, or forex, the customizable market open time and RR ratio make this indicator versatile and adaptable.
The combination of precise SL and TP calculations with offset pip adjustments helps protect your trades from market noise while maintaining a favorable RR.
Perfect for those who can’t monitor markets all day, the single-signal approach allows you to execute a high-quality trade and move on with your day.
 How to Use: 
 
  Set the Market Open Time: Adjust the open time to align with your asset’s session. For example, set 9:30 AM EST for U.S. stocks.
  Define Your Risk-Reward Ratio: Choose an RR multiple (e.g., 1:2 or 1:3) that aligns with your risk tolerance and trading goals.
  Apply Pip Offset: Add a buffer to your SL and TP to account for market volatility and reduce false stops.
 
The Daily Single Trade Indicator simplifies trading by focusing on one high-probability setup per day. It’s perfect for traders looking to maintain consistency, improve risk management, and reduce the stress of overanalyzing the markets.
 How Alerts Work: 
 
  Individual Alerts: Set separate notifications for specific actions, such as breakout signals, take-profit levels, or stop-loss activations.
  Master Alert: Manage all notifications with one streamlined setting, ensuring you never miss an opportunity while keeping your setup simple and efficient.
 
Take control of your trading with a strategy built for clarity, precision, and success!
Cari dalam skrip untuk "one一季度财报"
Top-Down Trend and Key Levels with Swing Points//by antaryaami0
 Overview 
The “Top-Down Trend and Key Levels with Swing Points” indicator is a comprehensive tool designed to enhance your technical analysis by integrating multiple trading concepts into a single, easy-to-use script. It combines higher timeframe trend analysis, key price levels, swing point detection, and ranging market identification to provide a holistic view of market conditions. This indicator is particularly useful for traders who employ multi-timeframe analysis, support and resistance levels, and price action strategies.
 Key Features
 
	1.	Higher Timeframe Trend Background Shading:
	•	Purpose: Identifies the prevailing trend on a higher timeframe to align lower timeframe trading decisions with the broader market direction.
	•	How it Works: The indicator compares the current higher timeframe close with the previous one to determine if the trend is up, down, or ranging.
	•	Customization:
	•	Trend Timeframe: Set your preferred higher timeframe (e.g., Daily, Weekly).
	•	Up Trend Color & Down Trend Color: Customize the background colors for uptrends and downtrends.
	•	Ranging Market Color: A separate color to indicate when the market is moving sideways.
	2.	Key Price Levels:
	•	Previous Day High (PDH) and Low (PDL):
	•	Purpose: Identifies key support and resistance levels from the previous trading day.
	•	Visualization: Plots horizontal lines at PDH and PDL with labels.
	•	Customization: Option to show or hide these levels and customize their colors.
	•	Pre-Market High (PMH) and Low (PML):
	•	Purpose: Highlights the price range during the pre-market session, which can indicate potential breakout levels.
	•	Visualization: Plots horizontal lines at PMH and PML with labels.
	•	Customization: Option to show or hide these levels and customize their colors.
	3.	First 5-Minute Marker (F5H/F5L):
	•	Purpose: Marks the high or low of the first 5 minutes after the market opens, which is significant for intraday momentum.
	•	How it Works:
	•	If the first 5-minute high is above the Pre-Market High (PMH), an “F5H” label is placed at the first 5-minute high.
	•	If the first 5-minute high is below the PMH, an “F5L” label is placed at the first 5-minute low.
	•	Visualization: Labels are placed at the 9:35 AM candle (closing of the first 5 minutes), colored in purple by default.
	•	Customization: Option to show or hide the marker and adjust the marker color.
	4.	Swing Points Detection:
	•	Purpose: Identifies significant pivot points in price action to help recognize trends and reversals.
	•	How it Works: Uses left and right bars to detect pivot highs and lows, then determines if they are Higher Highs (HH), Lower Highs (LH), Higher Lows (HL), or Lower Lows (LL).
	•	Visualization: Plots small markers (circles) with labels (HH, LH, HL, LL) at the corresponding swing points.
	•	Customization: Adjust the number of left and right bars for pivot detection and the size of the markers.
	5.	Ranging Market Detection:
	•	Purpose: Identifies periods when the market is consolidating (moving sideways) within a defined price range.
	•	How it Works: Calculates the highest high and lowest low over a specified period and determines if the price range is within a set percentage threshold.
	•	Visualization: Draws a gray box around the price action during the ranging period and labels the high and low prices at the end of the range.
	•	Customization: Adjust the range detection period and threshold, as well as the box color.
	6.	Trend Coloring on Chart:
	•	Purpose: Provides a visual cue for the short-term trend based on a moving average.
	•	How it Works: Colors the candles green if the price is above the moving average and red if below.
	•	Customization: Set the moving average length and customize the uptrend and downtrend colors.
 How to Use the Indicator
 
	1.	Adding the Indicator to Your Chart:
	•	Copy the Pine Script code provided and paste it into the Pine Script Editor on TradingView.
	•	Click “Add to Chart” to apply the indicator.
	2.	Configuring Inputs and Settings:
	•	Access Inputs:
	•	Click on the gear icon next to the indicator’s name on your chart to open the settings.
	•	Customize Key Levels:
	•	Show Pre-Market High/Low: Toggle on/off.
	•	Show Previous Day High/Low: Toggle on/off.
	•	Show First 5-Minute Marker: Toggle on/off.
	•	Set Trend Parameters:
	•	Trend Timeframe for Background: Choose the higher timeframe for trend analysis.
	•	Moving Average Length for Bar Color: Set the period for the moving average used in bar coloring.
	•	Adjust Ranging Market Detection:
	•	Range Detection Period: Specify the number of bars to consider for range detection.
	•	Range Threshold (%): Set the maximum percentage range for the market to be considered ranging.
	•	Customize Visuals:
	•	Colors: Adjust colors for trends, levels, markers, and ranging market boxes.
	•	Label Font Size: Choose the size of labels displayed on the chart.
	•	Level Line Width: Set the thickness of the lines for key levels.
	3.	Interpreting the Indicator:
	•	Background Shading:
	•	Green Shade: Higher timeframe is in an uptrend.
	•	Red Shade: Higher timeframe is in a downtrend.
	•	Gray Box: Market is ranging (sideways movement).
	•	Key Levels and Markers:
	•	PDH and PDL Lines: Represent resistance and support from the previous day.
	•	PMH and PML Lines: Indicate potential breakout levels based on pre-market activity.
	•	F5H/F5L Labels: Early indication of intraday momentum after market open.
	•	Swing Point Markers:
	•	HH (Higher High): Suggests bullish momentum.
	•	LH (Lower High): May indicate a potential bearish reversal.
	•	HL (Higher Low): Supports bullish continuation.
	•	LL (Lower Low): Indicates bearish momentum.
	•	Ranging Market Box:
	•	Gray Box Around Price Action: Highlights consolidation periods where breakouts may occur.
	•	Range High and Low Labels: Provide the upper and lower bounds of the consolidation zone.
	4.	Applying the Indicator to Your Trading Strategy:
	•	Trend Alignment:
	•	Use the higher timeframe trend shading to align your trades with the broader market direction.
	•	Key Levels Trading:
	•	Watch for price reactions at PDH, PDL, PMH, and PML for potential entry and exit points.
	•	Swing Points Analysis:
	•	Identify trend continuations or reversals by observing the sequence of HH, HL, LH, and LL.
	•	Ranging Market Strategies:
	•	During ranging periods, consider range-bound trading strategies or prepare for breakout trades when the price exits the range.
	•	Intraday Momentum:
	•	Use the F5H/F5L marker to gauge early market sentiment and potential intraday trends.
 Practical Tips
 
	•	Adjust Settings to Your Trading Style:
	•	Tailor the indicator’s inputs to match your preferred timeframes and trading instruments.
	•	Combine with Other Indicators:
	•	Use in conjunction with volume indicators, oscillators, or other technical tools for additional confirmation.
	•	Backtesting:
	•	Apply the indicator to historical data to observe how it performs and refine your settings accordingly.
	•	Stay Updated on Market Conditions:
	•	Be aware of news events or economic releases that may impact market behavior and the effectiveness of technical levels.
 Customization Options
 
	•	Time Zone Adjustment:
	•	The script uses “America/New_York” time zone by default. Adjust the timezone variable in the script if your chart operates in a different time zone.
 var timezone = "Your/Timezone" 
	•	Session Times:
	•	Modify the Regular Trading Session and Pre-Market Session times in the indicator settings to align with the trading hours of different markets or exchanges.
	•	Visual Preferences:
	•	Colors: Personalize the indicator’s colors to suit your visual preferences or to enhance visibility.
	•	Label Sizes: Adjust label sizes if you find them too intrusive or not prominent enough.
	•	Marker Sizes: Further reduce or enlarge the swing point markers by modifying the swing_marker_size variable.
 Understanding the Indicator’s Logic 
	1.	Higher Timeframe Trend Analysis:
	•	The indicator retrieves the closing prices of a higher timeframe using the request.security() function.
	•	It compares the current higher timeframe close with the previous one to determine the trend direction.
	2.	Key Level Calculation:
	•	Previous Day High/Low: Calculated by tracking the highest and lowest prices of the previous trading day.
	•	Pre-Market High/Low: Calculated by monitoring price action during the pre-market session.
	3.	First 5-Minute Marker Logic:
	•	At 9:35 AM (end of the first 5 minutes after market open), the indicator evaluates whether the first 5-minute high is above or below the PMH.
	•	It then places the appropriate label (F5H or F5L) on the chart.
	4.	Swing Points Detection:
	•	The script uses ta.pivothigh() and ta.pivotlow() functions to detect pivot points.
	•	It then determines the type of swing point based on comparisons with previous swings.
	5.	Ranging Market Detection:
	•	The indicator looks back over a specified number of bars to find the highest high and lowest low.
	•	It calculates the percentage difference between these two points.
	•	If the difference is below the set threshold, the market is considered to be ranging, and a box is drawn around the price action.
 Limitations and Considerations 
	•	Indicator Limitations:
	•	Maximum Boxes and Labels: Due to Pine Script limitations, there is a maximum number of boxes and labels that can be displayed simultaneously.
	•	Performance Impact: Adding multiple visual elements (boxes, labels, markers) can affect the performance of the script on lower-end devices or with large amounts of data.
	•	Market Conditions:
	•	False Signals: Like any technical tool, the indicator may produce false signals, especially during volatile or erratic market conditions.
	•	Not a Standalone Solution: This indicator should be used as part of a comprehensive trading strategy, including risk management and other forms of analysis.
 Conclusion 
The “Top-Down Trend and Key Levels with Swing Points” indicator is a versatile tool that integrates essential aspects of technical analysis into one script. By providing insights into higher timeframe trends, highlighting key price levels, detecting swing points, and identifying ranging markets, it equips traders with valuable information to make more informed trading decisions. Whether you are a day trader looking for intraday opportunities or a swing trader aiming to align with the broader trend, this indicator can enhance your chart analysis and trading strategy.
 Disclaimer 
Trading involves significant risk, and it’s important to understand that past performance is not indicative of future results. This indicator is a tool to assist in analysis and should not be solely relied upon for making trading decisions. Always conduct thorough research and consider seeking advice from financial professionals before engaging in trading activities.
Prometheus Markov ChainThe Prometheus Markov Chain Indicator is a custom-built tool designed to predict potential future price movements using a Markov Chain approach. A Markov Chain is a statistical model that assumes the probability of moving to a future state depends solely on the current state. In this indicator, states represent price movement classifications—bullish, bearish, or neutral—and are determined based on historical price changes (percentage returns). The indicator builds a transition matrix to calculate probabilities of transitioning from one state to another, enabling traders to identify patterns and forecast likely price actions.
Core Functionality and Transition Matrix
The transition matrix is the backbone of the Markov Chain. It captures the frequency of transitions between states in the historical price data and normalizes these counts into probabilities. For example, if the price was in a bearish state and transitioned to a bullish state 3 out of 10 times, the probability of transitioning from bearish to bullish would be 0.3. The matrix is created dynamically using the stateFunc function to classify states, which can use either dynamic thresholds (highest and lowest returns over a lookback period) or a user-defined percent return threshold. Below is the snippet that updates the transition matrix:
 transitionMatrix = matrix.new(dimension, dimension, 0.0)
for i = 0 to array.size(vec) - 2
    fromState = array.get(vec, i)
    toState = array.get(vec, i + 1)
    transitionMatrix.set(fromState, toState, transitionMatrix.get(fromState, toState) + 1)
for i = 0 to dimension - 1
    rowSum = 0.0
    for j = 0 to dimension - 1
        rowSum += transitionMatrix.get(i, j)
    for j = 0 to dimension - 1
        prob = transitionMatrix.get(i, j) / rowSum
        transitionMatrix.set(i, j, prob)
 
This snippet iterates through historical price movements, counts state transitions, and then normalizes each row of the matrix so that the sum of probabilities for all possible transitions from a given state equals 1.
How the Indicator Predicts Future States
After constructing the transition matrix, the indicator calculates the current state of the price based on the latest percentage return and then uses the matrix to compute probabilities for transitioning to other states. The state with the highest probability is predicted as the next state, which is displayed on the chart using color-coded labels: green for bullish and red for bearish. The following snippet demonstrates how the current state and predictions are calculated:
 current_chng = (close - close ) / close 
var int current_state = na
if not use_custom_thresh
    highest_chng = ta.highest(current_chng, int(size) * 2)
    lowest_chng = ta.lowest(current_chng, int(size) * 2)
    current_state := stateFunc(current_chng, highest_chng, lowest_chng)
else
    current_state := stateFunc(current_chng, custom_thresh)
predicted_probs = array.new(dimension, 0.0)
for j = 0 to dimension - 1
    array.set(predicted_probs, j, transitionMatrix.get(current_state, j))
 
The indicator evaluates which state has the highest transition probability (highest_prob) and places corresponding labels on the chart. For example, if the next state is predicted to be bullish, a green "Bullish" label is placed below the current bar. This predictive functionality helps traders anticipate potential reversals or continuations in price trends based on historical behavior patterns.
Usage:
  
Here we see the indicator at work on $PLTR. The states predicted are bullish then bearish. In this example we then see price move in a way that verifies those predictions.
  
On this 4 Hour  NASDAQ:AMZN  chart we see predictions play out in a short trade style. States quickly move from one to another but not without giving traders a way to take advantage.
This is the perspective we aim to provide. We encourage traders to not follow indicators blindly. No indicator is 100% accurate. This one can give you a different perspective market state. We encourage any comments about desired updates or criticism!
PSP Indicator [Elbaz]Precision Swing Point or PSP is a unique technical analysis tool designed to compare the price action of three tickers that are in sync.
It highlights moments when the price structure diverges between the markets, identifying ideal entry points for trades - We would like to enter a trade when we found PSP and one of the tickers took the wick while others didn't.
This strategy provides an edge by focusing on periods of desynchronization between the indices, where one index may be showing strength while another is lagging. The idea is to find the moments where the candle colors (bullish or bearish) differ across the markets, then wait for one of the tickers to "take" the wick of the PSP while other didn't and enter a trade.
Once a divergence is detected, the indicator plots an arrow on the chart, signaling a potential trade entry. To minimize risk, a good place to put stop loss will at the end of the wick of the PSP — the high or low wick of the candle where the divergence occurs.
The PSP Indicator allows for several custom inputs:
- Tickers: Customize the tickers to compare. The default values are S&P 500 E-mini, NASDAQ E-mini, and Dow Jones E-mini, if you trade Crypto you might want to use BTC, ETH, TOTAL3.
- Lookback Period: The lookback input defines how far back the indicator should evaluate to calculate the price structure point.
- Highlight Bar Times: Users can specify particular times during the trading day to highlight, such as the market open or significant news events. This helps traders focus on key trading windows.
Adaptive Linear Regression ChannelOverview 
The  Adaptive Linear Regression Channel  Script is an advanced, multi-functional trading tool crafted to help traders pinpoint market trends, identify potential reversals, assess volatility, and establish dynamic levels for profit-taking and position exits. By incorporating key concepts such as  linear regression ,  standard deviation , and other volatility measures like the  ATR , the script offers a comprehensive view of market behavior beyond traditional deviation metrics.
This dynamic model continuously adapts to changing market conditions, adjusting in real-time to provide clear visualizations of trends, channels, and volatility levels. This adaptability makes the script invaluable for both  trend-following  and  counter-trend  strategies, giving traders the flexibility to respond effectively to different market environments.
 Background 
 What is Linear Regression? 
 
 Definition : Linear regression is a statistical technique used to model the relationship between a dependent variable (target) and one or more independent variables (predictors).
 In its simplest form (simple linear regression), the relationship between two variables is represented by a straight line (the regression line).
    y = mx + b
    where :
    - y is the target variable (price)
    - m is the slope
    - x is the independent variable (time)
    - b is the intercept
 
 Slope of the Regression Line 
 
 Definition: The slope (m) measures the rate at which the dependent variable (y) changes as the independent variable (x) changes.
 Interpretation: 
    - A positive slope indicates an uptrend.
    - A negative slope indicates a downtrend.
 Uses in Trading: 
    - Identifying the strength and direction of market trends.
    - Assessing the momentum of price movements.
 
 R-squared (Coefficient of Determination) 
 
 Definition: A measure of how well the regression line fits the data, ranging from 0 to 1.
 Calculation :    
     R2 = 1− (SS tot/SS res)
    where:
    - SSres is the sum of squared residuals.
    - SStot is the total sum of squares.
 Interpretation: 
    - Higher R2 indicates a better fit, meaning the model explains a larger proportion of the variance in the data.
 Uses in Trading: 
    - Higher R-squared values give traders confidence in trend-based signals.
    - Low R-squared values may suggest that the market is more random or volatile.
 
 Standard Deviation 
 
 Definition: Standard Deviation quantifies the dispersion of data points in a dataset relative to the mean. A low standard deviation indicates that data points tend to be close to the mean, while a high standard deviation indicates that the data points are spread out over a larger range of values.
  Calculation
σ=√∑(xi−μ)2/N  
    Where
    - σ is the standard deviation.
    - ∑ is the summation symbol, indicating that the expression that follows should be summed over all data points.
    - xi, this represents the i-th data point in the dataset.
    - μ\mu, this represents the mean(average) of all the data points in the dataset.
    - (xi−μ)2, this is the squared difference between each data point and the mean.
    - N is the total number of data points in the dataset.
 - **Interpretation**
    - A higher standard deviation indicates greater volatility.
    - Useful for identifying overbought/oversold conditions in markets.
 
 Key Features 
 
 Dynamic Linear Regression Channels: 
    
    The script automatically generates adaptive regression channels that expand or contract based on the current market volatility. This real-time adjustment ensures that traders are always working with the most relevant data, making it easier to spot key  support  and  resistance  levels.
    
    The  channel width  itself serves as an indicator of market volatility, expanding during periods of heightened uncertainty and contracting during more stable phases. Additionally, the channel width is  trained on previous channel widths , allowing the script to adapt and provide a more accurate view of volatility trends of the asset. Traders can also customize the script to  train on less historical data , enabling a more  recent view of volatility , which is particularly useful in fast-moving or changing markets.
 Dynamic Profits and Stops: 
    
     What is it? 
    
    Dynamic profit levels allow traders to adjust take-profit targets based on real-time market conditions. Unlike static levels, which remain fixed regardless of market changes, these adaptive levels leverage past volatility data to create more flexible profit-taking strategies.
    
     How does it work? 
    
    The script determines these levels using previously stored deviation values. These deviations are categorized into quantiles (like Q1, Q2, Q3, etc.) to classify current market conditions. As new deviation data is recorded, the profit levels are adjusted dynamically to reflect changes in market volatility. This approach helps to refine profit targets, especially when using regression channels with standard deviation rather than traditional ATR bands.
    
     Why is it valuable? 
    
    By utilizing adaptive profit levels, traders can optimize their exits based on the current volatility landscape. For instance, when volatility increases, the dynamic levels expand, allowing trades to capture larger price movements. Conversely, during low volatility, profit targets tighten to lock in gains sooner, reducing exposure to market reversals. This flexibility is especially beneficial when combined with adaptive regression channels that respond to changes in standard deviation.
  
 Slope-Based Trend Analysis: 
    
    One of the core elements of this script is the  slope of the regression line , which helps define the  direction  and  strength  of the trend. Positive slopes indicate bullish momentum, while negative slopes suggest bearish conditions. The  slope's steepness  gives traders insight into the market's momentum, allowing them to adjust their strategies based on the strength of the trend.
    
    Additionally, the script uses the slope to create a  color gradient , which visually represents the intensity of the market's momentum. The gradient peaks at one color to show the  maximum bullish momentum  experienced in the past, while another color represents the  maximum bearish momentum  experienced in the past. This color-coded visualization makes it easier for traders to quickly assess the market's strength and direction at a glance.
  
 Volatility Heatmap: 
    
    The integrated  heatmap  provides an intuitive, color-coded visualization of market volatility. The heatmap highlights areas where price action is expanding or contracting, giving traders a clear view of where volatility is rising or falling. By mapping out  deviations  from the regression line, the heatmap makes it easier to spot periods of  high volatility  that could lead to major market moves or potential reversals.
  
 Deviation Concepts: 
    
    The script tracks price  deviations  from the regression line when a new range is formed, providing valuable insights when the price significantly deviates from the expected trend. These deviations are key in identifying potential  breakout points  or  trend shifts .
    
    This helps traders understand when the market is overextended or when a pullback may be imminent, allowing them to make more informed trading decisions.
  
 Adaptive Model Properties: 
    
    Unlike static indicators, this script  adapts over time . As the market changes, it stores historical data related to  channel widths ,  slope dynamics , and  volatility levels , adjusting its analysis accordingly to stay relevant to current market conditions.
    
    Traders have the  ability to train the model on all available data  or specify a set number of bars to focus on more recent market activity. This flexibility allows for more  tailored analysis , ensuring that traders can work with data that best fits their trading style and time horizon.
    
    This continuous learning approach ensures that traders always have the most up-to-date insight into the market's structure.
  
 Table 
    
    The table displays key metrics in real time to provide deeper insights into market behavior:
  
    1.  Deviation & Slope : Shows the current deviation if set to standard deviation or atr if set to atr(values used to calculated the channel widths) and the trend slope, helping to gauge market volatility and trend direction.
    2.  Rate of Change : For both deviation/atr and slope, the table also calculates the rate of change of their rates—essentially capturing the acceleration or deceleration of trends and volatility. This helps identify shifts in market momentum early.
    3.  R-squared : Indicates the strength and reliability of the trend fit. A higher value means the regression line better explains the price movements.
    4.  Quantiles : Uses historical deviation data to categorize current market conditions into quartiles (e.g., Q1, Q2, Q3). This helps classify the market's current volatility level, allowing traders to adjust strategies dynamically.
    
    By combining these metrics, the table offers a comprehensive, real-time snapshot of market conditions, enabling more informed and adaptive trading decisions.
 
 Settings 
Here’s a breakdown of the script's settings for easy reference:
 Linear Regression Settings 
 
 Show Dynamic Levels :Toggle to display dynamic profit levels on the chart.
 Deviation Type :Select the method for calculating deviation—options include ATR (Average True Range) or Standard Deviation.
 Timeframe :Sets the specific timeframe for the regression analysis (default is the chart’s timeframe).
 Period :Defines the number of bars used for calculating the regression line (e.g., 50 bars).
 Deviation Multiplier :Multiplier used to adjust the width of the deviation channel around the regression line.
 Rate of Change :Sets the period for calculating the rate of change of the slope (used for momentum analysis).
 Max Bars Back :Limits the number of historical bars to analyze (0 means all available data).
 Slope Lookback :Number of bars used to calculate the slope gradient for trend detection.
 Slope Gradient Display :Toggle to enable gradient coloring based on slope direction.
 Slope Gradient Colors :Set colors for positive and negative slopes, respectively.
 Slope Fill :Adjusts the transparency of the slope gradient fill.
 Volatility Gradient Display :Toggle to enable gradient coloring based on volatility levels.
 Volatility Gradient Colors :Set colors for low and high volatility, respectively.
 Volatility Fill :Adjusts the transparency of the volatility gradient fill.
 
 Table Settings 
 
 Show Table :Toggle to display the metrics table on the chart.
 Table Position :Choose where to position the table (e.g., top-right, middle-center, etc.).
 Font Size :Set the size of the text in the table. Options include Tiny, Small, Normal, Large, and Huge.
 
  
Forex Heatmap█   OVERVIEW 
This indicator creates a dynamic grid display of currency pair cross rates (exchange rates) and percentage changes, emulating the  Cross Rates  and  Heat Map  widgets available on our  Forex  page. It provides a view of realtime exchange rates for all possible pairs derived from a user-specified list of currencies, allowing users to monitor the relative performance of several currencies directly on a TradingView chart. 
█   CONCEPTS 
 Foreign exchange 
The Foreign Exchange (Forex/FX) market is the largest, most liquid financial market globally, with an average daily trading volume of over 5 trillion USD. Open 24 hours a day, five days a week, it operates through a decentralized network of financial hubs in various major cities worldwide. In this market, participants trade currencies in  pairs , where the listed price of a currency pair represents the exchange rate from a given  base currency  to a specific  quote currency . For example, the "EURUSD" pair's price represents the amount of USD (quote currency) that equals  one unit  of EUR (base currency). Globally, the most traded currencies include the U.S. dollar (USD), Euro (EUR), Japanese yen (JPY), British pound (GBP), and Australian dollar (AUD), with USD involved in over 87% of all trades. 
Understanding the Forex market is essential for traders and investors, even those who do not trade currency pairs directly, because exchange rates profoundly affect global markets. For instance, fluctuations in the value of USD can impact the demand for U.S. exports or the earnings of companies that handle multinational transactions, either of which can affect the prices of stocks, indices, and commodities. Additionally, since many factors influence exchange rates, including economic policies and interest rate changes, analyzing the exchange rates across currencies can provide insight into global economic health. 
█   FEATURES  
 Requesting a list of currencies 
This indicator requests data for every valid currency pair  combination  from the list of currencies defined by the "Currency list" input in the "Settings/Inputs" tab. The list can contain up to  six  unique currency codes separated by commas, resulting in a maximum of 30 requested currency pairs. 
For example, if the specified "Currency list" input is "CAD, USD, EUR", the indicator requests and displays relevant data for six currency pair combinations: "CADUSD", "USDCAD", "CADEUR", "EURCAD", "USDEUR", "EURUSD". See the "Grid display" section below to understand how the script organizes the requested information. 
Each item in the comma-separated list must represent a valid currency code. If the "Currency list" input contains an invalid currency code, the corresponding cells for that currency in the "Cross rates" or "Heat map" grid show "NaN" values. If the list contains empty items, e.g., "CAD, ,EUR, ", the indicator  ignores  them in its data requests and calculations. 
NOTE: Some uncommon currency pair combinations might not have data feeds available. If no available symbols provide the exchange rates between two specified currencies, the corresponding table cells show "NaN" results.
 Realtime data 
The indicator retrieves realtime market prices, daily price changes, and minimum tick sizes for all the currency pairs derived from the "Currency list" input. It updates the retrieved information shown in its grid display after new ticks become available to reflect the latest known values. 
NOTE: Pine scripts execute on realtime bars  only  when new ticks are available in the chart's data feed. If no new updates are available from the chart's realtime feed, it may cause a delay in the data the indicator receives.
 Grid display 
This indicator displays the requested data for each currency pair in a table with cells organized as a grid. Each row name corresponds to a pair's  base currency , and each column name corresponds to a  quote currency . The cell at the intersection of a specific row and column shows the value requested from the corresponding currency pair. 
For example, the cell at the intersection of a "EUR" row and "USD" column shows the data retrieved for the "EURUSD" currency pair, and the cell at the "USD" row and "EUR" column shows data for the inverse pair ("USDEUR"). 
Note that the main diagonal cells in the table, where rows and columns with the  same names  intersect, are blank. The exchange rate from one currency to itself is always 1, and no Forex symbols such as "EUREUR" exist.
The dropdown input at the top of the "Settings/Inputs" tab determines the type of information displayed in the table. Two options are available:  "Cross rates"  and  "Heat map" . Both modes color their cells for light and dark themes separately based on the inputs in the "Colors" section. 
 Cross rates 
When a user selects the "Cross rates" display mode, the table's cells show the latest available  exchange rate  for each currency pair, emulating the behavior of the  Cross Rates  widget. Each cell's value represents the amount of the quote currency (column name) that equals one unit of the base currency (row name). This display allows users to compare cross rates across currency pairs, and their inverses. 
The background color of each cell changes based on the most recent update to the exchange rate, allowing users to monitor the direction of short-term fluctuations as they occur. By default, the background turns green (positive cell color) when the cross rate increases from the last recorded update and red (negative cell color) when the rate decreases. The cell's color reverts to the chart's background color after no new updates are available for 200 milliseconds.
 Heat map 
When a user selects the "Heat map" display mode, the table's cells show the latest  daily percentage change  of each currency pair, emulating the behavior of the  Heat Map  widget. 
In this mode, the background color of each cell depends on the corresponding currency pair's daily performance. Heat maps typically use colors that vary in intensity based on the calculated values. This indicator uses the following color coding by default:
 •  Green (Positive cell color):  Percentage change > +0.1%
 •  No color:  Percentage change between 0.0% and +0.1%
 •  Bright red (Negative cell color):  Percentage change < -0.1%
 •  Lighter/darker red (Minor negative cell color):  Percentage change between 0.0% and -0.1%
█   FOR Pine Script™ CODERS 
 • This script utilizes  dynamic requests  to iteratively fetch information from multiple contexts using a single  request.security()  instance in the code. Previously, `request.*()` functions were not allowed within the local scopes of loops or conditional structures, and most `request.*()` function parameters, excluding `expression`, required arguments of a  simple  or weaker qualified type. The new `dynamic_requests` parameter in script declaration statements enables more flexibility in how scripts can use `request.*()` calls. When its value is `true`, all `request.*()` functions can accept  series  arguments for the parameters that define their requested contexts, and `request.*()` functions  can  execute within local scopes. See the  Dynamic requests  section of the Pine Script™ User Manual to learn more. 
 • Scripts can execute up to 40  unique  `request.*()` function calls. A `request.*()` call is unique only if the script does not already call the same function with the same arguments. See  this section  of the User Manual's  Limitations  page for more information. 
 • Typically, when requesting  higher-timeframe data  with  request.security()  using  barmerge.lookahead_on  as the `lookahead` argument, the `expression` argument should use the  history-referencing  operator to offset the series, preventing  lookahead bias  on historical bars. However, the  request.security()  call in this script uses  barmerge.lookahead_on   without  offsetting the `expression` because the script only displays results for the latest historical bar and all realtime bars, where there is no future information to leak into the past. Instead, using this call on those bars ensures each request fetches the  most recent  data available from each context. 
 • The  request.security()  instance in this script includes a `calc_bars_count` argument to specify that each request retrieves only a minimal number of bars from the end of each symbol's historical data feed. The script does not need to request all the historical data for each symbol because it only shows results on the last chart bar that do not depend on the entire time series. In this case, reducing the retrieved bars in each request helps minimize resource usage without impacting the calculated results. 
 Look first. Then leap.  
Market Stats Panel [Daveatt]█ Introduction 
I've created a script that brings TradingView's watchlist stats panel functionality directly to your charts. This isn't just another performance indicator - it's a pixel-perfect (kidding) recreation of TradingView's  native stats panel. 
 Important Notes 
You might need to adjust manually the scaling the firs time you're using this script to display nicely all the elements.
 █ Core Features 
 Performance Metrics 
The panel displays key performance metrics (1W, 1M, 3M, 6M, YTD, 1Y) in real-time, with color-coded boxes (green for positive, red for negative) for instant performance assessment.
 Display Modes 
Switch seamlessly between absolute prices and percentage returns, making it easy to compare assets across different price scales.
 Absolute mode 
  
 Percent mode 
  
 Historical Comparison 
View year-over-year performance with color-coded lines, allowing for quick historical pattern recognition and analysis.
 Data Structure Innovation 
Let's talk about one of the most interesting challenges I faced. PineScript has this quirky limitation where request.security() can only return 127 tuples at most. £To work around this, I implemented a dual-request system. The first request handles indices 0-63, while the second one takes care of indices 64-127. 
This approach lets us maintain extensive historical data without compromising script stability. 
And here's the cool part: if you need to handle even more years of historical data, you can simply extend this pattern by adding more request.security() calls. 
Each additional call can fetch another batch of monthly open prices and timestamps, following the same structure I've used. 
Think of it as building with LEGO blocks - you can keep adding more pieces to extend your historical reach.
 Flexible Date Range 
Unlike many scripts that box you into specific timeframes, I've designed this one to be completely flexible with your date selection. You can set any start year, any end year, and the script will dynamically scale everything to match. The visual presentation automatically adjusts to whatever range you choose, ensuring your data is always displayed optimally.
 █ Customization Options 
 Visual Settings 
The panel's visual elements are highly customizable. You can adjust the panel width to perfectly fit your workspace, fine-tune the line thickness to match your preferences, and enjoy the pre-defined year color scheme that makes tracking historical performance intuitive and visually appealing.
 Box Dimensions 
Every aspect of the performance boxes can be tailored to your needs. Adjust their height and width, fine-tune the spacing between them, and position the entire panel exactly where you want it on your chart. The goal is to make this tool feel like it's truly yours.
 █ Technical Challenges Solved 
 Polyline Precision 
Creating precise polylines was perhaps the most demanding aspect of this project. 
The challenge was ensuring accurate positioning across both time and price axes, while handling percentage mode scaling with precision. 
The script constantly updates the current year's data in real-time, seamlessly integrating new information as it comes in.
 Axis Management 
Getting the axes right was like solving a complex puzzle. The Y-axis needed to scale dynamically whether you're viewing absolute prices or percentages. 
The X-axis required careful month labeling that stays clean and readable regardless of your selected timeframe. 
Everything needed to align perfectly while maintaining proper spacing in all conditions.
 █ Final Notes 
This tool transforms complex market data into clear, actionable insights. Whether you're day trading or analyzing long-term trends, it provides the information you need to make informed decisions. And remember, while we can't predict the future, we can certainly be better prepared for it with the right tools at hand.
A word of warning though - seeing those red numbers in a beautifully formatted panel doesn't make them any less painful! 😉
---
Happy Trading! May your charts be green and your stops be far away!
Daveatt
Quick scan for cycles🙏🏻
The followup for
  
As I told before, ML based algorading is all about detecting any kind of non-randomness & exploiting it (cuz  allegedly  u cant trade randomness), and cycles are legit patterns that can be leveraged
But bro would u really apply Fourier / Wavelets / 'whatever else heavy' on every update of thousands of datasets, esp in real time on HFT / nearly HFT data? That's why this metric. It works much faster & eats hell of a less electicity, will do initial rough filtering of time series that might contain any kind of cyclic behaviour. And then, only on these filtered datasets u gonna put Periodograms / Autocorrelograms and see what's going there for real. Better to do it 10x times less a day on 10x less datasets, right? 
I ended up with 2 methods / formulas, I called em 'type 0' and 'type 1':
- type 0: takes sum of abs deviations from drift line, scales it by max abs deviation from the same drift line;
- type 1: takes sum of abs deviations from drift line, scales it by range of non-abs deviations from the same drift line.
 Finnaly I've chosen type 0 , both logically (sum of abs dev divided by max abs dev makes more sense) and experimentally. About that actually, here are both formulas put on sine waves with uniform noise:
  
^^ generated sine wave with uniform noise
  
^^ both formulas on that wave
  
^^ both formulas on real data
As you can see type 0 is less affected by noise and shows higher values on synthetic data, but I decided to put type 1 inside as well, in case my analysis was not complete and on real data type 1 can actually be better since it has a lil higher info gain / info content (still not sure). But I can assure u that out of all other ways I've designed & tested for quite a time I tell you, these 2 are really the only ones who got there.
 Now about dem thresholds and how to use it. 
Both type 0 and type 1 can be modelled with Beta distribution, and based on it and on some obvious & tho non mainstream statistical modelling techniques, I got these thresholds, so these are not optimized overfitted values, but natural ones. Each type has 3 thresholds (from lowest to highest):
- typical value (turned off by default). aka  basis ;
- typical deviation from typical value, aka  deviation ;
- maximum  modelled  deviation from typical value (idk whow to call it properly for now, this is my own R&D), aka  extension .
 So when the metric is above one of these thresholds (which one is up to you, you'll read about it in a sec), it means that there might be a strong enough periodic signal inside the data, and the data got to be put through proper spectral analysis tools to confirm / deny it.  
If you look at the pictures above again, you'll see gray signal, that's uniform noise. Take a look at it and see where does it sit comparing to the thresholds. Now you just undertand that picking up a threshold is all about the amount of false positives you care to withstand.
If you take  basis  as threshold, you'll get tons of false positives (that's why it's even turned off by default), but you'll almost never miss a true positive. If you take  deviation  as threshold, it's gonna be kinda balanced approach. If you take  extension  as threshold, you gonna miss some cycles, and gonna get only the strongest ones.
More true positives -> more false positives, less false positives -> less true positives, can't go around that mane
Just to be clear again, I am not completely sure yet, but I def lean towards type 0 as metric, and deviation as threshold.
Live Long and Prosper
P.S.: That was actually the main R&D of the last month, that script I've released earlier came out as derivative.
P.S.: These 2 are the first R&Ds made completely in "  art-space", St. Petersburg. Come and see me, say wassup🤘🏻
Pine Execution MapPine Script Execution Map 
 
 Overview: 
This is an educational script for Pine Script developers. The script includes data structure, functions/methods, and process to capture and print Pine Script execution map of functions called while pine script execution.
Map of execution is produced for last/latest candle execution.
The script also has example code to call execution map methods and generate Pine Execution map.
 Use cases: 
 
 Pine script developers can get view of how the functions are called
 This can also be used while debugging the code and know which functions are called vs what developer expect code to do
 One can use this while using any of the open source published script and understand how public script is organized and how functions of the script are called.
 
 Code components: 
User defined type
 type EMAP
    string group 
    string sub_group
    int level
array emap = array.new()
 
method called internally by other methods to generate level of function being executed
 method id(string tag) =>
    if(str.startswith(tag, "MAIN"))
        exe_level.set(0, 0)
    else if(str.startswith(tag, "END"))
        exe_level.set(0, exe_level.get(0) - 1)
    else 
        exe_level.set(0, exe_level.get(0) + 1)
    exe_level.get(0)
 
Method called from main/global scope to record execution of main scope code. There should be only one call to this method at the start of global scope.
 method main(string tag) =>
    this = EMAP.new()
    this.group := "MAIN"
    this.sub_group := tag 
    this.level := "MAIN".id()
    emap.push(this)
 
Method called from main/global scope to record end of execution of main scope code. There should be only one call to this method at the end of global scope.
 method end_main(string tag) =>
    this = EMAP.new()
    this.group := "END_MAIN"
    this.sub_group := tag 
    this.level := 0
    emap.push(this)
 
Method called from start of each function to record execution of function code
 method call(string tag) =>
    this = EMAP.new()
    this.group := "SUB"
    this.sub_group := tag
    this.level := "SUB".id() 
    emap.push(this)
 
Method called from end of each function to record end of execution of function code
 method end_call(string tag) =>
    this = EMAP.new()
    this.group := "END_SUB"
    this.sub_group := tag 
    this.level := "END_SUB".id()
    emap.push(this)
 
Pine code which generates execution map and show it as a label tooltip.
 if(barstate.islast)
    for rec in emap 
        if(not str.startswith(rec.group, "END"))
            lvl_tab = str.repeat("", rec.level+1, "\t")
            txt = str.format("=> {0}  {1}>  {2}", lvl_tab, rec.level, rec.sub_group)
            debug.log(txt)
    debug.lastr()
 
 Snapshot 1: 
This is the output of the script and can be viewed by hovering mouse pointer over the blue color diamond shaped label
  
 Snapshot 2: 
How to read the Pine execution map
  
Value at Risk [OmegaTools]The "Value at Risk" (VaR) indicator is a powerful financial risk management tool that helps traders estimate the potential losses in a portfolio over a specified period of time, given a certain level of confidence. VaR is widely used by financial institutions, traders, and risk managers to assess the probability of portfolio losses in both normal and volatile market conditions. This TradingView script implements a comprehensive VaR calculation using several models, allowing users to visualize different risk scenarios and adjust their trading strategies accordingly.
 Concept of Value at Risk 
Value at Risk (VaR) is a statistical technique used to measure the likelihood of losses in a portfolio or financial asset due to market risks. In essence, it answers the question: "What is the maximum potential loss that could occur in a given portfolio over a specific time horizon, with a certain confidence level?" For instance, if a portfolio has a one-day 95% VaR of $10,000, it means that there is a 95% chance the portfolio will not lose more than $10,000 in a single day. Conversely, there is a 5% chance of losing more than $10,000. VaR is a key risk management tool for portfolio managers and traders because it quantifies potential losses in monetary terms, allowing for better-informed decision-making.
There are several ways to calculate VaR, and this indicator script incorporates three of the most commonly used models:
Historical VaR: This approach uses historical returns to estimate potential losses. It is based purely on past price data, assuming that the past distribution of returns is indicative of future risks.
Variance-Covariance VaR: This model assumes that asset returns follow a normal distribution and that the risk can be summarized using the mean and standard deviation of past returns. It is a parametric method that is widely used in financial risk management.
Exponentially Weighted Moving Average (EWMA) VaR: In this model, recent data points are given more weight than older data. This dynamic approach allows the VaR estimation to react more quickly to changes in market volatility, which is particularly useful during periods of market stress. This model uses the Exponential Weighted Moving Average Volatility Model.
 How the Script Works 
The script starts by offering users a set of customizable input settings. The first input allows the user to choose between two main calculation modes: "All" or "OCT" (Only Current Timeframe). In the "All" mode, the script calculates VaR using all available methodologies—Historical, Variance-Covariance, and EWMA—providing a comprehensive risk overview. The "OCT" mode narrows the calculation to the current timeframe, which can be particularly useful for intraday traders who need a more focused view of risk.
The next input is the lookback window, which defines the number of historical periods used to calculate VaR. Commonly used lookback periods include 21 days (approximately one month), 63 days (about three months), and 252 days (roughly one year), with the script supporting up to 504 days for more extended historical analysis. A longer lookback period provides a more comprehensive picture of risk but may be less responsive to recent market conditions.
The confidence level is another important setting in the script. This represents the probability that the loss will not exceed the VaR estimate. Standard confidence levels are 90%, 95%, and 99%. A higher confidence level results in a more conservative risk estimate, meaning that the calculated VaR will reflect a more extreme loss scenario.
In addition to these core settings, the script allows users to customize the visual appearance of the indicator. For example, traders can choose different colors for "Bullish" (Risk On), "Bearish" (Risk Off), and "Neutral" phases, as well as colors for highlighting "Breaks" in the data, where returns exceed the calculated VaR. These visual cues make it easy to identify periods of heightened risk at a glance.
The actual VaR calculation is broken down into several models, starting with the Historical VaR calculation. This is done by computing the logarithmic returns of the asset's closing prices and then using linear interpolation to determine the percentile corresponding to the desired confidence level. This percentile represents the potential loss in the asset over the lookback period.
Next, the script calculates Variance-Covariance VaR using the mean and standard deviation of the historical returns. The standard deviation is multiplied by a z-score corresponding to the chosen confidence level (e.g., 1.645 for 95% confidence), and the resulting value is subtracted from the mean return to arrive at the VaR estimate.
The EWMA VaR model uses the EWMA for the sigma parameter, the standard deviation, obtaining a specific dynamic in the volatility. It is particularly useful in volatile markets where recent price behavior is more indicative of future risk than older data.
For traders interested in intraday risk management, the script provides several methods to adjust VaR calculations for lower timeframes. By using intraday returns and scaling them according to the chosen timeframe, the script provides a dynamic view of risk throughout the trading day. This is especially important for short-term traders who need to manage their exposure during high-volatility periods within the same day. The script also incorporates an EWMA model for intraday data, which gives greater weight to the most recent intraday price movements.
In addition to calculating VaR, the script also attempts to detect periods where the asset's returns exceed the estimated VaR threshold, referred to as "Breaks." When the returns breach the VaR limit, the script highlights these instances on the chart, allowing traders to quickly identify periods of extreme risk. The script also calculates the average of these breaks and displays it for comparison, helping traders understand how frequently these high-risk periods occur.
The script further visualizes the risk scenario using a risk phase classification system. Depending on the level of risk, the script categorizes the market as either "Risk On," "Risk Off," or "Risk Neutral." In "Risk On" mode, the market is considered bullish, and the indicator displays a green background. In "Risk Off" mode, the market is bearish, and the background turns red. If the market is neither strongly bullish nor bearish, the background turns neutral, signaling a balanced risk environment.
Traders can customize whether they want to see this risk phase background, along with toggling the display of the various VaR models, the intraday methods, and the break signals. This flexibility allows traders to tailor the indicator to their specific needs, whether they are day traders looking for quick intraday insights or longer-term investors focused on historical risk analysis.
The "Risk On" and "Risk Off" phases calculated by this Value at Risk (VaR) script introduce a novel approach to market risk assessment, offering traders an advanced toolset to gauge market sentiment and potential risk levels dynamically. These risk phases are built on a combination of traditional VaR methodologies and proprietary logic to create a more responsive and intuitive way to manage exposure in both normal and volatile market conditions. This method of classifying market conditions into "Risk On," "Risk Off," or "Risk Neutral" is not something that has been traditionally associated with VaR, making it a groundbreaking addition to this indicator.
 How the "Risk On" and "Risk Off" Phases Are Calculated 
In typical VaR implementations, the focus is on calculating the potential losses at a given confidence level without providing an overall market outlook. This script, however, introduces a unique risk classification system that takes the output of various VaR models and translates it into actionable signals for traders, marking whether the market is in a Risk On, Risk Off, or Risk Neutral phase.
The Risk On and Risk Off phases are primarily determined by comparing the current returns of the asset to the average VaR calculated across several different methods, including Historical VaR, Variance-Covariance VaR, and EWMA VaR. Here's how the process works:
1. Threshold Setting and Effect Calculation: The script first computes the average VaR using the selected models. It then checks whether the current returns (expressed as a negative value to signify loss) exceed the average VaR value. If the current returns surpass the calculated VaR threshold, this indicates that the actual market risk is higher than expected, signaling a potential shift in market conditions.
   
2. Break Analysis: In addition to monitoring whether returns exceed the average VaR, the script counts the number of instances within the lookback period where this breach occurs. This is referred to as the "break effect." For each period in the lookback window, the script checks whether the returns surpass the calculated VaR threshold and increments a counter. The percentage of periods where this breach occurs is then calculated as the "effect" or break percentage.
   
3. Dual Effect Check (if "Double" Risk Scenario is selected): When the user chooses the "Double" risk scenario mode, the script performs two layers of analysis. First, it calculates the effect of returns exceeding the VaR threshold for the current timeframe. Then, it calculates the effect for the lower intraday timeframe as well. Both effects are compared to the user-defined confidence level (e.g., 95%). If both effects exceed the confidence level, the market is deemed to be in a high-risk situation, thus triggering a Risk Off phase. If both effects fall below the confidence level, the market is classified as Risk On.
   
4. Risk Phases Determination: The final risk phase is determined by analyzing these effects in relation to the confidence level:
   - Risk On: If the calculated effect of breaks is lower than the confidence level (e.g., fewer than 5% of periods show returns exceeding the VaR threshold for a 95% confidence level), the market is considered to be in a relatively safe state, and the script signals a "Risk On" phase. This is indicative of bullish conditions where the potential for extreme loss is minimal.
   - Risk Off: If the break effect exceeds the confidence level (e.g., more than 5% of periods show returns breaching the VaR threshold), the market is deemed to be in a high-risk state, and the script signals a "Risk Off" phase. This indicates bearish market conditions where the likelihood of significant losses is higher.
   - Risk Neutral: If the break effect hovers near the confidence level or if there is no clear trend indicating a shift toward either extreme, the market is classified as "Risk Neutral." In this phase, neither bulls nor bears are dominant, and traders should remain cautious.
The phase color that the script uses helps visualize these risk phases. The background will turn green in Risk On conditions, red in Risk Off conditions, and gray in Risk Neutral phases, providing immediate visual feedback on market risk. In addition to this, when the "Double" risk scenario is selected, the background will only turn green or red if both the current and intraday timeframes confirm the respective risk phase. This double-checking process ensures that traders are only given a strong signal when both longer-term and short-term risks align, reducing the likelihood of false signals.
 A New Way of Using Value at Risk 
This innovative Risk On/Risk Off classification, based on the interaction between VaR thresholds and market returns, represents a significant departure from the traditional use of Value at Risk as a pure risk measurement tool. Typically, VaR is employed as a backward-looking measure of risk, providing a static estimate of potential losses over a given timeframe with no immediate actionable feedback on current market conditions. This script, however, dynamically interprets VaR results to create a forward-looking, real-time signal that informs traders whether they are operating in a favorable (Risk On) or unfavorable (Risk Off) environment. 
By incorporating the "break effect" analysis and allowing users to view the VaR breaches as a percentage of past occurrences, the script adds a predictive element that can be used to time market entries and exits more effectively. This **dual-layer risk analysis**, particularly when using the "Double" scenario mode, adds further granularity by considering both current timeframe and intraday risks. Traders can therefore make more informed decisions not just based on historical risk data, but on how the market is behaving in real-time relative to those risk benchmarks.
This approach transforms the VaR indicator from a risk monitoring tool into a decision-making system that helps identify favorable trading opportunities while alerting users to potential market downturns. It provides a more holistic view of market conditions by combining both statistical risk measurement and intuitive phase-based market analysis. This level of integration between VaR methodologies and real-time signal generation has not been widely seen in the world of trading indicators, marking this script as a cutting-edge tool for risk management and market sentiment analysis.
I would like to express my sincere gratitude to @skewedzeta for his invaluable contribution to the final script. From generating fresh ideas to applying his expertise in reviewing the formula, his support has been instrumental in refining the outcome.
Macros ICT KillZones [TradingFinder] Times & Price Trading Setup🔵 Introduction 
ICT Macros, developed by Michael Huddleston, also known as ICT (Inner Circle Trader), is a powerful trading tool designed to help traders identify the best trading opportunities during key time intervals like the London and New York trading sessions. 
For traders aiming to capitalize on market volatility, liquidity shifts, and Fair Value Gaps (FVG), understanding and using these critical time zones can significantly improve trading outcomes.
In today’s highly competitive financial markets, identifying the moments when the market is seeking buy-side or sell-side liquidity, or filling price imbalances, is essential for maximizing profitability. 
The ICT Macros indicator is built on the renowned ICT time and price theory, which enables traders to track and leverage key market dynamics such as breaks of highs and lows, imbalances, and liquidity hunts.
This indicator automatically detects crucial market times and optimizes strategies for traders by highlighting the specific moments when price movements are most likely to occur. A standout feature of ICT Macros is its automatic adjustment for Daylight Saving Time (DST), ensuring that traders remain synced with the correct session times. 
This means you can rely on accurate market timing without the need for manual updates, allowing you to focus on capturing profitable trades during critical timeframes.
  
🔵 How to Use 
The ICT Macros indicator helps you capitalize on trading opportunities during key market moments, particularly when the market is breaking highs or lows, filling Fair Value Gaps (FVG), or addressing imbalances. This indicator is particularly beneficial for traders who seek to identify liquidity, market volatility, and price imbalances. 
🟣 Sessions 
 London Sessions 
 London Macro 1 :
 
 UTC Time : 06:33 to 07:00
 New York Time : 02:33 to 03:00
 
 London Macro 2 :
 
 UTC Time : 08:03 to 08:30
 New York Time : 04:03 to 04:30
 
 New York Sessions 
 New York Macro AM 1 :
 
 UTC Time : 12:50 to 13:10
 New York Time : 08:50 to 09:10
 
 New York Macro AM 2 :
 
 UTC Time : 13:50 to 14:10
 New York Time : 09:50 to 10:10
 
 New York Macro AM 3 :
 
 UTC Time : 14:50 to 15:10
 New York Time : 10:50 to 11:10
 
 New York Lunch Macro :
 
 UTC Time : 15:50 to 16:10
 New York Time : 11:50 to 12:10
 
 New York PM Macro :
 
 UTC Time : 17:10 to 17:40
 New York Time : 13:10 to 13:40
 
 New York Last Hour Macro :
 
 UTC Time : 19:15 to 19:45
 New York Time : 15:15 to 15:45
 
These time intervals adjust automatically based on Daylight Saving Time (DST), helping traders to enter or exit trades during key market moments when price volatility is high.
  
  
  
 Below are the main applications of this tool and how to incorporate it into your trading strategies :
🟣 Combining ICT Macros with Trading Strategies 
The ICT Macros indicator can easily be used in conjunction with various trading strategies. Two well-known strategies that can be combined with this indicator include:
 ICT 2022 Trading Model : This model is designed based on identifying market liquidity, structural price changes, and Fair Value Gaps (FVG). By using ICT Macros, you can identify the key time intervals when the market is seeking liquidity, filling imbalances, or breaking through important highs and lows, allowing you to enter or exit trades at the right moment.
 Silver Bullet Strategy : This strategy, which is built around liquidity hunting and rapid price movements, can work more accurately with the help of ICT Macros. The indicator pinpoints precise liquidity times, helping traders take advantage of market shifts caused by filling Fair Value Gaps or correcting imbalances.
  
🟣 Capitalizing on Price Volatility During Key Times 
Large market algorithms often seek liquidity or fill Fair Value Gaps (FVG) during the intervals marked by ICT Macros. These periods are when price volatility increases, and traders can use these moments to enter or exit trades. 
For example, if sell-side liquidity is drained and the market fills an imbalance, the price might move toward buy-side liquidity. By identifying these moments, which may also involve breaking a previous high or low, you can leverage rapid market fluctuations to your advantage.
  
🟣 Identifying Liquidity and Price Imbalances 
One of the important uses of ICT Macros is identifying points where the market is seeking liquidity and correcting imbalances. You can determine high or low liquidity levels in the market before each ICT Macro, as well as Fair Value Gaps (FVG) and price imbalances that need to be filled, using them to adjust your trading strategy. This capability allows you to manage trades based on liquidity shifts or imbalance corrections without needing a bias toward a specific direction.
🔵 Settings 
The ICT Macros indicator offers various customization options, allowing users to tailor it to their specific needs. Below are the main settings:
 Time Zone Mode : You can select one of the following options to define how time is displayed:
 
 UTC : For traders who need to work with Universal Time.
 Session Local Time : The local time corresponding to the London or New York markets.
 Your Time Zone : You can specify your own time zone (e.g., "UTC-4:00").
 
 Your Time Zone : If you choose "Your Time Zone," you can set your specific time zone. By default, this is set to UTC-4:00.
 Show Range Time : This option allows you to display the time range of each session on the chart. If enabled, the exact start and end times of each interval are shown.
 Show or Hide Time Ranges : Toggle on/off for visual clarity depending on user preference.
 Custom Colors : Set distinct colors for each session, allowing users to personalize their chart based on their trading style.These settings allow you to adjust the key time intervals of each trading session to your preference and customize the time format according to your own needs.
🔵 Conclusion 
The ICT Macros indicator is a powerful tool for traders, helping them to identify key time intervals where the market seeks liquidity or fills Fair Value Gaps (FVG), corrects imbalances, and breaks highs or lows. This tool is especially valuable for traders using liquidity-based strategies such as ICT 2022 or Silver Bullet.
One of the key features of this indicator is its support for Daylight Saving Time (DST), ensuring you are always in sync with the correct trading session timings without manual adjustments. This is particularly beneficial for traders operating across different time zones.
With ICT Macros, you can capitalize on crucial market opportunities during sensitive times, take advantage of imbalances, and enhance your trading strategies based on market volatility, liquidity shifts, and Fair Value Gaps.
RSI Fakeout Filter with SMA Confirmation [CHE]  Introducing: RSI Fakeout Detection  
Are you tired of being caught in fakeouts that can lead to frustrating losses? The RSI Fakeout Detection   is here to enhance your trading strategy by filtering out false signals and providing you with more reliable entries. This innovative indicator is designed to help traders identify when market momentum, as indicated by the RSI, does not align with price movement – a key indicator of potential fakeouts!
  What Does It Do? 
The RSI Fakeout Detection focuses on one key goal: avoiding false signals. By monitoring when the RSI exceeds a customizable threshold (indicating strength) but the price remains below a moving average like the SMA, this indicator highlights situations where the market may seem strong, but the price action doesn't support that momentum. In other words, it saves you from those tricky fake breakouts.
  Key Benefits: 
1. Reduce Risk, Increase Confidence: Get an extra layer of protection against fakeouts by receiving signals only when both RSI and price confirm the market's true direction. Avoid entering false breakouts and trade with more confidence.
   
2. Dynamic Analysis of SMA Lengths: It doesn’t just rely on one SMA. The indicator automatically analyzes and sorts through different SMA lengths to find the most reliable one for your specific market condition, ensuring that you get the best possible signal.
3. Tailored for You: With customizable RSI thresholds, a choice of multiple moving average types (SMA, EMA, Bollinger Bands, and more), and vibrant color-coded visuals, this tool is built to fit your unique trading style and preferences.
4. Spot Fakeouts with Ease: Visual cues make it easy to see when the market might be tricking you. Labels, plotted lines, and a toggleable disclaimer keep everything transparent and easy to understand.
5. Friendly and Intuitive: Whether you’re new to trading or a seasoned pro, the RSI Fakeout Detection is designed to be simple and effective. The labels and plots are clear, the alerts are timely, and it seamlessly integrates into your chart without cluttering it.
 Why Choose RSI Fakeout Detection?
- Accuracy and Precision: By combining RSI and SMA analysis, this indicator minimizes the risk of following false trends and entering trades too early.
- Save Time and Reduce Guesswork: No more spending hours trying to figure out which SMA length works best – the RSI Fakeout Detection does it for you!
- Peace of Mind: Avoiding fakeouts means fewer bad trades, which can lead to more consistent performance and less stress.
Transform the way you trade, and step into a more confident trading future with RSI Fakeout Detection  . Whether you’re day trading or swing trading, this tool will give you an edge by helping you filter out the noise and make more informed decisions.
Best regards,  
Chervolino
 Disclaimer:
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Custom Pattern DetectionOverview 
Chart Patterns is a major tool for many traders. Pattern formation at specific location on the chart is used for investment/trading decisions.
This indicator is designed in a way to allow investors/traders to define patterns of their choice based on certain input parameters and then detect defined pattern on the chart. 
Investors/traders can use their own creativity to create and detect patterns.
This indicator works in 2 modes
 
 Create Pattern: One can define a pattern and verify sample pattern formation visually
 Detect Pattern: Detect and mark patterns on the chart
 
 Settings 
 Create Custom Pattern: 
 Show Custom Pattern  – This will mark the pattern lines on the chart so that one can verify how pattern appears based on the input’s parameters provided for lines XA, AB, BC, CD, DE, EF
 Offset  – Used while pattern creation. Offset is horizonal distance between 2 lines.
 XA Points  – Used to draw XA line when sample pattern is drawn. XA points can be a negative or position number. 
XA line is drawn based on Offset and XA Points. E.g. Offset = 5 and XA Points = -20. In this line would be drawn from last candle high to high – 20 (these are y1 and y2 points of a line). While drawing line distance of 5 candles would be placed between 2 line points (these are x1 and x2 points of a line). In XA line X forms start point and A forms end point of the line.
Line AB – Line AB is drawn from point X. To derive the end point of AB, average Fib% is derived based on From Fib% and To Fib% parameters. Finally end point is derived by applying Fib Retracement on Line XA based on average Fib%.
Line AB to Line EF – These points are derived as explained in Line AB.
The indicator can be used to define/create patterns up to 6 legs/lines. The line would be named as XA -> AB -> BC -> CD -> DE -> EF.
If one wish to create pattern consisting 3 legs then it can be achieved by unchecking/deselecting Line CD, DE and EF or by checking only Line AB and BC.
Based on the parameters above indicator draws a sample pattern after last candle/bar on the chart. Sample pattern helps to visually see how pattern will appear on the chart.
 Pattern Identification 
Indicator derive the swing high/low points based on the Pivot lookback and use as reference points while detecting patterns.
Use of From Fib% and To Fib% - While detecting pattern, retracement price points are derived for From Fib% and To Fib%. Price points between from Fib% and To Fib% are treated as valid retracement points.
 How to configure and use indicator for detecting patterns 
 Sample Pattern 1 
  
 Sample Pattern 2 
   
 Sample Pattern 3  
  
 Sample Pattern 4  
 
Shifted Symbol Overlay with OffsetThe Shifted Symbol Overlay Indicator is a custom TradingView indicator designed to overlay the price data of one stock or asset over another, allowing for direct visual comparison. This is particularly useful for comparing the performance of two assets over different time periods. The indicator enables you to shift the data from one asset either forward or backward in time, making it easier to compare historical data from one stock with more recent data from another. The indicator supports shifting both to the right (future periods) and to the left (earlier periods), helping traders and analysts explore correlations or divergences between two financial instruments.
The indicator also includes a normalization option that adjusts the scale of the two assets, so you can compare them even if they have vastly different price levels. This is useful when you're interested in relative performance rather than the absolute price values.
Absolute ZigZagThis ZigZag Indicator is a bit unique in it's kind. 
It uses my own Absolute ZigZag Lib to calculate the pivots:
Instead of using percentages or looking more than 1 bar left or right, this Zigzag library calculates pivots by just looking at the current bar highs and lows and the ones of one bar earlier. This is a very fast and accurate way of calculating pivots.
The library also features a solution for bars that have both a higher high and a higher low like seen below.
  
You can also use your own colors for the labels and the lines:
  
You can also quickly select a one-colored theme without changing all colors at once:
 
Tian Di Grid Merge Version 6.0
Strategy Introduction:
1. We know that the exchange can only set a maximum of 100 grids. However, our grid strategy can set a maximum of 350 grids.
2. We have added the modes of proportional and differential warehousing.
3. It should be noted that we have not set any filtering conditions, which means that when the price falls below the grid, we will execute a buy action at the closing price, and when the price falls above the grid, we will execute a sell action;
4. We suggest limiting the trading time cycle to 5 meters, as sometimes errors may appear on TV due to the dense grid or the inability to draw so many grids;
5. Please ensure that the minimum spacing between each grid is not less than 0.1%, as this is extremely difficult to profit from, and on the other hand, it may not function due to excessively dense spacing;
6. The maximum number of grids is 350, and the minimum number is currently 3;
matters needing attention:
Don't choose to go long or short together, and don't choose to go even short or short;
Closing position setting: It is recommended to select it to avoid order accumulation;
Unable to trade: If unable to trade normally, switch to a 1m cycle;
Number of cells: Calculate it yourself, 350 is just the maximum number of cells that can be adjusted;
Grid spacing: minimum 0.1%, below which no profit can be made;
Position value: default is 100u, which is the amount already leveraged;
Multiple investment: The order amount for each order is the same, and there is no need for multiple investment;
Open both long and short positions: You can open multiple positions for one account and open one position for one account. Do not open both long and short positions for the same target at the same time
Pressure Zones with MA [SYNC & TRADE]Description:
The "Pressure Zones with MA  " indicator is designed to analyze the pressure of buyers and sellers on the market, as well as to identify areas of increased activity. When designing it, the main task was to see manipulations on the market, when the power of sellers or the power of buyers is in a sideways trend or falling, and the opposite is growing.
Here is a good example. The power of sellers is in a narrow sideways trend, and sales are increasing very aggressively. The power of buyers is in a gray block with the inscription "range". Then we see the fading of the power of sellers and buyers furiously pounce on the asset that has fallen in price.
Here are the main aspects of its operation and use:
First, turn off the moving averages in the indicator settings, on the "style" tab. Choose your favorite asset, which you understand well and know all its ups and downs. I want you to see a clean chart, so that you can be imbued with a new idea, you need to watch it. This is a proprietary indicator and I understand that it does not have the inscription “buy” / “sell”, but believe me, if you pay attention, you will see its strength. I usually add functionality later, but the light code and visualization remain preferable in the first version.
Purpose:
The indicator helps to determine the strength of buyers and sellers in the market.
It visualizes zones where the pressure of buyers or sellers prevails.
Additionally displays moving averages (MA) for data smoothing.
Main components:
Buyer strength chart (blue line)
Seller strength chart (red line)
Moving averages for buyer and seller strength
Threshold line for defining zones
Indicator settings:
Period: defines the base period for calculations (default 89)
Threshold: sets the level for defining pressure zones (from 0 to 2, default 0.8)
MA type for purchases and sales: select the type of moving average (SMA, EMA, RMA, WMA, VWMA, HMA)
MA length for purchases and sales: period for calculating moving averages
Colors for uptrends and downtrends of MA
Moving averages:
Help smooth out data and identify trends
The direction of the MA (up or down) further confirms the current trend
The color of the MA changes depending on the direction (blue for up, red for down)
Now you can turn them on and see how they help in understanding where one or another force is weakening. It is in this case that we see the intersection of forces and the sellers' force is moving aggressively upward. Also, according to the moving average, we see the weakening of the sellers' force. The buyers' force was in the sideways range and then switched on to buy out and also according to the moving average, it is clear where the main interest in purchases disappeared.
Use:
Observe the strength of buyers and sellers relative to each other. They can move simultaneously in one direction, this is regarded as balance
can move in different directions and this will strengthen the upward force of sellers or buyers
You may also notice that the movement of one of the forces will be in a narrow range and the second will grow strongly - this is manipulation or trading without resistance.
You can also play with the threshold line, but it is not the main thing here. I disabled this function in the code.
// Display zones
//bgcolor(buy_zone ? color.new(color.blue, 90) : na)
//bgcolor(sell_zone ? color.new(color.red, 90) : na)
If you want to enable it, copy it instead
// Display zones
bgcolor(buy_zone ? color.new(color.blue, 90) : na)
bgcolor(sell_zone ? color.new(color.red, 90) : na)
Pay attention to the intersection of forces.
Use crossovers of force lines and their moving averages as potential signals
Combine the indicator signals with other technical analysis tools for confirmation
Limitations:
Requires customization of parameters for a specific trading instrument and timeframe
The indicator should not be used as the only tool for making trading decisions
Remember that this indicator provides additional information for market analysis, but is not a guarantee of successful trades. Always combine it with other analysis methods and follow risk management rules.
Описание:
Индикатор "Pressure Zones with MA  " предназначен для анализа давления покупателей и продавцов на рынке, а также для определения зон повышенной активности. При его проектировании основная задача была увидеть манипуляции на рынке, когда сила продавцов или сила покупателей стоит в боковике или падает, а противоположная растет.
Вот хороший пример. Сила продавцов стоит в узком боковике, а продажи очень агрессивно усиливаются. Сила покупателей в сером блоке с надписью “range”. Потом мы видим затухание силы продавцов и покупателей яростно накидываются на подешевевший актив.
Вот основные аспекты его работы и использования:
Для начала отключите средние скользящие в настройках индикатора, на закладке “стиль”. Выберите свой любимый актив, в котором вы хорошо разбираетесь и знаете его все взлеты и падения. Я хочу чтобы вы увидели чистый график, для того чтобы вы могли проникнутся новой идеей нужно понаблюдать за ним. Это авторский индикатор и я понимаю что на нем нет надписи “купить” / “продать”, но поверьте уделив свое внимание вы увидите его силу. Я обычно потом добавляю функционал но легкий код и визуализация, в первом варианте остается предпочтительней. 
Назначение:
Индикатор помогает определить силу покупателей и продавцов на рынке.
Он визуализирует зоны, где преобладает давление покупателей или продавцов.
Дополнительно отображает скользящие средние (MA) для сглаживания данных.
Основные компоненты:
График силы покупателей (синяя линия)
График силы продавцов (красная линия)
Скользящие средние для силы покупателей и продавцов
Пороговая линия для определения зон
Настройки индикатора:
Период (Period): определяет базовый период для расчетов (по умолчанию 89)
Порог (Threshold): устанавливает уровень для определения зон давления (от 0 до 2, по умолчанию 0.8)
Тип MA для покупок и продаж: выбор типа скользящей средней (SMA, EMA, RMA, WMA, VWMA, HMA)
Длина MA для покупок и продаж: период для расчета скользящих средних
Цвета для восходящего и нисходящего трендов MA
Скользящие средние:
Помогают сглаживать данные и выявлять тренды
Направление MA (вверх или вниз) дополнительно подтверждает текущий тренд
Цвет MA меняется в зависимости от направления (синий для восходящего, красный для нисходящего)
Теперь вы можете их включить и посмотреть как они помогают в понимании где ослабевает та или иная сила. Именно в этом случае мы видим пересечение сил и сила продавцов идет агрессивно вверх. Также по средней скользящей мы видим затухание силы продавцов. Сила покупателей стояла в боковике потом включилась на откуп и также по средней скользящей видно где пропал основной интерес к покупкам.
Использование:
Наблюдайте за силой покупателей и продавцов относительно друг друга. Они могут двигаться одновременно в одном направлении это расценивается как баланс
могут двигаться в разных направлениях и это будет усиливать восходящую силу продавцов или покупателей
также возможно вы заметите что движение одной из силы будет в узком диапазоне а вторая будет сильно расти - это манипуляция или торговля без сопротивления.
Также можете поиграть с пороговой линией, но она совершенно не главная здесь. В коде я отключил эту функцию. 
// Display zones
//bgcolor(buy_zone ? color.new(color.blue, 90) : na)
//bgcolor(sell_zone ? color.new(color.red, 90) : na)
Если захотите включить скопируйте вместо нее
// Display zones
bgcolor(buy_zone ? color.new(color.blue, 90) : na)
bgcolor(sell_zone ? color.new(color.red, 90) : na)
Обращайте внимание на пересечение сил.
Используйте пересечения линий силы и их скользящих средних как потенциальные сигналы
Комбинируйте сигналы индикатора с другими инструментами технического анализа для подтверждения
Ограничения:
Требуется настройка параметров под конкретный торговый инструмент и таймфрейм
Не следует использовать индикатор как единственный инструмент для принятия торговых решений
Помните, что этот индикатор предоставляет дополнительную информацию для анализа рынка, но не является гарантией успешных сделок. Всегда сочетайте его с другими методами анализа и соблюдайте правила управления рисками.
VWAP SlopePublishing one of the simplest yet one of my favorite concepts. Had to publish since I didn't really find any script for this on TV.
VWAP slope.
This is nothing fancy because it's just calculating "slope" with a very basic level formula
vwap_slope = (vwap - vwap ) / length
Above zero line, it's positive zone.
Below zero line, it's a negative zone.
The idea is to avoid choppy conditions and stay true to larger readings, sometimes when we have vwap directly on chart and when price interacts with it, we tend to take the lot of bad trades.
The intention here is to avoid just that. 
This is also good at tracking failure of change in sentiments, this failure is very important, because one's failure occurs there is significant movement in the opposite direction of the failure.
Since there isn't much alteration to this idea, there is not much to talk about tbh.
Just remember, this is an educational idea and not assurance of future performance.
Regards.
DrawingLibrary   "Drawing" 
User Defined types and methods for basic drawing structure. Consolidated from the earlier libraries - DrawingTypes and DrawingMethods
 method get_price(this, bar) 
  get line price based on bar
  Namespace types: Line
  Parameters:
     this (Line) : (series Line) Line object.
     bar (int) : (series/int) bar at which line price need to be calculated
  Returns: line price at given bar.
 method init(this) 
  Namespace types: PolyLine
  Parameters:
     this (PolyLine) 
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/Point object to string representation
  Namespace types: chart.point
  Parameters:
     this (chart.point) : DrawingTypes/Point object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/Point
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/LineProperties object to string representation
  Namespace types: LineProperties
  Parameters:
     this (LineProperties) : DrawingTypes/LineProperties object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/LineProperties
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/Line object to string representation
  Namespace types: Line
  Parameters:
     this (Line) : DrawingTypes/Line object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/Line
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/LabelProperties object to string representation
  Namespace types: LabelProperties
  Parameters:
     this (LabelProperties) : DrawingTypes/LabelProperties object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/LabelProperties
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/Label object to string representation
  Namespace types: Label
  Parameters:
     this (Label) : DrawingTypes/Label object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/Label
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/Linefill object to string representation
  Namespace types: Linefill
  Parameters:
     this (Linefill) : DrawingTypes/Linefill object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/Linefill
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/BoxProperties object to string representation
  Namespace types: BoxProperties
  Parameters:
     this (BoxProperties) : DrawingTypes/BoxProperties object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/BoxProperties
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/BoxText object to string representation
  Namespace types: BoxText
  Parameters:
     this (BoxText) : DrawingTypes/BoxText object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/BoxText
 method tostring(this, sortKeys, sortOrder, includeKeys) 
  Converts DrawingTypes/Box object to string representation
  Namespace types: Box
  Parameters:
     this (Box) : DrawingTypes/Box object
     sortKeys (bool) : If set to true, string output is sorted by keys.
     sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
     includeKeys (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
  Returns: string representation of DrawingTypes/Box
 method delete(this) 
  Deletes line from DrawingTypes/Line object
  Namespace types: Line
  Parameters:
     this (Line) : DrawingTypes/Line object
  Returns: Line object deleted
 method delete(this) 
  Deletes label from DrawingTypes/Label object
  Namespace types: Label
  Parameters:
     this (Label) : DrawingTypes/Label object
  Returns: Label object deleted
 method delete(this) 
  Deletes Linefill from DrawingTypes/Linefill object
  Namespace types: Linefill
  Parameters:
     this (Linefill) : DrawingTypes/Linefill object
  Returns: Linefill object deleted
 method delete(this) 
  Deletes box from DrawingTypes/Box object
  Namespace types: Box
  Parameters:
     this (Box) : DrawingTypes/Box object
  Returns: DrawingTypes/Box object deleted
 method delete(this) 
  Deletes lines from array of DrawingTypes/Line objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Line objects
  Returns: Array of DrawingTypes/Line objects
 method delete(this) 
  Deletes labels from array of DrawingTypes/Label objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Label objects
  Returns: Array of DrawingTypes/Label objects
 method delete(this) 
  Deletes linefill from array of DrawingTypes/Linefill objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Linefill objects
  Returns: Array of DrawingTypes/Linefill objects
 method delete(this) 
  Deletes boxes from array of DrawingTypes/Box objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Box objects
  Returns: Array of DrawingTypes/Box objects
 method clear(this) 
  clear items from array of DrawingTypes/Line while deleting underlying objects
  Namespace types: array
  Parameters:
     this (array) : array
  Returns: void
 method clear(this) 
  clear items from array of DrawingTypes/Label while deleting underlying objects
  Namespace types: array
  Parameters:
     this (array) : array
  Returns: void
 method clear(this) 
  clear items from array of DrawingTypes/Linefill while deleting underlying objects
  Namespace types: array
  Parameters:
     this (array) : array
  Returns: void
 method clear(this) 
  clear items from array of DrawingTypes/Box while deleting underlying objects
  Namespace types: array
  Parameters:
     this (array) : array
  Returns: void
 method draw(this) 
  Creates line from DrawingTypes/Line object
  Namespace types: Line
  Parameters:
     this (Line) : DrawingTypes/Line object
  Returns: line created from DrawingTypes/Line object
 method draw(this) 
  Creates lines from array of DrawingTypes/Line objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Line objects
  Returns: Array of DrawingTypes/Line objects
 method draw(this) 
  Creates label from DrawingTypes/Label object
  Namespace types: Label
  Parameters:
     this (Label) : DrawingTypes/Label object
  Returns: label created from DrawingTypes/Label object
 method draw(this) 
  Creates labels from array of DrawingTypes/Label objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Label objects
  Returns: Array of DrawingTypes/Label objects
 method draw(this) 
  Creates linefill object from DrawingTypes/Linefill
  Namespace types: Linefill
  Parameters:
     this (Linefill) : DrawingTypes/Linefill objects
  Returns: linefill object created
 method draw(this) 
  Creates linefill objects from array of DrawingTypes/Linefill objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Linefill objects
  Returns: Array of DrawingTypes/Linefill used for creating linefills
 method draw(this) 
  Creates box from DrawingTypes/Box object
  Namespace types: Box
  Parameters:
     this (Box) : DrawingTypes/Box object
  Returns: box created from DrawingTypes/Box object
 method draw(this) 
  Creates labels from array of DrawingTypes/Label objects
  Namespace types: array
  Parameters:
     this (array) : Array of DrawingTypes/Label objects
  Returns: Array of DrawingTypes/Label objects
 method createLabel(this, lblText, tooltip, properties) 
  Creates DrawingTypes/Label object from DrawingTypes/Point
  Namespace types: chart.point
  Parameters:
     this (chart.point) : DrawingTypes/Point object
     lblText (string) : Label text
     tooltip (string) : Tooltip text. Default is na
     properties (LabelProperties) : DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
  Returns: DrawingTypes/Label object
 method createLine(this, other, properties) 
  Creates DrawingTypes/Line object from one DrawingTypes/Point to other
  Namespace types: chart.point
  Parameters:
     this (chart.point) : First DrawingTypes/Point object
     other (chart.point) : Second DrawingTypes/Point object
     properties (LineProperties) : DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
  Returns: DrawingTypes/Line object
 method createLinefill(this, other, fillColor, transparency) 
  Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
  Namespace types: Line
  Parameters:
     this (Line) : First DrawingTypes/Line object
     other (Line) : Other DrawingTypes/Line object
     fillColor (color) : fill color of linefill. Default is color.blue
     transparency (int) : fill transparency for linefill. Default is 80
  Returns: Array of DrawingTypes/Linefill object
 method createBox(this, other, properties, textProperties) 
  Creates DrawingTypes/Box object from one DrawingTypes/Point to other
  Namespace types: chart.point
  Parameters:
     this (chart.point) : First DrawingTypes/Point object
     other (chart.point) : Second DrawingTypes/Point object
     properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
     textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
  Returns: DrawingTypes/Box object
 method createBox(this, properties, textProperties) 
  Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
  Namespace types: Line
  Parameters:
     this (Line) : Diagonal DrawingTypes/PoLineint object
     properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
     textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
  Returns: DrawingTypes/Box object
 LineProperties 
  Properties of line object
  Fields:
     xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
     extend (series string) : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
     color (series color) : Line color
     style (series string) : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
     width (series int) : Line width. Default is 1
 Line 
  Line object created from points
  Fields:
     start (chart.point) : Starting point of the line
     end (chart.point) : Ending point of the line
     properties (LineProperties) : LineProperties object which defines the style of line
     object (series line) : Derived line object
 LabelProperties 
  Properties of label object
  Fields:
     xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
     yloc (series string) : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
     color (series color) : Label fill color
     style (series string) : Label style as defined in Tradingview Documentation. Default is label.style_none
     textcolor (series color) : text color. Default is color.black
     size (series string) : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
     textalign (series string) : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
     text_font_family (series string) : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
 Label 
  Label object
  Fields:
     point (chart.point) : Point where label is drawn
     lblText (series string) : label text
     tooltip (series string) : Tooltip text. Default is na
     properties (LabelProperties) : LabelProperties object
     object (series label) : Pine label object
 Linefill 
  Linefill object
  Fields:
     line1 (Line) : First line to create linefill
     line2 (Line) : Second line to create linefill
     fillColor (series color) : Fill color
     transparency (series int) : Fill transparency range from 0 to 100
     object (series linefill) : linefill object created from wrapper
 BoxProperties 
  BoxProperties object
  Fields:
     border_color (series color) : Box border color. Default is color.blue
     bgcolor (series color) : box background color
     border_width (series int) : Box border width. Default is 1
     border_style (series string) : Box border style. Default is line.style_solid
     extend (series string) : Extend property of box. default is extend.none
     xloc (series string) : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
 BoxText 
  Box Text properties.
  Fields:
     boxText (series string) : Text to be printed on the box
     text_size (series string) : Text size. Default is size.auto
     text_color (series color) : Box text color. Default is color.yellow.
     text_halign (series string) : horizontal align style - default is text.align_center
     text_valign (series string) : vertical align style - default is text.align_center
     text_wrap (series string) : text wrap style - default is text.wrap_auto
     text_font_family (series string) : Text font. Default is
 Box 
  Box object
  Fields:
     p1 (chart.point) : Diagonal point one
     p2 (chart.point) : Diagonal point two
     properties (BoxProperties) : Box properties
     textProperties (BoxText) : Box text properties
     object (series box) : Box object created
 PolyLineProperties 
  Fields:
     curved (series bool) 
     closed (series bool) 
     xloc (series string) 
     lineColor (series color) 
     fillColor (series color) 
     lineStyle (series string) 
     lineWidth (series int) 
 PolyLine 
  Fields:
     points (array) 
     properties (PolyLineProperties) 
     object (series polyline)
1% Range Bars with Sequence TableOverall Logic :
The script is designed to help traders visualize and analyze price movements on the chart, where each 1% movement is highlighted with a corresponding symbol. Additionally, the table helps track and analyze the number and length of consecutive price movements in one direction, which can be useful for identifying trends and understanding market dynamics.
This script can be particularly useful for traders looking for recurring patterns in price movements and wanting to quickly identify significant changes on the chart.
 Main elements of the script :
Price Percentage Change:
The script tracks the price movement by 1% from the last significant value (the value at which the last 1% change was recorded).
If the price rises by 1% or more, a green circle is displayed above the bar.
If the price drops by 1% or more, a red circle is displayed below the bar.
Sequence Counting:
The script counts the number of consecutive 1% moves upwards (green circles) and downwards (red circles).
Separate counters are maintained for upward and downward movements, increasing each time the respective movement occurs.
If an opposite movement interrupts the sequence, the counter for the opposite direction is reset.
Sequence Table:
A table displayed on the chart shows the number of sequences of 1% movements in one direction for lengths from 1 to 15 bars.
The table is updated in real-time and shows how many times sequences of a certain length occurred on the chart, where the price moved by 1% in one direction.
VPSA - Volume Price Spread AnalysisDear Analysts and Traders,
I am pleased to present the latest version of my indicator, based on the logic of analyzing spread and volume. In this version, the indicator examines spread and volume using min-max normalization. The statistical value is captured through Z-Score standardization, and I have added configurable alerts based on the normalized values of spread, volume, and the sigmas for these variables.
 Theory and Evolution of the Indicator 
The normalization function used in this program allows for the comparison of two values with different ranges on a single chart. The values that reach the highest within the examined range are assigned a value of one. As in previous versions, I have adopted a bar chart where the wider bar represents volume and the narrower bar represents spread. I believe that using normalization is the most intuitive approach, as the standardization in the earlier sVPSA version could cause confusion. This was due to smaller bars for higher actual values and negative bars, which required additional reliance on actual volume data and significant proficiency in using the indicator. These were limitations stemming from the computational aspect of these issues. As in the previously mentioned script, I also used Z-Score standardization here, which serves as a measure of deviation from the mean. This is visualized in the script as the color of the bars, which in the default configuration are as follows: below one sigma - blue; above one sigma up to two sigmas - green; above two sigmas up to three sigmas - red; and above three sigmas - fuchsia. Additionally, I applied an exponential moving average in this indicator to minimize the influence of older candles on the mean. The indicator has been enhanced with configurable alerts, allowing for substantial control over the conditions triggering them. The alerts enable the definition of normalized variable values and sigma values. Furthermore, the program allows for the definition of logical dependencies for these conditions.
 Summary 
The program I have developed is a synthesis of the most important and useful functions from the indicators I previously created. The indicator is a standalone and powerful tool that facilitates effective analysis of the spread-volume relationship, which is one of the fundamental methods of analysis according to the Wyckoff and VSA methodologies. The alerts introduced in this version provide extensive possibilities for controlling the dynamics of any market.
Should you encounter any errors or have suggestions regarding the indicator, please feel free to contact me.
I wish you successful analyses! All the best!
CatTheTrader
Uptrick: Trend SMA Oscillator### In-Depth Analysis of the "Uptrick: Trend SMA Oscillator" Indicator
---
#### Introduction to the Indicator
The "Uptrick: Trend SMA Oscillator" is an advanced yet user-friendly technical analysis tool designed to help traders across all levels of experience identify and follow market trends with precision. This indicator builds upon the fundamental principles of the Simple Moving Average (SMA), a cornerstone of technical analysis, to deliver a clear, visually intuitive overlay on the price chart. Through its strategic use of color-coding and customizable parameters, the Uptrick: Trend SMA Oscillator provides traders with actionable insights into market dynamics, enhancing their ability to make informed trading decisions.
#### Core Concepts and Methodology
1. **Foundational Principle – Simple Moving Average (SMA):**
   - The Simple Moving Average (SMA) is the heart of the Uptrick: Trend SMA Oscillator. The SMA is a widely-used technical indicator that calculates the average price of an asset over a specified number of periods. By smoothing out price data, the SMA helps to reduce the noise from short-term fluctuations, providing a clearer picture of the overall trend.
   - In the Uptrick: Trend SMA Oscillator, two SMAs are employed:
     - **Primary SMA (oscValue):** This is applied to the closing price of the asset over a user-defined period (default is 14 periods). This SMA tracks the price closely and is sensitive to changes in market direction.
     - **Smoothing SMA (oscV):** This second SMA is applied to the primary SMA, further smoothing the data and helping to filter out minor price movements that might otherwise be mistaken for trend reversals. The default period for this smoothing is 50, but it can be adjusted to suit the trader's preference.
2. **Color-Coding for Trend Visualization:**
   - One of the most distinctive features of this indicator is its use of color to represent market trends. The indicator’s line changes color based on the relationship between the primary SMA and the smoothing SMA:
     - **Bullish (Green):** The line turns green when the primary SMA is equal to or greater than the smoothing SMA, indicating that the market is in an upward trend.
     - **Bearish (Red):** Conversely, the line turns red when the primary SMA falls below the smoothing SMA, signaling a downward trend.
   - This color-coded system provides traders with an immediate, easy-to-interpret visual cue about the market’s direction, allowing for quick decision-making.
#### Detailed Explanation of Inputs
1. **Bullish Color (Default: Green #00ff00):**
   - This input allows traders to customize the color that represents bullish trends on the chart. The default setting is green, a color commonly associated with upward market movement. However, traders can adjust this to any color that suits their visual preferences or matches their overall chart theme.
2. **Bearish Color (Default: Red RGB: 245, 0, 0):**
   - The bearish color input determines the color of the line when the market is trending downwards. The default setting is a vivid red, signaling caution or selling opportunities. Like the bullish color, this can be customized to fit the trader’s needs.
3. **Line Thickness (Default: 5):**
   - This setting controls the thickness of the line plotted by the indicator. The default thickness of 5 makes the line prominent on the chart, ensuring that the trend is easily visible even in complex or crowded chart setups. Traders can adjust the thickness to make the line thinner or thicker, depending on their visual preferences.
4. **Primary SMA Period (Value 1 - Default: 14):**
   - The primary SMA period defines how many periods (e.g., days, hours) are used to calculate the moving average based on the asset’s closing prices. The default period of 14 is a balanced setting that offers a good mix of responsiveness and stability, but traders can adjust this depending on their trading style:
     - **Shorter Periods (e.g., 5-10):** These make the indicator more sensitive, capturing trends more quickly but also increasing the likelihood of reacting to short-term price fluctuations or "noise."
     - **Longer Periods (e.g., 20-50):** These smooth the data more, providing a more stable trend line that is less prone to whipsaws but may be slower to respond to trend changes.
5. **Smoothing SMA Period (Value 2 - Default: 50):**
   - The smoothing SMA period determines how much the primary SMA is smoothed. A longer smoothing period results in a more gradual, stable line that focuses on the broader trend. The default of 50 is designed to smooth out most of the short-term fluctuations while still being responsive enough to detect significant trend shifts.
   - **Customization:**
     - **Shorter Smoothing Periods (e.g., 20-30):** Make the indicator more responsive, better for fast-moving markets or for traders who want to capture quick trends.
     - **Longer Smoothing Periods (e.g., 70-100):** Enhance stability, ideal for long-term traders looking to avoid reacting to minor price movements.
#### Unique Characteristics and Advantages
1. **Simplicity and Clarity:**
   - The Uptrick: Trend SMA Oscillator’s design prioritizes simplicity without sacrificing effectiveness. By relying on the widely understood SMA, it avoids the complexity of more esoteric indicators while still providing reliable trend signals. This simplicity makes it accessible to traders of all levels, from novices who are just learning about technical analysis to experienced traders looking for a straightforward, dependable tool.
2. **Visual Feedback Mechanism:**
   - The indicator’s use of color to signify market trends is a particularly powerful feature. This visual feedback mechanism allows traders to assess market conditions at a glance. The clarity of the green and red color scheme reduces the mental effort required to interpret the indicator, freeing the trader to focus on strategy execution.
3. **Adaptability Across Markets and Timeframes:**
   - One of the strengths of the Uptrick: Trend SMA Oscillator is its versatility. The basic principles of moving averages apply equally well across different asset classes and timeframes. Whether trading stocks, forex, commodities, or cryptocurrencies, traders can use this indicator to gain insights into market trends.
   - **Intraday Trading:** For day traders who operate on short timeframes (e.g., 1-minute, 5-minute charts), the oscillator can be adjusted to be more responsive, capturing quick shifts in momentum.
   - **Swing Trading:** Swing traders, who typically hold positions for several days to weeks, will find the default settings or slightly adjusted periods ideal for identifying and riding medium-term trends.
   - **Long-Term Trading:** Position traders and investors can adjust the indicator to focus on long-term trends by increasing the periods for both the primary and smoothing SMAs, filtering out minor fluctuations and highlighting sustained market movements.
4. **Minimal Lag:**
   - One of the challenges with moving averages is lag—the delay between when the price changes and when the indicator reflects this change. The Uptrick: Trend SMA Oscillator addresses this by allowing traders to adjust the periods to find a balance between responsiveness and stability. While all SMAs inherently have some lag, the customizable nature of this indicator helps traders mitigate this effect to align with their specific trading goals.
5. **Customizable and Intuitive:**
   - While many technical indicators come with a fixed set of parameters, the Uptrick: Trend SMA Oscillator is fully customizable, allowing traders to tailor it to their trading style, market conditions, and personal preferences. This makes it a highly flexible tool that can be adjusted as markets evolve or as a trader’s strategy changes over time.
#### Practical Applications for Different Trader Profiles
1. **Day Traders:**
   - **Use Case:** Day traders can customize the SMA periods to create a faster, more responsive indicator. This allows them to capture short-term trends and make quick decisions. For example, reducing the primary SMA to 5 and the smoothing SMA to 20 can help day traders react promptly to intraday price movements.
   - **Strategy Integration:** Day traders might use the Uptrick: Trend SMA Oscillator in conjunction with volume-based indicators to confirm the strength of a trend before entering or exiting trades.
2. **Swing Traders:**
   - **Use Case:** Swing traders can use the default settings or slightly adjust them to smooth out minor price fluctuations while still capturing medium-term trends. This approach helps in identifying the optimal points to enter or exit trades based on the broader market direction.
   - **Strategy Integration:** Swing traders can combine this indicator with oscillators like the Relative Strength Index (RSI) to confirm overbought or oversold conditions, thereby refining their entry and exit strategies.
3. **Position Traders:**
   - **Use Case:** Position traders, who hold trades for extended periods, can extend the SMA periods to focus on long-term trends. By doing so, they minimize the impact of short-term market noise and focus on the underlying trend.
   - **Strategy Integration:** Position traders might use the Uptrick: Trend SMA Oscillator in combination with fundamental analysis. The indicator can help confirm the timing of entries and exits based on broader economic or corporate developments.
4. **Algorithmic and Quantitative Traders:**
   - **Use Case:** The simplicity and clear logic of the Uptrick: Trend SMA Oscillator make it an excellent candidate for algorithmic trading strategies. Its binary output—bullish or bearish—can be easily coded into automated trading systems.
   - **Strategy Integration:** Quant traders might use the indicator as part of a larger trading system that incorporates multiple indicators and rules, optimizing the SMA periods based on historical backtesting to achieve the best results.
5. **Novice Traders:**
   - **Use Case:** Beginners can use the Uptrick: Trend SMA Oscillator to learn the basics of trend-following strategies.
 The visual simplicity of the color-coded line helps novice traders quickly understand market direction without the need to interpret complex data.
   - **Educational Value:** The indicator serves as an excellent starting point for those new to technical analysis, providing a practical example of how moving averages work in a real-world trading environment.
#### Combining the Indicator with Other Tools
1. **Relative Strength Index (RSI):**
   - The RSI is a momentum oscillator that measures the speed and change of price movements. When combined with the Uptrick: Trend SMA Oscillator, traders can look for instances where the RSI shows divergence from the price while the oscillator confirms the trend. This can be a powerful signal of an impending reversal or continuation.
2. **Moving Average Convergence Divergence (MACD):**
   - The MACD is another popular trend-following momentum indicator. By using it alongside the Uptrick: Trend SMA Oscillator, traders can confirm the strength of a trend and identify potential entry and exit points with greater confidence. For example, a bullish crossover on the MACD that coincides with the Uptrick: Trend SMA Oscillator turning green can be a strong buy signal.
3. **Volume Indicators:**
   - Volume is often considered the fuel behind price movements. Using volume indicators like the On-Balance Volume (OBV) or Volume Weighted Average Price (VWAP) in conjunction with the Uptrick: Trend SMA Oscillator can help traders confirm the validity of a trend. A trend identified by the oscillator that is supported by increasing volume is typically more reliable.
4. **Fibonacci Retracement:**
   - Fibonacci retracement levels are used to identify potential reversal levels in a trending market. When the Uptrick: Trend SMA Oscillator indicates a trend, traders can use Fibonacci retracement levels to find potential entry points that align with the broader trend direction.
#### Implementation in Different Market Conditions
1. **Trending Markets:**
   - The Uptrick: Trend SMA Oscillator excels in trending markets, where it provides clear signals on the direction of the trend. In a strong uptrend, the line will remain green, helping traders stay in the trade for longer periods. In a downtrend, the red line will signal the continuation of bearish conditions, prompting traders to stay short or avoid long positions.
2. **Sideways or Range-Bound Markets:**
   - In range-bound markets, where price oscillates within a confined range without a clear trend, the Uptrick: Trend SMA Oscillator may produce more frequent changes in color. While this could indicate potential reversals at the range boundaries, traders should be cautious of false signals. It may be beneficial to pair the oscillator with a volatility indicator to better navigate such conditions.
3. **Volatile Markets:**
   - In highly volatile markets, where prices can swing rapidly, the sensitivity of the Uptrick: Trend SMA Oscillator can be adjusted by modifying the SMA periods. A shorter SMA period might capture quick trends, but traders should be aware of the increased risk of whipsaws. Combining the oscillator with a volatility filter or using it in a higher time frame might help mitigate some of this risk.
#### Final Thoughts
The "Uptrick: Trend SMA Oscillator" is a versatile, easy-to-use indicator that stands out for its simplicity, visual clarity, and adaptability. It provides traders with a straightforward method to identify and follow market trends, using the well-established concept of moving averages. The indicator’s customizable nature makes it suitable for a wide range of trading styles, from day trading to long-term investing, and across various asset classes.
By offering immediate visual feedback through color-coded signals, the Uptrick: Trend SMA Oscillator simplifies the decision-making process, allowing traders to focus on execution rather than interpretation. Whether used on its own or as part of a broader technical analysis toolkit, this indicator has the potential to enhance trading strategies and improve overall performance.
Its accessibility and ease of use make it particularly appealing to novice traders, while its adaptability and reliability ensure that it remains a valuable tool for more experienced market participants. As markets continue to evolve, the Uptrick: Trend SMA Oscillator remains a timeless tool, rooted in the fundamental principles of technical analysis, yet flexible enough to meet the demands of modern trading.
Uptrick: FVG Market Zones**Uptrick: FVG Market Zones**
---
### Introduction
**Uptrick: FVG Market Zones** is a cutting-edge technical analysis tool designed to identify and visualize Fair Value Gaps (FVGs) within financial markets. This indicator focuses on pinpointing critical price levels where significant gaps occur, which can act as potential support and resistance zones. By integrating advanced volatility analysis and user-configurable parameters, the **Uptrick: FVG Market Zones** provides traders with a robust framework for understanding market dynamics and making informed trading decisions.
### Purpose and Functionality
The primary purpose of the **Uptrick: FVG Market Zones** indicator is to detect and highlight Fair Value Gaps, which are areas on a price chart where there is a significant price movement without any trading activity in between. These gaps can provide critical insights into market behavior, as they often indicate areas where the market has not fully accounted for the supply and demand dynamics. Traders use these zones to anticipate potential reversals, breakouts, or consolidations, making this tool highly valuable for both short-term and long-term trading strategies.
### Unique Features and Originality
The **Uptrick: FVG Market Zones** indicator is distinguished by its focus on FVGs and its ability to integrate this concept into a broader market analysis framework. Unlike other indicators that may offer generalized support and resistance levels, this tool specifically identifies and visualizes gaps based on volatility-adjusted criteria. This precision allows traders to focus on the most relevant market zones, improving their ability to anticipate market movements.
One of the standout features of this indicator is its user-configurable settings, which provide a high degree of customization. This flexibility ensures that traders can tailor the indicator to suit their specific trading style and the particular market they are analyzing. Additionally, the indicator's visualization capabilities are enhanced with customizable colors and gap-filling options, making it easier for traders to interpret and act on the information presented.
### Inputs and Configurations
**Uptrick: FVG Market Zones** comes with several user inputs that allow traders to customize the indicator's behavior and appearance. Each input plays a crucial role in determining how the indicator identifies and visualizes FVGs on the chart. Here’s a detailed breakdown of each input:
1. **FVG Analysis Period (fvgPeriod):**
   - **Description:** This input determines the period over which the indicator analyzes the chart for identifying FVGs. By adjusting this value, traders can control how far back in time the indicator looks to detect significant gaps.
   - **Default Value:** 25
   - **Purpose:** A shorter period may focus on more recent market activity, making the indicator more sensitive to recent price movements. In contrast, a longer period allows the indicator to identify gaps that have remained unfilled for an extended time, potentially acting as stronger support or resistance levels.
2. **Analysis Mode (mode):**
   - **Description:** The Analysis Mode input allows traders to choose between different methods of analyzing the chart for FVGs.
   - **Options:** "Recent Gaps" and "Extended View"
   - **Default Option:** "Recent Gaps"
   - **Purpose:** 
     - **Recent Gaps:** Focuses on the latest significant gaps, providing traders with up-to-date information on the most relevant market zones.
     - **Extended View:** Considers a broader range of gap patterns, which can be useful in markets where historical gaps may still influence current price action.
  
3. **Volatility Sensitivity (volatilityFactor):**
   - **Description:** This input adjusts the sensitivity of the indicator to market volatility. It is used in calculating the threshold for identifying FVGs.
   - **Default Value:** 0.3
   - **Step Size:** 0.1
   - **Purpose:** A higher sensitivity will cause the indicator to detect smaller gaps, which might be more frequent but less significant. Lower sensitivity focuses on larger, more impactful gaps, which are less frequent but potentially more powerful in predicting market behavior.
4. **Highlight Market Gaps (showGaps):**
   - **Description:** A boolean input that determines whether the identified FVGs should be highlighted on the chart.
   - **Default Value:** True
   - **Purpose:** This input allows traders to toggle the visualization of FVGs. When enabled, the indicator highlights gaps using colored boxes, making them visually prominent on the chart.
5. **Bullish Highlight Color (bullColor):**
   - **Description:** Sets the color used to highlight bullish FVGs (gaps that may indicate support).
   - **Default Value:** #00FF7F (a shade of green)
   - **Purpose:** The color choice is crucial for quickly distinguishing bullish zones from bearish ones. Green is typically associated with upward price movement, making it intuitive for traders to identify potential support areas.
6. **Bearish Highlight Color (bearColor):**
   - **Description:** Sets the color used to highlight bearish FVGs (gaps that may indicate resistance).
   - **Default Value:** #FF4500 (a shade of red)
   - **Purpose:** Red is commonly associated with downward price movement, making it easy for traders to identify potential resistance areas. This color coding helps in quickly assessing the chart.
7. **Fill Gap Areas (fillGaps):**
   - **Description:** A boolean input that determines whether the FVGs should be filled with a color on the chart.
   - **Default Value:** True
   - **Purpose:** Filling the gap areas provides a more solid visual cue for traders. It enhances the visibility of the gaps, making it easier to spot these zones during fast-paced trading sessions.
8. **Hidden Color (hidden):**
   - **Description:** A color input that is used when certain elements should be hidden from the chart.
   - **Default Value:** color.rgb(0,0,0,100) (a semi-transparent black)
   - **Purpose:** This input is useful for controlling the visibility of certain plots or elements on the chart, ensuring that the indicator remains clean and uncluttered.
### Market Gap Detection
The core functionality of the **Uptrick: FVG Market Zones** indicator lies in its ability to detect Fair Value Gaps. These gaps occur when the price makes a significant jump from one level to another without any trading activity in between. The indicator uses a combination of price action analysis and volatility thresholds to identify these gaps.
- **Volatility Measurement:** The indicator begins by measuring market volatility using the Average True Range (ATR). This volatility measurement is then adjusted by the user-defined sensitivity factor, which determines the threshold for identifying significant gaps.
- **Gap Identification:** The indicator checks for instances where the current low is higher than the high two bars ago (bullish gap) or where the current high is lower than the low two bars ago (bearish gap). These conditions signify a potential FVG.
- **Gap Storage and Management:** Once a gap is identified, it is stored in an array. The indicator also manages the size of these arrays based on the selected analysis mode, ensuring that only the most relevant gaps are considered in the analysis.
### Visualization
Visualization is a key component of the **Uptrick: FVG Market Zones** indicator. By providing clear and customizable visual cues, the indicator ensures that traders can quickly and easily interpret the information it provides.
- **Gap Highlighting:** When enabled, the indicator highlights the identified FVGs on the chart using colored boxes. Bullish gaps are highlighted in green, while bearish gaps are highlighted in red. This color coding helps traders instantly recognize potential support and resistance zones.
- **Gap Filling:** The indicator can also fill the identified gaps with a semi-transparent color. This option enhances the visibility of the gaps, making them more prominent on the chart. Filled gaps are particularly useful for traders who want to keep track of these zones over multiple trading sessions.
- **Gap Averages:** The indicator calculates the average level of the identified gaps and plots these averages as lines on the chart. These lines represent the general area of support or resistance based on the detected gaps, providing traders with a reference point for setting their stop losses or profit targets.
- **Text Labels:** The indicator also labels each FVG with the text "FVG" inside the highlighted area. This feature ensures that traders can easily identify these zones even in charts with dense price action.
### Practical Applications
The **Uptrick: FVG Market Zones** indicator is versatile and can be applied to a wide range of trading strategies across different markets and timeframes. Here are a few examples of how this indicator can be used in practice:
1. **Support and Resistance Trading:**
   - Traders can use the identified FVGs as dynamic support and resistance levels. By placing their trades based on these levels, they can take advantage of potential reversals or continuations at key market zones.
2. **Gap Filling Strategy:**
   - Some traders focus on the concept of gap filling, where the market eventually returns to "fill" the gap created by rapid price movements. The **Uptrick: FVG Market Zones** indicator can
 help identify such gaps and anticipate when the market might return to these levels.
3. **Breakout Trading:**
   - The indicator can be used to identify breakouts from significant gaps. When the price moves beyond the identified FVGs, it may signal a strong trend continuation, providing an opportunity for breakout traders.
4. **Reversal Trading:**
   - By monitoring the signals generated by the indicator, traders can identify potential market reversals. A sell signal after a prolonged uptrend or a buy signal after a downtrend may indicate a reversal, allowing traders to position themselves accordingly.
5. **Risk Management:**
   - The average levels of the FVGs can be used to set stop-loss and take-profit levels. By aligning these levels with the FVG zones, traders can improve their risk management practices and enhance their trading discipline.
### Customization and Flexibility
One of the standout features of the **Uptrick: FVG Market Zones** indicator is its high level of customization. Traders can adjust various parameters to tailor the indicator to their specific needs and preferences.
- **Customizable Colors:** The indicator allows traders to choose their preferred colors for highlighting bullish and bearish gaps. This flexibility ensures that the indicator can be integrated seamlessly into any trading setup, regardless of the trader's color scheme preferences.
- **Adjustable Periods and Sensitivity:** By allowing traders to adjust the analysis period and volatility sensitivity, the indicator can be fine-tuned to suit different market conditions. For example, a trader might use a shorter analysis period and higher sensitivity in a volatile market, while opting for a longer period and lower sensitivity in a more stable market.
- **Toggling Visual Elements:** Traders can choose to enable or disable various visual elements of the indicator, such as gap highlighting, gap filling, and text labels. This level of control allows traders to declutter their charts and focus on the information that is most relevant to their trading strategy.
### Advantages and Benefits
The **Uptrick: FVG Market Zones** indicator offers several key advantages that make it a valuable tool for traders:
1. **Precision:** By focusing on Fair Value Gaps, the indicator provides highly precise levels of support and resistance, which are often more reliable than traditional horizontal levels.
2. **Clarity:** The clear visual representation of FVGs, along with the text labels and color coding, ensures that traders can quickly interpret the indicator's signals and incorporate them into their trading decisions.
3. **Adaptability:** The indicator's customizable settings allow it to be adapted to different markets, timeframes, and trading styles. Whether you are a day trader, swing trader, or long-term investor, this indicator can be tailored to meet your needs.
4. **Enhanced Decision-Making:** The trading signals generated by the indicator provide actionable insights that can help traders make more informed decisions. By aligning their trades with the identified FVG zones, traders can improve their chances of success.
5. **Risk Management:** The use of FVG zones as reference points for stop-loss and take-profit levels enhances risk management practices, helping traders protect their capital while maximizing their profit potential.
### Conclusion
The **Uptrick: FVG Market Zones** indicator is a powerful and versatile tool for traders seeking to enhance their market analysis and improve their trading outcomes. By focusing on Fair Value Gaps and providing a high level of customization, this indicator offers a unique blend of precision, clarity, and adaptability. Whether you are looking to identify key market zones, generate trading signals, or improve your risk management practices, the **Uptrick: FVG Market Zones** indicator is a valuable addition to any trader's toolkit.
With its innovative approach to market analysis and user-friendly design, **Uptrick: FVG Market Zones** stands out as an essential tool for traders who want to stay ahead of the market and make more informed trading decisions. Whether you are trading stocks, forex, commodities, or cryptocurrencies, this indicator provides the insights you need to navigate the markets with confidence and success.






















