Normalized ZScoreThe Normalized ZScore Indicator is a dynamic tool designed to help traders identify potential overbought and oversold conditions in the market. It calculates the ZScore of the price movement relative to a moving average, allowing users to track the deviation of price from its average and normalize it within a fixed range for clearer signal generation. The indicator can be used for both trend-following and mean-reversion strategies, offering customizable options for various trading styles.
How It Works
This indicator works by calculating two distinct ZScores:
Standard ZScore: Based on the price deviation from a simple moving average (SMA).
Fast ZScore: Calculated using price deviation from the SMA combined with standard deviation over a shorter period.
The ZScore values are normalized between -100 and 100, allowing for consistent and comparable signal outputs across different assets and timeframes.
Key Features
Customizable MA and Deviation Lengths: Adjust the length of the moving average (MA Length) and deviation (Deviation Length) to suit your trading needs.
Overbought/Oversold Zones: The indicator highlights areas where the market may be overbought or oversold using a user-defined threshold.
Color-Coded Signals: The ZScore plot changes color based on market conditions:
Positive ZScore (overbought) = Customizable Positive Color
Neutral ZScore = Customizable Middle Color
Negative ZScore (oversold) = Customizable Negative Color
Trend Filtering Option: The built-in trend filter helps to enhance signal accuracy by factoring in the overall market trend.
Signal Shapes:
Diamonds: Indicate strong long or short entry signals when ZScore crosses predefined thresholds.
X-Crosses: Indicate weaker long or short entry signals for users preferring caution in their trades.
Inputs
MA Length: Set the length of the moving average used for calculating the ZScore.
Deviation Length: Set the length used for deviation calculations.
OBS Threshold: Set the threshold for defining overbought and oversold zones.
Trend Filter: Enable or disable the trend filter for added signal confidence.
Color Settings: Customize the colors for positive, middle, and negative ZScore values.
Visual Features
ZScore Plot: A smooth and color-coded line plot to visualize the ZScore in real-time.
Overbought/Oversold Zones: Visualized with horizontal lines and fill colors to highlight extremes.
Bar Coloring: Bars change colors when ZScore exceeds overbought/oversold zones, enhancing visual clarity.
Signal Markers: Diamond or X-shaped markers appear on the chart to indicate potential trade signals.
How to Use
Entry Points: Look for the ZScore to cross into overbought/oversold regions for potential reversal trades. Use the diamonds and X-crosses for long and short entries.
Trend Filter: Enable the trend filter to avoid taking trades against the overall market trend.
Customize Settings: Adjust the lengths and colors to match your specific trading strategy and timeframe.
インジケーターとストラテジー
Smartos VWAPSmartos VWAP Indicator Description
Smartos VWAP is a versatile and customizable technical analysis tool designed for traders and analysts to gauge the average price of a security based on its trading volume. The indicator calculates the Volume Weighted Average Price (VWAP) over six different customizable periods, allowing users to adapt the analysis to their trading strategies.
Key Features:
Volume Weighted Average Price (VWAP): The Smartos VWAP provides a dynamic measure of the average price at which a security has traded throughout the day, weighted by volume. This makes it a useful reference point for assessing price levels.
Customizable Periods: The indicator allows users to set six different candle lengths for VWAP calculations, with default values of 21, 48, 84, 175, 480, and 840 candles. Users can easily modify these values to suit their trading preferences.
Multiple VWAP Lines: The indicator plots six distinct VWAP lines on the chart, each representing a different period. This enables traders to observe price action relative to multiple VWAPs, helping identify trends and potential support and resistance levels.
Visual Clarity: Each VWAP line is color-coded for easy differentiation, making it simple for traders to analyze price movements and the relationship between the current price and the average price over the selected periods.
Usage:
Traders can use the Smartos VWAP indicator to make informed decisions regarding entry and exit points, as well as to assess overall market sentiment. By observing the position of the price relative to the VWAP lines, traders can gain insights into potential bullish or bearish trends.
Volumatic Variable Index Dynamic Average [BigBeluga]The Volumatic VIDYA (Variable Index Dynamic Average) indicator is a trend-following tool that calculates and visualizes both the current trend and the corresponding buy and sell pressure within each trend phase. Using the Variable Index Dynamic Average as the core smoothing technique, this indicator also plots volume levels of lows and highs based on market structure pivot points, providing traders with key insights into price and volume dynamics.
Additionally, it generates delta volume values to help traders evaluate buy-sell pressure balance during each trend, making it a powerful tool for understanding market sentiment shifts.
BTC:
TSLA:
🔵 IDEA
The Volumatic VIDYA indicator's core idea is to provide a dynamic, adaptive smoothing tool that identifies trends while simultaneously calculating the volume pressure behind them. The VIDYA line, based on the Variable Index Dynamic Average, adjusts according to the strength of the price movements, offering a more adaptive response to the market compared to standard moving averages.
By calculating and displaying the buy and sell volume pressure throughout each trend, the indicator provides traders with key insights into market participation. The horizontal lines drawn from the highs and lows of market structure pivots give additional clarity on support and resistance levels, backed by average volume at these points. This dual analysis of trend and volume allows traders to evaluate the strength and potential of market movements more effectively.
🔵 KEY FEATURES & USAGE
VIDYA Calculation:
The Variable Index Dynamic Average (VIDYA) is a special type of moving average that adjusts dynamically to the market’s volatility and momentum. Unlike traditional moving averages that use fixed periods, VIDYA adjusts its smoothing factor based on the relative strength of the price movements, using the Chande Momentum Oscillator (CMO) to capture the magnitude of price changes. When momentum is strong, VIDYA adapts and smooths out price movements quicker, making it more responsive to rapid price changes. This makes VIDYA more adaptable to volatile markets compared to traditional moving averages such as the Simple Moving Average (SMA) or the Exponential Moving Average (EMA), which are less flexible.
// VIDYA (Variable Index Dynamic Average) function
vidya_calc(src, vidya_length, vidya_momentum) =>
float momentum = ta.change(src)
float sum_pos_momentum = math.sum((momentum >= 0) ? momentum : 0.0, vidya_momentum)
float sum_neg_momentum = math.sum((momentum >= 0) ? 0.0 : -momentum, vidya_momentum)
float abs_cmo = math.abs(100 * (sum_pos_momentum - sum_neg_momentum) / (sum_pos_momentum + sum_neg_momentum))
float alpha = 2 / (vidya_length + 1)
var float vidya_value = 0.0
vidya_value := alpha * abs_cmo / 100 * src + (1 - alpha * abs_cmo / 100) * nz(vidya_value )
ta.sma(vidya_value, 15)
When momentum is strong, VIDYA adapts and smooths out price movements quicker, making it more responsive to rapid price changes. This makes VIDYA more adaptable to volatile markets compared to traditional moving averages
Triangle Trend Shift Signals:
The indicator marks trend shifts with up and down triangles, signaling a potential change in direction. These signals appear when the price crosses above a VIDYA during an uptrend or crosses below during a downtrend.
Volume Pressure Calculation:
The Volumatic VIDYA tracks the buy and sell pressure during each trend, calculating the cumulative volume for up and down bars. Positive delta volume occurs during uptrends due to higher buy pressure, while negative delta volume reflects higher sell pressure during downtrends. The delta is displayed in real-time on the chart, offering a quick view of volume imbalances.
Market Structure Pivot Lines with Volume Labels:
The indicator draws horizontal lines based on market structure pivots, which are calculated using the highs and lows of price action. These lines are extended on the chart until price crosses them. The indicator also plots the average volume over a 6-bar range to provide a clearer understanding of volume dynamics at critical points.
🔵 CUSTOMIZATION
VIDYA Length & Momentum: Control the sensitivity of the VIDYA line by adjusting the length and momentum settings, allowing traders to customize the smoothing effect to match their trading style.
Volume Pivot Detection: Set the number of bars to consider for identifying pivots, which influences the calculation of the average volume at key levels.
Band Distance: Adjust the band distance multiplier for controlling how far the upper and lower bands extend from the VIDYA line, based on the ATR (Average True Range).
ICT CheckListCredit to the owner of this script "TalesOfTrader"
The Awakening Checklist indicator is a tool designed to help traders evaluate certain key market conditions and elements before making trading decisions. It consists of a series of questions that the trader must answer using the options "Yes", "No" or "N/A" (not applicable).
“Has Asia Session ended?” : This question aims to determine if the Asian trading session has ended. The answer to this question can influence trading strategies depending on market conditions.
“Have you identified potential medium induction?” : This question concerns the identification of potential average inductions on the market. Recognizing these inductions can help traders anticipate future price movements.
"Have you identified potential PoI's": This question asks about the identification of potential points of interest on the market. These points of interest can indicate areas of significant support or resistance.
"Have you identified in which direction they are creating lQ?" : This question aims to determine in which direction market participants create liquidity (lQ). Understanding this dynamic can help make informed trade decisions.
“Have they induced Asia Range”: This question concerns the induction of the Asian range by market participants. Recognizing this induction can be important in assessing future price movements.
“Have you had a medium induction”: This question asks about the presence of a medium induction on the market. The answer to this question can influence trading prospects.
“Do you have a BoS away from the induction”: This question aims to find out if the trader has an offer (BoS) far from the identified induction. This can be a risk management strategy.
"Doas your induction PoI have imbalance": This question concerns the imbalance of points of interest (PoI) linked to induction. Recognizing this imbalance can help anticipate price movements.
“Do you have a valid target in mind”: This question aims to find out if the trader has a clear trading objective in mind. Having a goal can help guide trading decisions and manage risk.
RSI Crossover Strategy with Compounding (Monthly)Explanation of the Code:
Initial Setup:
The strategy initializes with a capital of 100,000.
Variables track the capital and the amount invested in the current trade.
RSI Calculation:
The RSI and its SMA are calculated on the monthly timeframe using request.security().
Entry and Exit Conditions:
Entry: A long position is initiated when the RSI is above its SMA and there’s no existing position. The quantity is based on available capital.
Exit: The position is closed when the RSI falls below its SMA. The capital is updated based on the net profit from the trade.
Capital Management:
After closing a trade, the capital is updated with the net profit plus the initial investment.
Plotting:
The RSI and its SMA are plotted for visualization on the chart.
A label displays the current capital.
Notes:
Test the strategy on different instruments and historical data to see how it performs.
Adjust parameters as needed for your specific trading preferences.
This script is a basic framework, and you might want to enhance it with risk management, stop-loss, or take-profit features as per your trading strategy.
Feel free to modify it further based on your needs!
Cumulative Volume Delta with VWAP-based Buy/Sell AlertsDescription:
This script combines Cumulative Volume Delta (CVD) with Volume Weighted Average Price (VWAP) to generate buy and sell signals. It plots both the cumulative volume delta and its moving average on the chart, but the actual buy and sell signals are now based on the crossover and crossunder of the price with the VWAP, a popular tool for tracking price relative to the volume-weighted average over time.
Features:
Cumulative Volume Delta (CVD) Plot:
CVD helps visualize the net buying or selling pressure by accumulating volume when the price is rising and subtracting it when the price is falling. The cumulative volume is plotted on the chart as a blue line.
Moving Average of CVD:
A simple moving average (SMA) of the cumulative volume delta is plotted in orange to smooth out fluctuations and help detect the trend of volume flow.
VWAP Calculation:
VWAP (Volume Weighted Average Price) is a standard benchmark widely used in trading. It gives insight into whether the price is trading above or below the average price at which most of the volume has traded, weighted by volume. The VWAP is plotted as a purple line on the chart.
Buy/Sell Signals Based on VWAP:
Buy Signal: Triggered when the price crosses above the VWAP, indicating potential upward momentum.
Sell Signal: Triggered when the price crosses below the VWAP, signaling potential downward momentum.
These signals are displayed on the chart with clear labels:
Buy Signal: A green upward label appears below the price.
Sell Signal: A red downward label appears above the price.
Alerts for Buy/Sell Conditions:
Alerts are built into the script, so traders can receive notifications when the following conditions are met:
Buy Alert: The price crosses above the VWAP.
Sell Alert: The price crosses below the VWAP.
Use Case:
This script is useful for traders looking to incorporate both volume-based indicators and the VWAP into their trading strategy. The combination of CVD and VWAP provides a more comprehensive view of both price and volume dynamics:
VWAP helps traders understand whether the price is trading above or below its volume-weighted average.
CVD highlights buying or selling pressure through cumulative volume analysis.
Customization:
Anchor Periods: The user can customize the anchor period to suit different timeframes and trading styles.
Custom Alerts: The alert conditions can be easily modified to integrate into any trader’s strategy.
This script can be adapted for both short-term and long-term trading strategies and is especially useful in high-volume markets.
How to Use:
Add the script to your TradingView chart.
Customize the timeframe and anchor period, if needed, to match your preferred trading style.
Watch for Buy/Sell signals based on price crossing the VWAP.
Set up alerts to receive notifications when Buy or Sell signals are triggered.
This script is designed to help traders make informed decisions based on both price action relative to volume and Cumulative Delta volume trends, giving a more comprehensive view of the market dynamics.
Leading Indicator by Parag RautBreakdown of the Leading Indicator:
Linear Regression (LRC):
A linear regression line is used to estimate the current trend direction. When the price is above or below the regression line, it indicates whether the price is deviating from its mean, signaling potential reversals.
Rate of Change (ROC):
ROC measures the momentum of the price over a set period. By using thresholds (positive or negative), we predict that the price will continue in the same direction if momentum is strong enough.
Leading Indicator Calculation:
We calculate the difference between the price and the linear regression line. This is normalized using the standard deviation of price over the same period, giving us a leading signal based on price divergence from the mean trend.
The leading indicator is used to forecast changes in price behavior by identifying when the price is either stretched too far from the mean (indicating a potential reversal) or showing strong momentum in a particular direction (predicting trend continuation).
Buy and Sell Signals:
Buy Signal: Generated when ROC is above a threshold and the leading indicator shows the price is above the regression line.
Sell Signal: Generated when ROC is below a negative threshold and the leading indicator shows the price is below the regression line.
Visual Representation:
The indicator oscillates around zero. Values above zero signal potential upward price movements, while values below zero signal potential downward movements.
Background colors highlight potential buy (green) and sell (red) areas based on our conditions.
How It Works as a Leading Indicator:
This indicator attempts to predict price movements before they happen by combining the trend (via linear regression) and momentum (via ROC).
When the price significantly diverges from the trendline and momentum supports a continuation, it signals a potential entry point (either buy or sell).
It is leading in that it anticipates price movement before it becomes fully apparent in the market.
Next Steps:
You can adjust the length of the linear regression and ROC to fine-tune the indicator’s sensitivity to your trading style.
This can be combined with other indicators or used as part of a larger strategy
Volume CalendarDescription:
The indicator displays a calendar with Volume data for up to 6 last months. It is designed to work on any timeframe, but works best on Daily and below. It is also consistent in that it displays the same data even if you go to lower timeframes like 5 minutes (even though the data is used is Daily).
Features:
- displays volume data for last N months (volume, volume change, % of weekly, monthly and yearly volume)
- display total volume for each month
- display monthly sentiment
- find dates with volume spikes
Inputs:
- Number of months -> how many last months of data to display (from 1 to 6)
- Volume Type -> display only Bullish, only Bearish or all volume
- Cell color is based on -> Volume - the brighter the cell the higher volume was on that day; Volume Change - the brighter the cell the higher was the volume change that day; Volume Spike - the brighter the cell the higher was volume spike that day (volume spike is based on volume being above its average over last N candles)
- Cell color timeframe -> Weekly - the cell color is calculated comparing volume of that cell with weekly volume; Monthly - comparing volume with monthly volume
- Use volume for sentiment -> take the volume into account when calculating monthly sentiment (otherwise calculate it based on number of Bullish and Bearish days in the month)
- Spike Average Period -> period of the moving average used for spike calculation
- Spike Threshold -> current volume must be this many times greater than the average for it to be considered a spike
- Table Size -> size of the table
- Theme -> colouring of the table
Stronger Buy/Sell Signals This custom Pine Script indicator is designed to detect strong buy and sell signals based on price action trends and momentum, with an emphasis on using two simple moving averages (SMAs) for trend identification and RSI (Relative Strength Index) impulses for additional confirmation. The script is optimized to ensure that signals are not triggered too frequently, only highlighting strong trend-based opportunities. Additionally, the script is built as an overlay to keep the chart clean and prevent any visual shrinking caused by extra indicators.
Key Features
1. Moving Averages (SMAs):
- 11-period SMA (short-term trend): This moving average is used to track short-term price movement and serves as the primary trend filter.
- 50-period SMA (medium-term trend): This moving average is used to track the medium-term price trend, providing additional confirmation for trend direction.
The price must be above both SMAs for a buy signal or below both SMAs for a sell signal, ensuring that signals are only triggered in well-defined trends.
2. RSI Momentum Confirmation:
- Although the RSI is not displayed on the chart, it plays a critical role in filtering the signals.
- The RSI is calculated using the standard 14-period formula, and an additional condition requires that the RSI must show an upward or downward momentum (impulse) for buy or sell signals, respectively.
- The RSI impulse is measured by comparing the RSI value to its 5-period moving average:
- Upward impulse for a buy signal.
- Downward impulse for a sell signal.
3. Buy Signal:
- A strong buy signal is triggered when:
- The price is above both the 11-period and 50-period SMAs (confirming a bullish trend).
- The RSI is showing upward momentum, implying growing buying pressure.
- When both of these conditions are met, a green "Strong Buy" label will appear below the price bars, indicating a strong buying opportunity.
4. Sell Signal:
- A strong sell signal is triggered when:
- The price is below both the 11-period and 50-period SMAs (confirming a bearish trend).
- The RSI is showing downward momentum, implying growing selling pressure.
- When both of these conditions are met, a red "Strong Sell" label will appear above the price bars, indicating a strong selling opportunity.
5. No RSI Display:
- While the RSI is used for internal signal filtering, it is not displayed on the chart. This decision ensures that the chart remains uncluttered, with only the important buy/sell signals and moving averages visible.
6. Overlay-Only Indicator:
- This script is designed as an overlay indicator, meaning it plots directly on the price chart without adding additional panes. This helps the chart maintain its size and avoids shrinking the view.
---
Use Case
This indicator is ideal for traders who want to:
- Focus on strong, trend-confirming signals while avoiding noise from weaker setups.
- Trade in alignment with the trend , as defined by both short-term (11-SMA) and medium-term (50-SMA) price action.
- Filter signals based on momentum without cluttering their charts with additional indicators.
Customization Options
- SMA Periods : You can adjust the periods for the 11-SMA and 50-SMA depending on your preferred timeframe and trading strategy.
- RSI Conditions : If you want to add or remove sensitivity from the buy and sell signals, you can modify the RSI impulse logic to adjust the thresholds for what qualifies as an upward or downward impulse.
---
Conclusion
The "Stronger Buy/Sell Signals" Pine Script is a powerful trend-following tool that uses a combination of moving averages and RSI momentum to generate reliable trading signals. The indicator is designed to help traders stay in strong trends, while filtering out weaker signals that don't meet strict criteria. By not displaying the RSI directly and keeping the chart focused on key signals, this script maintains a clean and functional trading setup.
This indicator is best used by traders who prefer clear visual guidance for buying and selling opportunities, especially in trending markets.
---
Feel free to adjust the parameters to suit your specific trading style! Let me know if you'd like any additional features or modifications.
Advanced BB Bands with PlotThis code implements an advanced version of Bollinger Bands with additional moving averages, ATR-based bands, step lines, market direction indicators, and real-time data display. Here’s a breakdown of the functionality:
1. Inputs and Parameters:
length: The base period used for calculating the moving averages and the typical price.
atr_length: The length used for calculating the Average True Range (ATR).
step_length: The period for calculating step lines (highest high and lowest low over a given period).
2. Core Calculations:
Typical Price: (high + low + close) / 3 is the base for the moving averages.
ATR: ta.atr(atr_length) is used to create dynamic bands around the moving averages.
PL Dot: An average of the typical prices from the current and past two bars. This provides a short-term trend indicator.
3. Multiple Moving Averages (MAs):
Three simple moving averages (ma1, ma2, ma3) are calculated using different multiples of the base length. These help indicate short-, mid-, and long-term trends.
4. Step Lines:
Step Up: Highest close over the step_length.
Step Down: Lowest close over the step_length. These act as short-term support and resistance levels.
5. Outer Bands:
Upper Band: ma1 + 2 * ATR, an upper boundary based on ATR volatility.
Lower Band: ma1 - 2 * ATR, a lower boundary. Together, these form a dynamic range around the short-term moving average.
6. Market Direction:
Bullish or Bearish condition is determined by comparing ma1 and ma2. If ma1 is above ma2, the market is bullish; otherwise, it's bearish. This decision is displayed on the TradingView chart using a table.
7. Visual Elements:
Moving Averages (ma1, ma2, ma3): Plotted in different colors (blue, purple, white) to indicate different timeframes.
PL Dot: A step line plot for the PL Dot, which helps in spotting short-term trends.
Step Lines: Step-up and step-down levels plotted in lime and red, respectively.
Outer Bands: Upper and lower ATR-based bands plotted in aqua, with a filled region between the bands for easy visualization of price volatility.
Candlestick Coloring: Green bars for bullish and red for bearish price action.
8. Real-Time Board Display:
A table is created in the top-right corner of the chart to display:
The current closing price.
The market direction ("Bullish" or "Bearish").
The PL Dot value. The table updates on the most recent bar (barstate.islast).
9. Dynamic Labels:
On the most recent bar, labels are added dynamically to the upper and lower bands and the ma1. These labels help in identifying the values of key indicators directly on the chart.
10. Signals and Alerts:
Bullish and Bearish Cross: Visual signals are plotted on the chart when ma1 crosses above or below ma2. These are represented as up and down triangles, providing potential buy/sell signals.
Key Features Summarized:
Multi-Timeframe Moving Averages: 3 MAs based on different timeframes.
Dynamic ATR Bands: ATR-based upper and lower boundaries for volatility measurement.
Step Lines: Short-term high and low lines for support/resistance.
PL Dot: A short-term trend identifier.
Real-Time Dashboard: Live updates of price, trend, and PL Dot on the chart.
Visual Alerts: Dynamic labeling and crossover signals to assist in decision-making.
This script is designed for traders who want to track price movement within bands, evaluate trends across multiple timeframes, and visualize short-term market direction with dynamic alerts.
TimeLibraryLibrary "TimeLibrary"
TODO: add library description here
Line_Type_Control(Type)
Line_Type_Control: This function changes between common line types options available are "Solid","Dashed","Dotted"
Parameters:
Type (string) : : The string to choose the line type from
Returns: Line_Type : returns the pine script equivalent of the string input
Text_Size_Switch(Text_Size)
Text_Size_Switch : This function changes between common text sizes options are "Normal", "Tiny", "Small", "Large", "Huge", "Auto"
Parameters:
Text_Size (string) : : The string to choose the text type from
Returns: Text_Type : returns the pine script equivalent of the string input
TF(TF_Period, TF_Multip)
TF generates a string representation of a time frame based on the provided time frame unit (`TF_Period`) and multiplier (`TF_Multip`).
Parameters:
TF_Period (simple string)
TF_Multip (simple int)
Returns: A string that represents the time frame in Pine Script format, depending on the `TF_Period`:
- For "Minute", it returns the multiplier as a string (e.g., "5" for 5 minutes).
- For "Hour", it returns the equivalent number of minutes (e.g., "120" for 2 hours).
- For "Day", it appends "D" to the multiplier (e.g., "2D" for 2 days).
- For "Week", it appends "W" to the multiplier (e.g., "1W" for 1 week).
- For "Month", it appends "M" to the multiplier (e.g., "3M" for 3 months).
If none of these cases match, it returns the current chart's time frame.
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip)
TF_Display generates a string representation of a time frame based on user-defined inputs or the current chart's time frame settings.
Parameters:
Chart_as_Timeframe (bool) : (bool): Determines whether to use the current chart's time frame or a custom time frame.
TF_Period` (string): The time frame unit (e.g., "Minute", "Hour", "Day", "Week", "Month").
TF_Multip` (int): The multiplier for the time frame (e.g., 15 for 15 minutes, 2 for 2 days).
TF_Period (string)
TF_Multip (int)
Returns: If `Chart_as_Timeframe` is `false`, the function returns a time frame string based on the provided `TF_Period` and `TF_Multip` values (e.g., "5Min", "2D").
If `Chart_as_Timeframe` is `true`, the function determines the current chart's time frame and returns it as a string:
For minute-based time frames, it returns the number of minutes with "Min" (e.g., "15Min") unless it's an exact hour, in which case it returns the hour (e.g., "1H").
For daily, weekly, and monthly time frames, it returns the multiplier with the appropriate unit (e.g., "1D" for daily, "1W" for weekly, "1M" for monthly).
MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)
MTF_MS_Display This function calculates and returns a modified swing length value based on the selected time frame and current chart's time frame.
Parameters:
Chart_as_Timeframe (bool)
TF_Period (string)
TF_Multip (int)
Swing_Length (int)
HTF_Structure_Control(Chart_as_Timeframe, Show_Only_On_Lower_Timeframes, TF_Period, TF_Multip)
Parameters:
Chart_as_Timeframe (bool)
Show_Only_On_Lower_Timeframes (bool)
TF_Period (string)
TF_Multip (int)
Enhanced Economic Composite with Dynamic WeightEnhanced Economic Composite with Dynamic Weight
Overview of the Indicator :
The "Enhanced Economic Composite with Dynamic Weight" is a comprehensive tool that combines multiple economic indicators, technical signals, and dynamic weighting to provide insights into market and economic health. It adjusts based on current volatility and recession risk, offering a detailed view of market conditions.
What This Indicator Does :
Tracks Economic Health: Uses key economic and market indicators to assess overall market conditions.
Dynamic Weighting: Adjusts the importance of components like stock indices, gold, and bonds based on volatility (VIX) and yield curve inversion.
Technical Signals: Identifies market momentum shifts through key crossovers like the Golden Cross, Death Cross, Silver Cross, and Hospice Cross.
Recession Shading: Marks known recessions for historical context.
Economic Factors Considered :
TIP (Treasury Inflation-Protected Securities): Reflects inflation expectations.
Gold: A safe-haven asset, increases in weight during volatility or rising momentum.
US Dollar Index (DXY): Measures USD strength, fixed weight of 10%, smoothed with EMA.
Commodities (DBC): Indicates global demand; weight increases with momentum or volatility.
Volatility Index (VIX): Reflects market risk, inversely related to market confidence.
Stock Indices (S&P 500, DJIA, NASDAQ, Russell 2000): Represent market performance, with weights reduced during high volatility or negative yield spread.
Yield Spread (10Y - 2Y Treasuries): Predicts recessions; negative spread reduces stock weighting.
Credit Spread (HYG - TLT): Indicates market risk through corporate vs. government bond yields.
How and Why Factors are Weighted:
Stock Indices get more weight in stable markets (low VIX, positive yield spread), while safe-haven assets like gold and bonds gain weight in volatile markets or during yield curve inversions. This dynamic adjustment ensures the composite reflects current market sentiment.
Technical Signals:
Golden Cross: 50 EMA crossing above 200 SMA, signaling bullish momentum.
Death Cross: 50 EMA below 200 SMA, indicating bearish momentum.
Silver Cross: 21 EMA crossing above 50 EMA, plotted only if below the 200-day SMA, signaling potential upside in downtrend conditions.
Hospice Cross: 50 EMA crosses below 21 EMA, plotted only if 21 EMA is below 200 SMA, a leading bearish signal.
Recession Shading:
Recession periods like the Great Recession, Early 2000s Recession, and COVID-19 Recession are shaded to provide historical context.
Benefits of Using This Indicator:
Comprehensive Analysis: Combines economic fundamentals and technical analysis for a full market view.
Dynamic Risk Adjustment: Weights shift between growth and safe-haven assets based on volatility and recession risk.
Early Signals: The Silver Cross and Hospice Cross provide early warnings of potential market shifts.
Recession Forecasting: Helps predict downturns through the yield curve and recession indicators.
Who Can Benefit:
Traders: Identify market momentum shifts early through crossovers.
Long-term Investors: Use recession warnings and dynamic adjustments to protect portfolios.
Analysts: A holistic tool for analyzing both economic trends and market movements.
This indicator helps users navigate varying market conditions by dynamically adjusting based on economic factors and providing early technical signals for market momentum shifts.
VATICAN BANK CARTELVATICAN BANK CARTEL - Precision Signal Detection for Buyers.
The VATICAN BANK CARTEL indicator is a highly sophisticated tool designed specifically for buyers, helping them identify key market trends and generate actionable buy signals. Utilizing advanced algorithms, this indicator employs a multi-variable detection mechanism that dynamically adapts to price movements, offering real-time insights to assist in executing profitable buy trades. This indicator is optimized solely for identifying buying opportunities, ensuring that traders are equipped to make well-timed entries and exits, without signals for shorting or selling.
The recommended settings for VATICAN BANK CARTEL indicator is as follows:-
Depth Engine = 20,30,40,50,100.
Deviation Engine = 3,5,7,15,20.
Backstep Engine = 15,17,20,25.
NOTE:- But you can also use this indicator as per your setting, whichever setting gives you best results use that setting.
Key Features:
1.Adaptive Depth, Deviation, and Backstep Inputs:
The core of this indicator is its customizable Depth Engine, Deviation Engine, and Backstep Engine parameters. These inputs allow traders to adjust the sensitivity of the trend detection algorithm based on specific market conditions:
Depth: Defines how deep the indicator scans historical price data for potential trend reversals.
Deviation: Determines the minimum required price fluctuation to confirm a market movement.
Backstep: Sets the retracement level to filter false signals and maintain the accuracy of trend detection.
2. Visual Signal Representation:
The VATICAN BANK CARTEL plots highly visible labels on the chart to mark trend reversals. These labels are customizable in terms of size and transparency, ensuring clarity in various chart environments. Traders can quickly spot buying opportunities with green labels and potential square-off points with red labels, focusing exclusively on buy-side signals.
3.Real-Time Alerts:
The indicator is equipped with real-time alert conditions to notify traders of significant buy or square-off buy signals. These alerts, which are triggered based on the indicator’s internal signal logic, ensure that traders never miss a critical market movement on the buy side.
4.Custom Label Size and Transparency:
To enhance visual flexibility, the indicator allows the user to adjust label size (from small to large) and transparency levels. This feature provides a clean, adaptable view suited for different charting styles and timeframes.
How It Works:
The VATICAN BANK CARTEL analyzes the price action using a sophisticated algorithm that considers historical low and high points, dynamically detecting directional changes. When a change in market direction is detected, the indicator plots a label at the key reversal points, helping traders confirm potential entry points:
- Buy Signal (Green): Indicates potential buying opportunities based on a trend reversal.
- Square-Off Buy Signal (Red): Marks the exit point for open buy positions, allowing traders to take profits or protect capital from potential market reversals.
Note: This indicator is exclusively designed to provide signals for buyers. It does not generate sell or short signals, making it ideal for traders focused solely on identifying optimal buying opportunities in the market.
Customizable Parameters:
- Depth Engine: Fine-tunes the historical data analysis for signal generation.
- Deviation Engine: Adjusts the minimum price change required for detecting trends.
- Backstep Engine: Controls the indicator's sensitivity to retracements, minimizing false signals.
- Labels Transparency: Adjusts the opacity of the labels, ensuring they integrate seamlessly into any chart layout.
- Buy and Sell Colors: Customizable color options for buy and square-off buy labels to match your preferred color scheme.
- Label Size: Select between five different label sizes for optimal chart visibility.
Ideal For:
This indicator is ideal for both beginner and experienced traders looking to enhance their buying strategy with a highly reliable, visual, and alert-driven tool. The VATICAN BANK CARTEL adapts to various timeframes, making it suitable for day traders, swing traders, and long-term investors alike—focused exclusively on buying opportunities.
Benefits and Applications:
1.Intraday Trading: The VATICAN BANK CARTEL indicator is particularly well-suited for intraday trading, as it provides accurate and timely "buy" and "square-off buy" signals based on the current market dynamics.
2.Trend-following Strategies: Traders who employ trend-following strategies can leverage the indicator's ability to identify the overall market direction, allowing them to align their trades with the dominant trend.
3.Swing Trading: The dynamic price tracking and signal generation capabilities of the indicator can be beneficial for swing traders, who aim to capture medium-term price movements.
Security Measures:
1. The code includes a security notice at the beginning, indicating that it is subject to the Mozilla Public License 2.0, which is a reputable open-source license.
2. The code does not appear to contain any obvious security vulnerabilities or malicious content that could compromise user data or accounts.
NOTE:- This indicator is provided under the Mozilla Public License 2.0 and is subject to its terms and conditions.
Disclaimer: The usage of VATICAN BANK CARTEL indicator might or might not contribute to your trading capital(money) profits and losses and the author is not responsible for the same.
IMPORTANT NOTICE:
While the indicator aims to provide reliable "buy" and "square-off buy" signals, it is crucial to understand that the market can be influenced by unpredictable events, such as natural disasters, political unrest, changes in monetary policies, or economic crises. These unforeseen situations may occasionally lead to false signals generated by the VATICAN BANK CARTEL indicator.
Users should exercise caution and diligence when relying on the indicator's signals, as the market's behavior can be unpredictable, and external factors may impact the accuracy of the signals. It is recommended to thoroughly backtest the indicator's performance in various market conditions and to use it as one of the many tools in a comprehensive trading strategy, rather than solely relying on its output.
Ultimately, the success of the VATICAN BANK CARTEL indicator will depend on the user's ability to adapt it to their specific trading style, market conditions, and risk management approach. Continuous monitoring, analysis, and adjustment of the indicator's settings may be necessary to maintain its effectiveness in the ever-evolving financial markets.
DEVELOPER:- yashgode9
PineScript:- version:- 5
This indicator aims to enhance trading decision-making by combining DEPTH, DEVIATION, BACKSTEP with custom signal generation, offering a comprehensive tool for traders seeking clear "buy" and "square-off buy" signals on the TradingView platform.
Adaptive Gaussian MA For Loop [BackQuant]Adaptive Gaussian MA For Loop
PLEASE Read the following carefully before applying this indicator to your trading system. Knowing the core logic behind the tools you're using allows you to integrate them into your strategy with confidence and precision.
Introducing BackQuant's Adaptive Gaussian Moving Average For Loop (AGMA FL) — a sophisticated trading indicator that merges the Gaussian Moving Average (GMA) with adaptive volatility to provide dynamic trend analysis. This unique indicator further enhances its effectiveness by utilizing a for-loop scoring mechanism to detect potential shifts in market direction. Let's dive into the components, the rationale behind them, and how this indicator can be practically applied to your trading strategies.
Understanding the Gaussian Moving Average (GMA)
The Gaussian Moving Average (GMA) is a smoothed moving average that applies Gaussian weighting to price data. Gaussian weighting gives more significance to data points near the center of the lookback window, making the GMA particularly effective at reducing noise while maintaining sensitivity to changes in price direction. In contrast to simpler moving averages like the SMA or EMA, GMA provides a more refined smoothing function, which can help traders follow the true trend in volatile markets.
In this script, the GMA is calculated over a defined Calculation Period (default 14), applying a Gaussian filter to smooth out market fluctuations and provide a clearer view of underlying trends.
Adaptive Volatility: A Dynamic Edge
The Adaptive feature in this indicator gives it the ability to adjust its sensitivity based on current market volatility. If the Adaptive option is enabled, the GMA uses a standard deviation-based volatility measure (with a default period of 20) to dynamically adjust the width of the Gaussian filter, allowing the GMA to react faster in volatile markets and more slowly in calm conditions. This dynamic nature ensures that the GMA stays relevant across different market environments.
When the Adaptive setting is disabled, the script defaults to a constant standard deviation value (default 1.0), providing a more stable but less responsive smoothing function.
Why Use Adaptive Gaussian Moving Average?
The Gaussian Moving Average already provides smoother results than standard moving averages, but by adding an adaptive component, the indicator becomes even more responsive to real-time price changes. In fast-moving or highly volatile markets, this adaptation allows traders to react quicker to emerging trends. Conversely, in quieter markets, it reduces over-sensitivity to minor fluctuations, thus lowering the risk of false signals.
For-Loop Scoring Mechanism
The heart of this indicator lies in its for-loop scoring system, which evaluates the smoothed price data (the GMA) over a specified range, comparing it to previous values. This scoring system assigns a numerical value based on whether the current GMA is higher or lower than previous values, creating a trend score.
Long Signals: These are generated when the for-loop score surpasses the Long Threshold (default set at 40), signaling that the GMA is gaining upward momentum, potentially identifying a favorable buying opportunity.
Short Signals: These are triggered when the score crosses below the Short Threshold (default set at -10), indicating that the market may be losing strength and that a selling or shorting opportunity could be emerging.
Thresholds & Customization Options
This indicator offers a high degree of flexibility, allowing you to fine-tune the settings according to your trading style and risk preferences:
Calculation Period: Adjust the lookback period for the Gaussian filter, affecting how smooth or responsive the indicator is to price changes.
Adaptive Mode: Toggle the adaptive feature on or off, allowing the GMA to dynamically adjust based on market volatility or remain consistent with a fixed standard deviation.
Volatility Settings: Control the standard deviation period for adaptive mode, fine-tuning how quickly the GMA responds to shifts in volatility.
For-Loop Settings: Modify the start and end points for the for-loop score calculation, adjusting the depth of analysis for trend signals.
Thresholds for Signals: Set custom long and short thresholds to determine when buy or sell signals should be generated.
Visualization Options: Choose to color bars based on trend direction, plot signal lines, or adjust the background color to reflect current market sentiment visually.
Trading Applications
The Adaptive Gaussian MA For Loop can be applied to a variety of trading styles and markets. Here are some key ways you can use this indicator in practice:
Trend Following: The combination of Gaussian smoothing and adaptive volatility helps traders stay on top of market trends, identifying significant momentum shifts while filtering out noise. The for-loop scoring system enhances this by providing a numerical representation of trend strength, making it easier to spot when a new trend is emerging or when an existing one is gaining strength.
Mean Reversion: For traders looking to capitalize on short-term market corrections, the adaptive nature of this indicator makes it easier to identify when price action is deviating too far from its smoothed trend, allowing for strategic entries and exits based on overbought or oversold conditions.
Swing Trading: With its ability to capture medium-term price movements while avoiding the noise of short-term fluctuations, this indicator is well-suited for swing traders who aim to profit from market reversals or short-to-mid-term trends.
Volatility Management: The adaptive feature allows the indicator to adjust dynamically in volatile markets, ensuring that it remains responsive in times of increased uncertainty while avoiding unnecessary noise in calmer periods. This makes it an effective tool for traders who want to manage risk by staying in tune with changing market conditions.
Final Thoughts
The Adaptive Gaussian MA For Loop is a powerful and flexible indicator that merges the elegance of Gaussian smoothing with the adaptability of volatility-based adjustments. By incorporating a for-loop scoring mechanism, this indicator provides traders with a comprehensive view of market trends and potential trade opportunities.
It’s important to test the settings on historical data and adapt them to your specific trading style, timeframe, and market conditions. As with any technical tool, the AGMA For Loop should be used in conjunction with other indicators and solid risk management practices for the best results.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Two Pole Butterworth For Loop [BackQuant]Two Pole Butterworth For Loop
PLEASE read the following carefully, as understanding the underlying concepts and logic behind the indicator is key to incorporating it into your trading system in a sound and methodical manner.
Introducing BackQuant's Two Pole Butterworth For Loop (2P BW FL) — an advanced indicator that fuses the power of the Two Pole Butterworth filter with a dynamic for-loop scoring mechanism. This unique approach is designed to extract actionable trading signals by smoothing out price data and then analyzing it using a comparative scoring method. Let's delve into how this indicator works, why it was created, and how it can be used in various trading scenarios.
Understanding the Two Pole Butterworth Filter
The Butterworth filter is a signal processing tool known for its smooth response and minimal distortion. It's often used in electronic and communication systems to filter out unwanted noise. In trading, the Butterworth filter can be applied to price data to smooth out the volatility, providing traders with a clearer view of underlying trends without the whipsaws often associated with market noise.
The Two Pole Butterworth variant further enhances this effect by applying the filter with two poles, effectively creating a sharper transition between the passband and stopband. In simple terms, this allows the filter to follow the price action more closely, reacting to changes while maintaining smoothness.
In this script, the Two Pole Butterworth filter is applied to the Calculation Source (default is set to the closing price), creating a smoothed price series that serves as the foundation for further analysis.
Why Use a Two Pole Butterworth Filter?
The Two Pole Butterworth filter is chosen for its ability to reduce lag while maintaining a smooth output. This makes it an ideal choice for traders who want to capture trends without being misled by short-term volatility or market noise. By filtering the price data, the Two Pole Butterworth enables traders to focus on the broader market movements and avoid false signals.
The For-Loop Scoring Mechanism
In addition to the Butterworth filter, this script uses a for-loop scoring system to evaluate the smoothed price data. The for-loop compares the current value of the filtered price (referred to as "subject") to previous values over a defined range (set by the start and end input). The score is calculated based on whether the subject is higher or lower than the previous points, and the cumulative score is used to determine the strength of the trend.
Long and Short Signal Logic
Long Signals: A long signal is triggered when the score surpasses the Long Threshold (default set at 40). This suggests that the price has built sufficient upward momentum, indicating a potential buying opportunity.
Short Signals: A short signal is triggered when the score crosses under the Short Threshold (default set at -10). This indicates weakening price action or a potential downtrend, signaling a possible selling or shorting opportunity.
By utilizing this scoring system, the indicator identifies moments when the price momentum is shifting, helping traders enter positions at opportune times.
Customization and Visualization Options
One of the strengths of this indicator is its flexibility. Traders can customize various settings to fit their personal trading style or adapt it to different markets and timeframes:
Calculation Periods: Adjust the lookback period for the Butterworth filter, allowing for shorter or longer smoothing depending on the desired sensitivity.
Threshold Levels: Set the long and short thresholds to define when signals should be triggered, giving you control over the balance between sensitivity and specificity.
Signal Line Width and Colors: Customize the visual presentation of the indicator on the chart, including the width of the signal line and the colors used for long and short conditions.
Candlestick and Background Colors: If desired, the indicator can color the candlesticks or the background according to the detected trend, offering additional clarity at a glance.
Trading Applications
This Two Pole Butterworth For Loop indicator is versatile and can be adapted to various market conditions and trading strategies. Here are a few use cases where this indicator shines:
Trend Following: The Butterworth filter smooths the price data, making it easier to follow trends and identify when they are gaining or losing strength. The for-loop scoring system enhances this by providing a clear indication of how strong the current trend is compared to recent history.
Mean Reversion: For traders looking to identify potential reversals, the indicator’s ability to compare the filtered price to previous values over a range of periods allows it to spot moments when the trend may be losing steam, potentially signaling a reversal.
Swing Trading: The combination of smoothing and scoring allows swing traders to capture short to medium-term price movements by filtering out the noise and focusing on significant shifts in momentum.
Risk Management: By providing clear long and short signals, this indicator helps traders manage their risk by offering well-defined entry and exit points. The smooth nature of the Butterworth filter also reduces the risk of getting caught in false signals due to market noise.
Final Thoughts
The Two Pole Butterworth For Loop indicator offers traders a powerful combination of smoothing and scoring to detect meaningful trends and shifts in price momentum. Whether you are a trend follower, swing trader, or someone looking to refine your entry and exit points, this indicator provides the tools to make more informed trading decisions.
As always, it's essential to backtest the indicator on historical data and tailor the settings to your specific trading style and market. While the Butterworth filter helps reduce noise and smooth trends, no indicator can predict the future with absolute certainty, so it should be used in conjunction with other tools and sound risk management practices.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Fourier For Loop [BackQuant]Fourier For Loop
PLEASE Read the following, as understanding an indicator's functionality is essential before integrating it into a trading strategy. Knowing the core logic behind each tool allows for a sound and strategic approach to trading.
Introducing BackQuant's Fourier For Loop (FFL) — a cutting-edge trading indicator that combines Fourier transforms with a for-loop scoring mechanism. This innovative approach leverages mathematical precision to extract trends and reversals in the market, helping traders make informed decisions. Let's break down the components, rationale, and potential use-cases of this indicator.
Understanding Fourier Transform in Trading
The Fourier Transform decomposes price movements into their frequency components, allowing for a detailed analysis of cyclical behavior in the market. By transforming the price data from the time domain into the frequency domain, this indicator identifies underlying patterns that traditional methods may overlook.
In this script, Fourier transforms are applied to the specified calculation source (defaulted to HLC3). The transformation yields magnitude values that can be used to score market movements over a defined range. This scoring process helps uncover long and short signals based on relative strength and trend direction.
Why Use Fourier Transforms?
Fourier Transforms excel in identifying recurring cycles and smoothing noisy data, making them ideal for fast-paced markets where price movements may be erratic. They also provide a unique perspective on market volatility, offering traders additional insights beyond standard indicators.
Calculation Logic: For-Loop Scoring Mechanism
The For Loop Scoring mechanism compares the magnitude of each transformed point in the series, summing the results to generate a score. This score forms the backbone of the signal generation system.
Long Signals: Generated when the score surpasses the defined long threshold (default set at 40). This indicates a strong bullish trend, signaling potential upward momentum.
Short Signals: Triggered when the score crosses under the short threshold (default set at -10). This suggests a bearish trend or potential downside risk.'
Thresholds & Customization
The indicator offers customizable settings to fit various trading styles:
Calculation Periods: Control how many periods the Fourier transform covers.
Long/Short Thresholds: Adjust the sensitivity of the signals to match different timeframes or risk preferences.
Visualization Options: Traders can visualize the thresholds, change the color of bars based on trend direction, and even color the background for enhanced clarity.
Trading Applications
This Fourier For Loop indicator is designed to be versatile across various market conditions and timeframes. Some of its key use-cases include:
Cycle Detection: Fourier transforms help identify recurring patterns or cycles, giving traders a head-start on market direction.
Trend Following: The for-loop scoring system helps confirm the strength of trends, allowing traders to enter positions with greater confidence.
Risk Management: With clearly defined long and short signals, traders can manage their positions effectively, minimizing exposure to false signals.
Final Note
Incorporating this indicator into your trading strategy adds a layer of mathematical precision to traditional technical analysis. Be sure to adjust the calculation start/end points and thresholds to match your specific trading style, and remember that no indicator guarantees success. Always backtest thoroughly and integrate the Fourier For Loop into a balanced trading system.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future .
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Multiple ATR Lines with Current Price PercentageThis indicator plots multiple lines based on the Average True Range (ATR) on the chart, helping traders identify potential support and resistance levels. Specifically, it draws three lines above the price and three lines below the price at different multiples of the ATR. Additionally, it plots a dynamic line at the current price level, which shows how much percentage of the ATR the current price has traveled from a specific point.
How it works:
ATR-Based Lines: The indicator calculates three upper and three lower levels based on the ATR of the selected period. These levels represent 1x, 2x, and 3x ATR above and below the current price.
Current Price Line: A dotted line follows the current price, displaying the percentage of the ATR that the price has moved.
Labels: Each line is labeled with its respective ATR multiple (1x ATR, 2x ATR, 3x ATR), and the current price line shows the percentage of the ATR traveled.
Use Cases:
Identifying Market Volatility: Traders can use this indicator to see how far the price has moved relative to its average volatility.
Support and Resistance Levels: The ATR lines can be treated as potential support and resistance zones, providing insight into price targets or stop-loss placement.
Dynamic Tracking: The percentage of ATR traveled helps traders understand the market momentum relative to its historical volatility.
Settings:
ATR Length: The user can adjust the length of the ATR calculation period.
ATR Multiplier: A multiplier to adjust the distance of the lines relative to the ATR.
Advantages:
Clear visualization of market volatility through ATR-based levels.
Real-time tracking of the price’s movement relative to ATR, giving traders a better understanding of price action.
Customizable settings for different trading styles.
Support Resistance ImportanceThe Support Resistance Importance indicator is designed to highlight key price levels based on the relationship between fractal occurrences and volume distribution within a given price range. By dividing the range into bins, the indicator calculates the total volume traded at each fractal level and normalizes the values for easy visualization. The normalized values represent an "importance score" for each price range, helping traders identify critical support and resistance levels where price action might react.
Key Features:
Fractal Detection:
The indicator detects Williams Fractals, which are specific price patterns representing potential market reversals. It identifies both upward fractals (potential resistance) and downward fractals (potential support).
Price Range Binning:
The price range is divided into a user-defined number of bins (default is 20). Each bin represents a segment of the total price range, allowing the indicator to bucket price action and track fractal volumes in each bin.
Volume-Based Importance Calculation:
For each bin, the indicator sums up the volume traded at the time a fractal occurred. The volumes are then normalized to reflect their relative importance.
The importance score is calculated as the relative volume in each bin, representing the potential influence of that price range. Higher scores indicate stronger support or resistance levels.
Normalization:
The volume data is normalized to allow for better comparison across bins. This normalization ensures that the highest and lowest volumes are scaled between 0 and 1 for visualization purposes. The smallest volume value is used to scale the rest, ensuring meaningful comparisons.
Visualization:
The indicator provides a table-based visualization showing the price range and the corresponding importance score for each bin.
Each bin is color-coded based on the normalized importance score, with blue or greenish shades indicating higher importance levels. The current price range is highlighted to help traders quickly identify relevant areas of interest.
Trading Utility:
Traders can use the importance scores to identify price levels where significant volume has accumulated at fractals. A higher importance score suggests a stronger likelihood of the price reacting to that level.
If a price moves towards a bin with a high score and the bins above it have much smaller values, it suggests that the price may "pump" up to the next high-scored range, similar to how price drops can occur.
Example Use Case:
Suppose the price approaches a bin with an importance score of 25, and the bins above have much smaller values. This suggests that price may break higher towards the next significant level of resistance, offering traders an opportunity to capitalize on the move by entering long positions or adjusting their stop losses.
This indicator is particularly useful for support and resistance trading, where understanding key levels of price action and volume can improve decision-making in anticipating market reactions.
Adaptive Volatility-Controlled LSMA [QuantAlgo]Adaptive Volatility-Controlled LSMA by QuantAlgo 📈💫
Introducing the Adaptive Volatility-Controlled LSMA (Least Squares Moving Average) , a powerful trend-following indicator that combines trend detection with dynamic volatility adjustments. This indicator is designed to help traders and investors identify market trends while accounting for price volatility, making it suitable for a wide range of assets and timeframes. By integrating LSMA for trend analysis and Average True Range (ATR) for volatility control, this tool provides clearer signals during both trending and volatile market conditions.
💡 Core Concept and Innovation
The Adaptive Volatility-Controlled LSMA leverages the precision of the LSMA to track market trends and combines it with the sensitivity of the ATR to account for market volatility. LSMA fits a linear regression line to price data, providing a smoothed trend line that is less reactive to short-term noise. The ATR, on the other hand, dynamically adjusts the volatility bands around the LSMA, allowing the indicator to filter out false signals and respond to significant price moves. This combination provides traders with a reliable tool to identify trend shifts while managing risk in volatile markets.
📊 Technical Breakdown and Calculations
The indicator consists of the following components:
1. Least Squares Moving Average (LSMA): The LSMA calculates a linear regression line over a defined period to smooth out price fluctuations and reveal the underlying trend. It is more reactive to recent data than traditional moving averages, allowing for quicker trend detection.
2. ATR-Based Volatility Bands: The Average True Range (ATR) measures market volatility and creates upper and lower bands around the LSMA. These bands expand and contract based on market conditions, helping traders identify when price movements are significant enough to indicate a new trend.
3. Volatility Extensions: To further account for rapid market changes, the bands are extended using additional volatility measures. This ensures that trend signals are generated when price movements exceed both the standard volatility range and the extended volatility range.
⚙️ Step-by-Step Calculation:
1. LSMA Calculation: The LSMA is computed using a least squares regression method over a user-defined length. This provides a trend line that adapts to recent price movements while smoothing out noise.
2. ATR and Volatility Bands: ATR is calculated over a user-defined length and is multiplied by a factor to create upper and lower bands around the LSMA. These bands help detect when price movements are substantial enough to signal a new trend.
3. Trend Detection: The price’s relationship to the LSMA and the volatility bands is used to determine trend direction. If the price crosses above the upper volatility band, a bullish trend is detected. Conversely, a cross below the lower band indicates a bearish trend.
✅ Customizable Inputs and Features:
The Adaptive Volatility-Controlled LSMA offers a variety of customizable options to suit different trading or investing styles:
📈 Trend Settings:
1. LSMA Length: Adjust the length of the LSMA to control its sensitivity to price changes. A shorter length reacts quickly to new data, while a longer length smooths the trend line.
2. Price Source: Choose the type of price (e.g., close, high, low) that the LSMA uses to calculate trends, allowing for different interpretations of price data.
🌊 Volatility Controls:
ATR Length and Multiplier: Adjust the length and sensitivity of the ATR to control how volatility is measured. A higher ATR multiplier widens the bands, making the trend detection less sensitive, while a lower multiplier tightens the bands, increasing sensitivity.
🎨 Visualization and Alerts:
1. Bar Coloring: Customize bar colors to visually distinguish between uptrends and downtrends.
2. Volatility Bands: Enable or disable the display of volatility bands on the chart. The bands provide visual cues about trend strength and volatility thresholds.
3. Alerts: Set alerts for when the price crosses the upper or lower volatility bands, signaling potential trend changes.
📈 Practical Applications
The Adaptive Volatility-Controlled LSMA is ideal for traders and investors looking to follow trends while accounting for market volatility. Its key use cases include:
Identifying Trend Reversals: The indicator detects when price movements break through volatility bands, signaling potential trend reversals.
Filtering Market Noise: By applying ATR-based volatility filtering, the indicator helps reduce false signals caused by short-term price fluctuations.
Managing Risk: The volatility bands adjust dynamically to account for market conditions, helping traders manage risk and improve the accuracy of their trend-following strategies.
⭐️ Summary
The Adaptive Volatility-Controlled LSMA by QuantAlgo offers a robust and flexible approach to trend detection and volatility management. Its combination of LSMA and ATR creates clearer, more reliable signals, making it a valuable tool for navigating trending and volatile markets. Whether you're detecting trend shifts or filtering market noise, this indicator provides the tools you need to enhance your trading and investing strategy.
Note: The Adaptive Volatility-Controlled LSMA is a tool to enhance market analysis. It should be used in conjunction with other analytical tools and should not be relied upon as the sole basis for trading or investment decisions. No signals or indicators constitute financial advice, and past performance is not indicative of future results.
Multi-timeframe 24 moving averages + BB+SAR+Supertrend+VWAP █ OVERVIEW
The script allows to display up to 24 moving averages ("MA"'s) across 5 timeframes plus two bands (Bollinger Bands or Supertrend or Parabolic SAR or VWAP bands) each from its own timeframe.
The main difference of this script from many similar ones is the flexibility of its settings:
- Bulk enable/disable and/or change properties of several MAs at once.
- Save 3 of your frequently used templates as presets using CSV text configurations.
█ HOW TO USE
Some use examples:
In order to "show 31, 50, 200 EMAs and 20, 100, 200 SMAs for each of 1H, 4H, D, W, M timeframes using blue for short MA, yellow for mid MA and red for long MA" use the settings as shown on a screenshot below.
In order to "Show a band of chart timeframe MA's of lengths 5, 8, 13, 21, 34, 55, 100 and 200 plus some 1H, 4H, D and W MAs. Be able to quickly switch off the band of chart tf's MAs. For chart timeframe MA's only show labels for 21, 100 and 200 EMAs". You can set TF1 and TF2 to chart's TF and set you fib MAs there and configure fixed higher timeframe MAs using TF3, TF4 and TF5 (e.g. using 1H, D and W timeframes and using 1H 800 in place of 4H 200 MA). However, quicker way may be using CSV - the syntax is very simple and intuitive, see Preset 2 as it comes in the script. You can easily switch chart tf's band of MAs by toggling on/off your chart timeframe TF's (in our example, TF1 and TF2).
The settings are either obvious or explained in tooltips.
Note 1: When using group settings and CSV presets do not forget that individual setting affected will no have any effect. So, if some setting does not work, check whether it is overridden with some group setting or a CSV preset.
Note 2: Sometimes you can notice parts of MA's hanging in the air, not lasting up to the last bar. This is not a bug as explained on this screenshot:
█ FOR DEVELOPERS
The script is a use case of my CSVParser library, which in turn uses Autotable library, both of which I hope will be quite helpful. Autotable is so powerful and comprehensive that you will hardly ever wish to use normal table functions again for complex tables.
The indicator was inspired by Pablo Limonetti's url=https://www.tradingview.com/script/nFs56VUZ/]Multi Timeframe Moving Averages and Raging @RagingRocketBull's # Multi SMA EMA WMA HMA BB (5x8 MAs Bollinger Bands) MAX MTF - RRB
HTFBands█ OVERVIEW
Contains type and methods for drawing higher-timeframe bands of several types:
Bollinger bands
Parabolic SAR
Supertrend
VWAP
By copy pasting ready made code sections to your script you can add as many multi-timeframe bands as necessary.
█ HOW TO USE
Please see instructions in the code. (Important: first fold all sections of the script: press Cmd + K then Cmd + - (for Windows Ctrl + K then Ctrl + -)
█ FULL LIST OF FUNCTIONS AND PARAMETERS
atr2(length)
An alternate ATR function to the `ta.atr()` built-in, which allows a "series float"
`length` argument.
Parameters:
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The ATR value.
pine_supertrend2(factor, atrLength, wicks)
An alternate SuperTrend function to `supertrend()`, which allows a "series float"
`atrLength` argument.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when
reversing trend, or to use the close price. Optional. Default is false.
Returns: ( ) A tuple of the superTrend value and trend direction.
method getDefaultBandQ1(bandType)
For a given BandType returns its default Q1
Namespace types: series BandTypes
Parameters:
bandType (series BandTypes)
method getDefaultBandQ2(bandType)
For a given BandType returns its default Q2
Namespace types: series BandTypes
Parameters:
bandType (series BandTypes)
method getDefaultBandQ3(bandType)
For a given BandType returns its default Q3
Namespace types: series BandTypes
Parameters:
bandType (series BandTypes)
method init(this, bandsType, q1, q2, q3, vwapAnchor)
Initiates RsParamsBands for each band (used in htfUpdate() withi req.sec())
Namespace types: RsParamsBands
Parameters:
this (RsParamsBands)
bandsType (series BandTypes)
q1 (float) : (float) Depending on type: BB - length, SAR - AF start, ST - ATR's prd
q2 (float) : (float) Depending on type: BB - StdDev mult, SAR - AF step, ST - mult
q3 (float) : (float) Depending on type: BB - not used, SAR - AF max, ST - not used
vwapAnchor (series VwapAnchors) : (VwapAnchors) VWAP ahcnor
method init(this, bandsType, tf, showRecentBars, lblsShow, lblsMaxLabels, lblSize, lnMidClr, lnUpClr, lnLoClr, fill, fillClr, lnWidth, lnSmoothen)
Initialises object with params (incl. input). Creates arrays if any.
Namespace types: HtfBands
Parameters:
this (HtfBands)
bandsType (series BandTypes) : (BandTypes) Just used to enable/disable - if BandTypes.none then disable )
tf (string) : (string) Timeframe
showRecentBars (int) : (int) Only show over this number of recent bars
lblsShow (bool) : (bool) Show labels
lblsMaxLabels (int) : (int) Max labels to show
lblSize (string) : (string) Size of the labels
lnMidClr (color) : (color) Middle band color
lnUpClr (color) : (color) Upper band color
lnLoClr (color) : (color) Lower band color
fill (bool)
fillClr (color) : (color) Fill color
lnWidth (int) : (int) Line width
lnSmoothen (bool) : (bool) Smoothen the bands
method htfUpdateTuple(rsPrms, repaint)
(HTF) Calculates Bands within request.security(). Returns tuple . If any or all of the bands are not available returns na as their value.
Namespace types: RsParamsBands
Parameters:
rsPrms (RsParamsBands) : (RsParamsBands) Parameters of the band.
repaint (bool) : (bool) If true does not update on realtime bars.
Returns: A tuple (corresponds to fields in RsReturnBands)
method importRsRetTuple(this, htfBi, mid, up, lo, dir)
Imports a tuple returned from req.sec() into an HtfBands object
Namespace types: HtfBands
Parameters:
this (HtfBands) : (HtfBands) Object to import to
htfBi (int) : (float) Higher timeframe's bar index (Default = na)
mid (float)
up (float) : (float) Value of upper band (Default = na)
lo (float) : (float) Value of lower band (Default = na)
dir (int) : (int) Direction (for bands like Parabolic SAR) (Default = na)
method addUpdDrawings(this, rsPrms)
Draws band's labels
Namespace types: HtfBands
Parameters:
this (HtfBands)
rsPrms (RsParamsBands)
method update(this)
Sets band's values to na on intrabars if `smoothen` is set.
Namespace types: HtfBands
Parameters:
this (HtfBands)
method newRsParamsBands(this)
A wraper for RsParamsBands.new()
Namespace types: LO_A
Parameters:
this (LO_A)
method newHtfBands(this)
A wraper for HtfBands.new()
Namespace types: LO_B
Parameters:
this (LO_B)
RsParamsBands
Used to pass bands' params to req.sec()
Fields:
bandsType (series BandTypes) : (enum BandTypes) Type of the band (BB, SAR etc.)
q1 (series float) : (float) Depending on type: BB - length, SAR - AF start, ST - ATR's prd
q2 (series float) : (float) Depending on type: BB - StdDev mult, SAR - AF step, ST - mult
q3 (series float) : (float) Depending on type: BB - not used, SAR - AF max, ST - not used
vwapAnchor (series VwapAnchors)
RsReturnBands
Used to return bands' data from req.sec(). Params of the bands are in RsParamsBands
Fields:
htfBi (series float) : (float) Higher timeframe's bar index (Default = na)
upBand (series float) : (float) Value of upper band (Default = na)
loBand (series float) : (float) Value of lower band (Default = na)
midBand (series float) : (float) Value of middle band (Default = na)
dir (series int) : (float) Direction (for bands like Parabolic SAR) (Default = na)
BandsDrawing
Contains plot visualization parameters and stores and keeps track of lines, labels and other visual objects (not plots)
Fields:
lnMidClr (series color) : (color) Middle band color
lnLoClr (series color) : (color) Lower band color
lnUpClr (series color) : (color) Upper band color
fillUpClr (series color)
fillLoClr (series color)
lnWidth (series int) : (int) Line width
lnSmoothen (series bool) : (bool) Smoothen the bands
showHistory (series bool) : (bool) If true show bands lines, otherwise only current level
showRecentBars (series int) : (int) Only show over this number of recent bars
arLbl (array) : (label Labels
lblsMaxLabels (series int) : (int) Max labels to show
lblsShow (series bool) : (bool) Show labels
lblSize (series string) : (string) Size of the labels
HtfBands
Calcs and draws HTF bands
Fields:
rsRet (RsReturnBands) : (RsReturnBands) Bands' values
rsRetNaObj (RsReturnBands) : (RsReturnBands) Dummy na obj for returning from request.security()
rsPrms (RsParamsBands) : (RsParamsBands) Band parameters (for htfUpdate() called in req.sec() )
drw (BandsDrawing) : (BandsDrawing) Contains plot visualization parameters and stores and keeps track of lines, labels and other visual objects (not plots)
enabled (series bool) : (bool) Toggles bands on/off
tf (series string) : (string) Timeframe
LO_A
LO Library object, whose only purpose is to serve as a shorthand for library name in script code.
Fields:
dummy (series string)
LO_B
LO Library object, whose only purpose is to serve as a shorthand for library name in script code.
Fields:
dummy (series string)
HTFMAs█ OVERVIEW
Contains a type HTFMA used to return data on six moving averages from a higher timeframe.
Several types of MA's are supported.
█ HOW TO USE
Please see instructions in the code (in library description). (Important: first fold all sections of the script: press Cmd + K then Cmd + - (for Windows Ctrl + K then Ctrl + -)
█ FULL LIST OF FUNCTIONS AND PARAMETERS
method getMaType(this)
Enumerator function, given a key returns `enum MaTypes` value
Namespace types: series string, simple string, input string, const string
Parameters:
this (string)
method init(this, enableAll, ma1Enabled, ma1MaType, ma1Src, ma1Prd, ma2Enabled, ma2MaType, ma2Src, ma2Prd, ma3Enabled, ma3MaType, ma3Src, ma3Prd, ma4Enabled, ma4MaType, ma4Src, ma4Prd, ma5Enabled, ma5MaType, ma5Src, ma5Prd, ma6Enabled, ma6MaType, ma6Src, ma6Prd)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs)
enableAll (simple MaEnable)
ma1Enabled (bool)
ma1MaType (series MaTypes)
ma1Src (string)
ma1Prd (int)
ma2Enabled (bool)
ma2MaType (series MaTypes)
ma2Src (string)
ma2Prd (int)
ma3Enabled (bool)
ma3MaType (series MaTypes)
ma3Src (string)
ma3Prd (int)
ma4Enabled (bool)
ma4MaType (series MaTypes)
ma4Src (string)
ma4Prd (int)
ma5Enabled (bool)
ma5MaType (series MaTypes)
ma5Src (string)
ma5Prd (int)
ma6Enabled (bool)
ma6MaType (series MaTypes)
ma6Src (string)
ma6Prd (int)
method init(this, enableAll, tf, rngAtrQ, showRecentBars, lblsOffset, lblsShow, lnOffset, lblSize, lblStyle, smoothen, ma1lnClr, ma1lnWidth, ma1lnStyle, ma2lnClr, ma2lnWidth, ma2lnStyle, ma3lnClr, ma3lnWidth, ma3lnStyle, ma4lnClr, ma4lnWidth, ma4lnStyle, ma5lnClr, ma5lnWidth, ma5lnStyle, ma6lnClr, ma6lnWidth, ma6lnStyle, ma1ShowHistory, ma2ShowHistory, ma3ShowHistory, ma4ShowHistory, ma5ShowHistory, ma6ShowHistory, ma1ShowLabel, ma2ShowLabel, ma3ShowLabel, ma4ShowLabel, ma5ShowLabel, ma6ShowLabel)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
enableAll (series MaEnable)
tf (string)
rngAtrQ (int)
showRecentBars (int)
lblsOffset (int)
lblsShow (bool)
lnOffset (int)
lblSize (string)
lblStyle (string)
smoothen (bool)
ma1lnClr (color)
ma1lnWidth (int)
ma1lnStyle (string)
ma2lnClr (color)
ma2lnWidth (int)
ma2lnStyle (string)
ma3lnClr (color)
ma3lnWidth (int)
ma3lnStyle (string)
ma4lnClr (color)
ma4lnWidth (int)
ma4lnStyle (string)
ma5lnClr (color)
ma5lnWidth (int)
ma5lnStyle (string)
ma6lnClr (color)
ma6lnWidth (int)
ma6lnStyle (string)
ma1ShowHistory (bool)
ma2ShowHistory (bool)
ma3ShowHistory (bool)
ma4ShowHistory (bool)
ma5ShowHistory (bool)
ma6ShowHistory (bool)
ma1ShowLabel (bool)
ma2ShowLabel (bool)
ma3ShowLabel (bool)
ma4ShowLabel (bool)
ma5ShowLabel (bool)
ma6ShowLabel (bool)
method get(this, id)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs)
id (int)
method set(this, id, prop, val)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs)
id (int)
prop (string)
val (string)
method set(this, id, prop, val)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
id (int)
prop (string)
val (string)
method htfUpdateTuple(rsParams, repaint)
Namespace types: RsParamsMAs
Parameters:
rsParams (RsParamsMAs)
repaint (bool)
method clear(this)
Namespace types: MaDrawing
Parameters:
this (MaDrawing)
method importRsRetTuple(this, htfBi, ma1, ma2, ma3, ma4, ma5, ma6)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
htfBi (int)
ma1 (float)
ma2 (float)
ma3 (float)
ma4 (float)
ma5 (float)
ma6 (float)
method getDrw(this, id)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
id (int)
method setDrwProp(this, id, prop, val)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
id (int)
prop (string)
val (string)
method initDrawings(this, rsPrms, dispBandWidth)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
rsPrms (RsParamsMAs)
dispBandWidth (float)
method updateDrawings(this, rsPrms, dispBandWidth)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
rsPrms (RsParamsMAs)
dispBandWidth (float)
method update(this)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps0 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps1 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps2 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps3 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps4 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps5 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `RsParamsMAs` child `RsMaCalcParams` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (RsParamsMAs) Target object to import prop values to.
oCfg (objProps6 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs)
oCfg (objProps7 type from moebius1977/CSVParser/1)
maCount (int)
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: RsParamsMAs
Parameters:
this (RsParamsMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps8 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps0 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps1 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps2 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps3 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps4 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps5 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Imports HTF MAs settings from objProps (of any level) into `HTFMAs` child `MaDrawing` objects (into the first first `maCount` of them)
Namespace types: HTFMAs
Parameters:
this (HTFMAs) : (HTFMAs) Target object to import prop values to.
oCfg (objProps6 type from moebius1977/CSVParser/1) : (CSVP.objProps) (one of objProps types) an objProps, ... opjProps8 containing properties' values in a child objProps objects
maCount (int) : (int) Number of tgtObj's RsMaCalcParams childs of tgtObj to set (1 to 6, starting from 1)
Returns: this
method importConfig(this, oCfg, maCount)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
oCfg (objProps7 type from moebius1977/CSVParser/1)
maCount (int)
method importConfig(this, oCfg, maCount)
Namespace types: HTFMAs
Parameters:
this (HTFMAs)
oCfg (objProps8 type from moebius1977/CSVParser/1)
maCount (int)
method newRsParamsMAs(this)
Namespace types: LO
Parameters:
this (LO)
method newHTFMAs(this)
Namespace types: LO
Parameters:
this (LO)
RsMaCalcParams
Parameters of one MA (only calculation params needed within req.sec(), visual parameters are within htfMAs type)
Fields:
enabled (series bool)
maType (series MaTypes) : MA type options: SMA / EMA / WMA / ...
src (series string)
prd (series int) : MA period
RsParamsMAs
Collection of parameters of 6 MAs. Used to pass params to req.sec()
Fields:
ma1CalcParams (RsMaCalcParams)
ma2CalcParams (RsMaCalcParams)
ma3CalcParams (RsMaCalcParams)
ma4CalcParams (RsMaCalcParams)
ma5CalcParams (RsMaCalcParams)
ma6CalcParams (RsMaCalcParams)
RsReturnMAs
Used to return data from req.sec().
Fields:
htfBi (series int)
ma1 (series float)
ma2 (series float)
ma3 (series float)
ma4 (series float)
ma5 (series float)
ma6 (series float)
MaDrawing
MA's plot parameters plus drawing objects for MA's current level (line and label).
Fields:
lnClr (series color) : (color) MA plot line color (like in plot())
lnWidth (series int) : (int) MA plot line width (like in plot())
lnStyle (series string) : (string) MA plot line style (like in plot())
showHistory (series bool) : (bool) Whether to plot the MA on historical bars or only show current level to the right of the latest bar.
showLabel (series bool) : (bool) Whether to show the name of the MA to the right of the MA's level
ln (series line) : (line) line to show MA"s current level
lbl (series label) : (label) label showing MA's name
HTFMAs
Contains data and drawing parameters for MA's of one timeframe (MA calculation parameters for MA's of one timeframe are in a separate object RsParamsMAs)
Fields:
rsRet (RsReturnMAs) : (RsReturnMAs) Contains data returned from req.sec(). Is set to na in between HTF bar changes if smoothing is enabled.
rsRetLast (RsReturnMAs) : (RsReturnMAs) Contains a copy of data returned from req.sec() in case rsRet is set to na for smoothing.
rsRetNaObj (RsReturnMAs) : (RsReturnMAs) An empty object as `na` placeholder
ma1Drawing (MaDrawing) : (MaDrawing) MA drawing properties
ma2Drawing (MaDrawing) : (MaDrawing) MA drawing properties
ma3Drawing (MaDrawing) : (MaDrawing) MA drawing properties
ma4Drawing (MaDrawing) : (MaDrawing) MA drawing properties
ma5Drawing (MaDrawing) : (MaDrawing) MA drawing properties
ma6Drawing (MaDrawing) : (MaDrawing) MA drawing properties
enabled (series bool) : (bool ) Enables/disables all of the MAs of one timeframe.
tf (series string) : (string) Timeframe
showHistory (series bool) : (bool ) Plot MA line on historical bars
rngAtrQ (series int) : (int ) A multiplier for atr(14). Determines a range within which the MA's will be plotted. MA's too far away will not be plotted.
showRecentBars (series int) : (int ) Only plot MA on these recent bars
smoothen (series bool) : (bool ) Smoothen MA plot. If false the same HTF value is returned on all chart bars within a HTF bar (intrabars), so the plot looks like steps.
lblsOffset (series int) : (int ) Show MA name this number of bars to the right off last bar.
lblsShow (series bool) : (bool ) Show MA name
lnOffset (series int) : (int ) Start line showing current level of the MA this number of bars to the right off the last bar.
lblSize (series string) : (string) Label size
lblStyle (series string) : (string) Label style
lblTxtAlign (series string) : (string) Label text align
bPopupLabel (series bool) : (bool ) Show current MA value as a tooltip to MA's name.
LO
LO Library object, whose only purpose is to serve as a shorthand for library name in script code.
Fields:
dummy (series string)
CSVParser█ OVERVIEW
The library contains functions for parsing and importing complex CSV configurations (with a special simple syntax) into a special hierarchical object (of type objProps ) as follows:
Functions:
parseConfig() - reads CSV text into an objProps object.
toT() - displays the contents of an objProps object in a table form, which allows to check the CSV text for syntax errors.
getPropAr() - returns objProps.arS array for child object with `prop` key in mpObj map (or na if not found)
This library is handy in allowing users to store presets for the scripts and switch between them (see, e.g., my HTF moving averages script where users can switch between several preset configuations of 24 MA's across 5 timeframes).
█ HOW THE SCRIPT WORKS.
The script works as follows:
all values read from config text are stored as strings
Nested brackets in config text create a named nested objects of objProps0, ... , objProps9 types.
objProps objects of each level have the following fields:
- array arS for storing values without names (e.g. "12, 23" will be imported into a string array arS as )
- map mpS for storing items with names (e.g. "tf = 60, length = 21" will be imported as <"tf", "60"> and <"length", "21"> pairs into mpS )
- map mpObj for storing nested objects (e.g. "TF1(tf=60, length(21,50,100))" creates a <"TF1, objProps0 object> pair in mpObj map property of the top level object (objProps) , "tf=60" is stored as <"tf", "60"> key-value pair in mpS map property of a next level object (objProps0) and "length (...)" creates a <"length", objProps1> pair in objProps0.mpObj map while length values are stored in objProps1.arS array as strings. Every opening bracket creates a next level objProps object.
If objects or properties with duplicate names are encountered only the latest is imported
(e.g. for "TF1(length(12,22)), TF1(tf=240)" only "TF1(tf=240)" will be imported
Line breaks are not regarded as part of syntax (i.e. values are imported with line breaks, you can supply
symbols "(" , ")" , "," and "=" are special characters and cannot be used within property values (with the exception of a quoted text as a value of a property as explained below)
named properties can have quoted text as their value. In that case special characters within quotation marks are regarded as normal characters. Text between "=" and opening quotation mark as well as text following the closing quotation mark and until next property value is ignored. E.g. "quote = ignored "The quote" also ignored" will be imported as <"quote", "The quote">. Quotation marks within quotes must be excaped with "\" .
if a key names happens to be a multi-line then only first line containing non-space characters (trimmed from spaces) is taken as a key.
")," or ") ," and similar do not create an empty ("") array item while ",," does. (",)" creates an "" array item)
█ CSV CONFIGURATION SYNTAX
Unnamed values: just list them comma separated and they will be imported into arS of the object of the current level.
Named values: use "=" sign as follows: "property1=value1, property2 = value2"
Value of several objects: Use brackets after the name of the object ant list all object properties within the brackets (including its child objects if necessary). E.g. "TF1(tf =60, length(21,200), TF2(tf=240, length(50,200)"
Named and unnamed values as well as objects can go in any order. E.g. "12, tf=60, 21" will be imported as follows: "12", "21" will go to arS array and <"tf", "60"> will go to mpS maP of objProps (the top level object).
You can play around and test your config text using demo in this library, just edit your text in script settings and see how it is parsed into objProps objects.
█ USAGE RECOMMENDATIONS AND SAMPLE USE
I suggest the following approach:
- create functions for your UDT which can set properties by name.
- create enumerator functions which iterates through all the property names (supplied as a const string array) and imports their values into the object
█ SAMPLE USE
A sample use of this library can be seen in my Multi-timeframe 24 moving averages + BB+SAR+Supertrend+VWAP script where settings for the MAs across many timeframes are imported from CSV configurations (presets).
█ FULL LIST OF FUNCTIONS AND PROPERTIES
nzs(_s, nz)
Like nz() but for strings. Returns `nz` arg (default = "") if _s is na.
Parameters:
_s (string)
nz (string)
method init(this)
Initializes objProps obj (creates child maps and arrays)
Namespace types: objProps
Parameters:
this (objProps)
method toT(this, nz)
Outputs objProps to string matrices for further display using autotable().
Namespace types: objProps, objProps1, ..., objProps9
Parameters:
this (objProps/objProps1/..../objProps9)
nz (string)
Returns: A tuple - value, merge and color matrix (autotable() parameters)
method parseConfig(this, s)
Reads config text into objProps (unnamed values into arS, named into mpS, sub-levels into mpObj)
Namespace types: objProps
Parameters:
this (objProps)
s (string)
method getPropArS(this, prop)
Returns a string array of values for a given property name `prop`. Looks for a key `prop` in objProps.mpObj
if finds pair returns obj.arS, otherwise returns na. Returns a reference to the original, not a copy.
Namespace types: objProps, objProps1, ..., objProps8
Parameters:
this (objProps/objProps1/..../objProps8)
prop (string)
method getPropVal(this, prop, id)
Checks if there is an array of values for property `prop` and returns its `id`'s element or na if not found
Namespace types: objProps, objProps1, ..., objProps8
Parameters:
this (objProps/objProps1/..../objProps8) : objProps object containing array of property values in a child objProp object corresponding to propertty name.
prop (string) : (string) Name of the property
id (int) : (int) Id of the element to be returned from the array pf property values
objProps9 type
Object for storing values read from CSV relating to a particular object or property name.
Fields:
mpS (map) : (map() Stores property values as pairs
arS (array) : (string ) Array of values
objProps, objProps0, ... objProps8 types
Object for storing values read from CSV relating to a particular object or property name.
Fields:
mpS (map) : (map() Stores property values as pairs
arS (array) : (string ) Array of values
mpObj (map) : (map() Stores objProps objects containing properties's data as pairs