MA Ratio Weighted Trend System I [InvestorUnknown]The MA Ratio Weighted Trend System I combines slow and fast indicators to identify stable trends and capture potential market turning points. By dynamically adjusting the weight of fast indicators based on the Moving Average Ratio (MAR), the system aims to provide timely entry and exit signals while maintaining overall trend stability through slow indicators.
Slow and Fast Indicators with Dynamic Weighting
Slow Indicators: Designed for stable trend identification, these indicators maintain a constant weight in the overall signal calculation. They include:
DMI For Loop (Directional Movement Index)
CCI For Loop (Commodity Channel Index)
Aroon For Loop
Fast Indicators: Aim to detect rapid market changes and potential turning points. Their weights are dynamically adjusted based on the absolute value of the Moving Average Ratio (MAR). Fast indicators include:
ZLEMA For Loop (Zero-Lag Exponential Moving Average)
IIRF For Loop (Infinite Impulse Response Filter)
Dynamic Weighting Mechanism:
Moving Average Ratio (MAR) is calculated as the ratio of the price to its moving average, minus one (for simplicity and visualization).
Weight Calculation
Fast indicator weights are determined based on the absolute value of MAR, possibly with an offset to avoid scenarios where MAR follows rapid price reversals too closely:
// Function to calculate weights based on MAR
f_mar_weights(series float mar, simple int offset, simple float weight_thre) =>
o_mar = math.abs(mar )
float fast_weight = 0
float slow_weight = 1
if o_mar != 0
if weight_thre > 0
if o_mar <= weight_thre
fast_weight := o_mar
else
fast_weight := o_mar
Threshold-Based vs. Continuous Weighting:
Threshold-Based: Fast indicators receive weight only when the absolute MAR exceeds a user-defined threshold (weight_thre).
Continuous: By setting weight_thre to zero, fast indicators always receive some weight, though this may increase false signals.
Offset Mechanism
The offset parameter shifts the MAR used for weighting by a certain number of bars. This helps avoid situations where the MAR follows sudden price movements too closely, preventing fast indicators from failing to provide timely exit signals.
Signal Calculation
The final signal is a weighted average of the slow and fast indicators:
// Calculate Signal (as weighted average)
float sig = math.round(((DMI*slow_w) + (CCI*slow_w) + (Aroon*slow_w) + (ZLEMA*fast_w) + (IIRF*fast_w)) / (3*slow_w + 2*fast_w), 2)
Backtesting and Performance Metrics
Enables users to test the indicator's performance over historical data, comparing it to a buy-and-hold strategy.
Alerts
Set up alerts for when the signal crosses above or below the thresholds.
alertcondition(long_alert, "LONG (MAR Weighted Trend System)", "MAR Weighted Trend System flipped ⬆LONG⬆")
alertcondition(short_alert, "SHORT (MAR Weighted Trend System)", "MAR Weighted Trend System flipped ⬇Short⬇")
Important Notes
Customization: Due to the experimental nature of this indicator, users are strongly encouraged to adjust and calibrate the settings to align with their trading strategies and market conditions.
Default Settings Disclaimer: The default settings are not optimized or recommended for any specific use and serve only as placeholders for the indicator's publication.
Backtest Results Disclaimer: Historical backtest results are not indicative of future performance. Market conditions change, and past results do not guarantee future outcomes.
Statistics
Manual Trading Checklist by Afnan TajuddinHey traders! This Trading Checklist indicator like your personal to-do list right on your chart! Here’s what it does:
Easy Tracking: Seven checkboxes to make sure you’ve done all your trading steps.
Colorful Signs: Green "✔" for done stuff and red "✘" for things you need to fix.
Make It Yours: Change where the table is on the chart, pick your favorite colors, and set the text size just how you like it.
Simple Setup: Rename the checklist items and toggle them on or off in the settings.
Clean Look: It stays neat on your chart without messing things up.
Whether you’re just starting out or you’ve been trading for a while, this checklist helps you stay organized and stick to your plan. Perfect for anyone who loves keeping things tidy and on track!
Important to Know: This checklist is not dynamic or automatic and not specific to any symbol. You need to manually check it every time for all the stocks you’re planning to trade. It won’t do the checking for you, so make sure to update it yourself! 🚨
Sharpe Ratio Z-ScoreThe "Sharpe Ratio Z-Score" indicator is a powerful tool designed to measure risk-adjusted returns in financial assets. This script helps investors evaluate the performance of a security relative to its risk, using a Z-score based modification of the Sharpe Ratio. The indicator is suitable for assessing market environments and understanding periods of underperformance or overperformance relative to historical standards.
Features:
Risk Assessment and Scaling: The indicator calculates a modified version of the Sharpe Ratio
over a user-defined period. By using scaling and mean offset adjustments, it allows for better
fitting to different market conditions.
Customizable Settings:
Period Length: The number of bars used to calculate the Sharpe Ratio.
Mean Adjustment: Offset value to adjust the average return of the calculated Sharpe ratio.
Scale Factor: A multiplier for emphasizing or reducing the calculated score's impact.
Line Color: Easily customize the plot's appearance.
Visual Cues:
Plots horizontal lines and fills specific regions to visually represent significant Z-score levels.
Highlighted zones include risk thresholds, such as overbought (positive Z-scores) and oversold
(negative Z-scores) areas, using intuitive color fills:
Green for areas below -0.5 (potential buy opportunities).
Red for areas above 0.5 (potential sell opportunities).
Yellow for neutral zones between -0.5 and 0.5.
Use Cases:
Risk-Adjusted Decision Making: Understand when returns are favorable compared to risk, especially during volatile market conditions.
Timing Reversion to Mean: Use highlighted zones to identify potential reversion-to-mean scenarios.
Trend Analysis: Identify times when an asset's performance is significantly deviating from its
average risk-adjusted return.
How It Works:
The script computes the daily returns over a set period, calculates the standard deviation of
those returns, and then applies a modified Sharpe Ratio approach. The Z-score transformation
helps to visualize how far an asset's risk-adjusted return deviates from its historical average.
This "Sharpe Ratio Z-Score" indicator is well-suited for investors seeking to combine quantitative metrics with visual cues, enhancing decision-making for long and short positions while maintaining a risk-adjusted perspective.
Conditional Value at Risk (CVaR)This Pine Script implements the Conditional Value at Risk (CVaR), a risk metric that evaluates the potential losses in a financial portfolio beyond a certain confidence level, incorporating both the Value at Risk (VaR) and the expected loss given that the VaR threshold has been breached.
Key Features:
Input Parameters:
length: Defines the observation period in days (default is 252, typically used to represent the number of trading days in a year).
confidence: Specifies the confidence interval for calculating VaR and CVaR, with values between 0.5 and 0.99 (default is 0.95, indicating a 95% confidence level).
Logarithmic Returns Calculation: The script computes the logarithmic returns based on the daily closing prices, a common method to measure financial asset returns, given by:
Log Return=ln(PtPt−1)
Log Return=ln(Pt−1Pt)
where PtPt is the price at time tt, and Pt−1Pt−1 is the price at the previous time point.
VaR Calculation: Value at Risk (VaR) is estimated as the percentile of the returns array corresponding to the given confidence interval. This represents the maximum loss expected over a given time horizon under normal market conditions at the specified confidence level.
CVaR Calculation: The Conditional VaR (CVaR) is calculated as the average of the returns that fall below the VaR threshold. This represents the expected loss given that the loss has exceeded the VaR threshold.
Visualization: The script plots two key risk measures:
VaR: The maximum potential loss at the specified confidence level.
CVaR: The average of the losses beyond the VaR threshold.
The script also includes a neutral line at zero to help visualize the losses and their magnitude.
Source and Scientific Background:
The concept of Value at Risk (VaR) was popularized by J.P. Morgan in the 1990s, and it has since become a widely-used tool for risk management (Jorion, 2007). Conditional Value at Risk (CVaR), also known as Expected Shortfall, addresses the limitation of VaR by considering the severity of losses beyond the VaR threshold (Rockafellar & Uryasev, 2002). CVaR provides a more comprehensive risk measure, especially in extreme tail risk scenarios.
References:
Jorion, P. (2007). Value at Risk: The New Benchmark for Managing Financial Risk. McGraw-Hill Education.
Rockafellar, R.T., & Uryasev, S. (2002). Conditional Value-at-Risk for General Loss Distributions. Journal of Banking & Finance, 26(7), 1443–1471.
Volume-Based Bar ColorThis indicator changes the bar color if the bar has more than a specified amount of volume. Best use case would be to apply it to a tick chart (ex: 500 Tick) and set the volume threshold to say 590-600 volume. This would show you visually where and when 18-20% more volume than required was in a candle. That candle can then be used to identify volume based zones where buys and sellers may be in control. Works well with volume profile.
Intraday new day marker/seperator - IndiaJust marks the first candle of a new day . to be used in intraday charts
RHR_CANDLELibrary "RHR_CANDLE"
Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator based on Jake Bernstein’s principles of Moving Average Channel system.
calc(shortLookback, longLookback)
Calculates Expansion Contraction values.
Parameters:
shortLookback (int) : Integer for the short lookback calculation, defaults to 8
longLookback (int) : Integer for the long lookback calculation, defaults to 32
@return Returns array of Expansion Contraction values
stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong, stdevLookback)
Calculates standard deviation lines based on Expansion Contraction Long and Short values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
stdevLookback (int) : Integer for the standard deviation lookback, defaults to 500
@return Returns array of standard deviation values
trend(positiveShort, negativeShort, positiveLong, negativeLong)
Determines if trend is strong or weak based on Expansion Contraction values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
@return Returns array of boolean values indicating strength or weakness of trend
COT Report Indicator with Speculator Net PositionsThe COT Report Indicator with Speculator Net Positions is designed to give traders insights into the behavior of large market participants, particularly speculators, based on the Commitment of Traders (COT) report data. This indicator visualizes the long and short positions of non-commercial traders, allowing users to gauge the sentiment and positioning of large speculators in key markets, such as Gold, Silver, Crude Oil, S&P 500, and currency pairs like EURUSD, GBPUSD, and others.
The indicator provides three essential components:
Net Long Position (Green) - Displays the total long positions held by speculators.
Net Short Position (Purple) - Shows the total short positions held by speculators.
Net Difference (Long - Short) (Yellow) - Illustrates the difference between long and short positions, helping users identify whether speculators are more bullish or bearish on the asset.
Recommended Timeframes:
Best Timeframes: Weekly and Monthly
The COT report data is released on a weekly basis, making higher timeframes like the Weekly and Monthly charts ideal for this indicator. These timeframes provide a more accurate reflection of the underlying trends in speculator positioning, avoiding the noise present in lower timeframes.
How to Use:
Market Sentiment: Use this indicator to gauge the sentiment of large speculators, who often drive market trends. A strong net long position can indicate bullish sentiment, while a high net short position might suggest bearish sentiment.
Trend Reversal Signals: Sudden changes in the net difference between long and short positions may indicate potential trend reversals.
Confirmation Tool: Pair this indicator with your existing analysis to confirm the strength of a trend or identify overbought/oversold conditions based on speculator activity.
Supported Symbols:
This indicator currently supports a range of commodities and currency pairs, including:
Gold ( OANDA:XAUUSD )
Silver ( OANDA:XAGUSD )
Crude Oil ( TVC:USOIL )
Natural Gas ( NYMEX:NG1! )
S&P 500 ( SP:SPX )
Dollar Index ( TVC:DXY )
EURUSD ( FX:EURUSD )
GBPUSD ( FX:GBPUSD )
GBPJPY( FX:GBPJPY )
By providing clear insight into the positions of large speculators, this indicator is a powerful tool for traders looking to align with institutional sentiment and enhance their trading strategy.
Financial X-RayThe Financial X-Ray is an advanced indicator designed to provide a thorough analysis of a company's financial health and market performance. Its primary goal is to offer investors and analysts a quick yet comprehensive overview of a company's financial situation by combining various key financial ratios and metrics.
How It Works
Data Collection: The indicator automatically extracts a wide range of financial data for the company, covering aspects such as financial strength, profitability, valuation, growth, and operational efficiency.
Sector-Specific Normalization: A unique feature of this indicator is its ability to normalize metrics based on the company's industry sector. This approach allows for more relevant comparisons between companies within the same sector, taking into account industry-specific characteristics.
Standardized Scoring: Each metric is converted to a score on a scale of 0 to 10, facilitating easy comparison and rapid interpretation of results.
Multidimensional Analysis: The indicator doesn't focus on just one financial dimension but offers an overview by covering several crucial aspects of a company's performance.
Fair Value Calculation: Using financial data and market conditions, the indicator provides an estimate of the company's fair value, offering a reference point for assessing current valuation.
Visual Presentation: Results are displayed directly on the TradingView chart in a tabular format, allowing for quick and efficient reading of key information.
Advantages for Users
Time-Saving: Instead of manually collecting and analyzing numerous financial data points, users get an instant comprehensive overview.
Contextual Analysis: Sector-specific normalization allows for a better understanding of the company's performance relative to its peers.
Flexibility: Users can choose which metrics to display, customizing the analysis to their specific needs.
Objectivity: By relying on quantitative data and standardized calculations, the indicator offers an objective perspective on the company's financial health.
Decision Support: The fair value estimate and normalized scores provide valuable reference points for investment decision-making.
Customization and Evolution
One of the major strengths of this indicator is its open-source nature. Users can modify the code to adjust normalization methods, add new metrics, or adapt the display to their preferences. This flexibility allows the indicator to evolve and continuously improve through community contributions.
In summary, the Financial X-Ray is a powerful tool that combines automation, contextual analysis, and customization to provide investors with a clear and comprehensive view of companies' financial health, facilitating informed decision-making in financial markets.
This Financial X-Ray indicator is provided for informational and educational purposes only. It should not be considered as financial advice or a recommendation to buy or sell any security. The data and calculations used in this indicator may not be accurate or up-to-date. Users should always conduct their own research and consult with a qualified financial advisor before making any investment decisions. The creator of this indicator is not responsible for any losses or damages resulting from its use.
Fed Fund Futures Custom AverageThis indicator helps traders track the expected average interest rate for the upcoming 12 months based on Fed Fund Futures. It calculates the average price of the next 12 monthly futures contracts and also shows the spread against the 1-Year US Treasury yield (US01Y). This can be useful for understanding market expectations regarding interest rate changes and identifying trading opportunities related to interest rate movements.
BarRange StrategyHello,
This is a long-only, volatility-based strategy that analyzes the range of the previous bar (high - low).
If the most recent bar’s range exceeds a threshold based on the last X bars, a trade is initiated.
You can customize the lookback period, threshold value, and exit type.
For exits, you can choose to exit after X bars or when the close price exceeds the previous bar’s high.
The strategy is designed for instruments with a long-term upward-sloping curves, such as ES1! or NQ1!. It may not perform well on other instruments.
Commissions are set to $2.50 per side ($5.00 per round trip).
Recommended timeframes are 1h and higher. With adjustments to the lookback period and threshold, it could potentially achieve similar results on lower timeframes as well.
Z Value AlertZ Value Alert analyzes daily price movements by evaluating fluctuations relative to historical volatility. It calculates the daily percentage change in the closing price, the average of this change over 252 days, and the standard deviation. Using these values, a Z-Score is calculated, indicating how much the current price change deviates from the historical range of fluctuations.
The user can set a threshold in standard deviations (Z-Score). When the absolute Z-Score exceeds this threshold, a significant movement is detected, indicating increased volatility. The Z-Score is visualized as a histogram, and an alert can be triggered when a significant movement occurs.
The number of trading days used to calculate historical volatility is adjustable, allowing the Sigma Move Alert to be tailored to various trading strategies and analysis periods.
Additionally, a dropdown option for the calculation method is available in the input menu, allowing the user to select between:
Normal: Calculates the percentage change in closing prices without using the logarithm.
Logarithmic: Uses the natural logarithm of daily returns. This method is particularly suitable for longer timeframes and scientific analyses, as logarithmic returns are additive.
These comprehensive features allow for precise customization of the Sigma Move Alert to individual needs and specific market conditions.
lib_momentumLibrary "lib_momentum"
This library calculates the momentum, derived from a sample range of prior candles. Depending on set MomentumType it either deduces the momentum from the price, volume, or a product of both. If price/product are selected, you can choose from SampleType if only candle body, full range from high to low or a combination of both (body counts full, wicks half for each direction) should be used. Optional: You can choose to normalize the results, dividing each value by its average (normalization_ma_length, normalization_ma). This will allow comparison between different instruments. For the normalization Moving Average you can choose any currently supported in my lib_no_delay.
get_momentum(momentum_type, sample_type, sample_length, normalization_ma_length, normalization_ma)
Parameters:
momentum_type (series MomentumType) : select one of MomentumType. to sample the price, volume or a product of both
sample_type (series SampleType) : select one of SampleType. to sample the body, total range from high to low or a combination of both (body count full, wicks half for each direction)
sample_length (simple int) : how many candles should be sampled (including the current)
normalization_ma_length (simple int) : if you want to normalize results (momentum / momentum average) this sets the period for the average. (default = 0 => no normalization)
normalization_ma (simple MovingAverage enum from robbatt/lib_no_delay/9) : is the type of moving average to normalize / compare with
Returns: returns the current momentum where the total line is not just (up - down) but also sampled over the sample_length and can therefore be used as trend indicator. If up/down fail to reach total's level it's a sign of decreasing momentum, if up/down exceed total the trend it's a sign of increasing momentum.
Position Size Calculator by Dr. Rahul Ware.Position Size Calculator
The Position Size Calculator script helps traders determine the optimal position size for their trades based on their account balance, risk percentage, and stop loss parameters. It calculates the number of shares to buy and the total position size in INR (Indian Rupees), providing a clear and concise way to manage risk effectively.
Key Features:
Account Balance Input: Specify your account balance in INR to tailor the position size calculations to your specific trading capital.
Risk Percentage Input: Define the percentage of your account balance you are willing to risk on each trade, ensuring you stay within your risk tolerance.
Stop Loss Options: Choose between using a fixed stop loss price or a stop loss percentage to calculate the risk amount per share.
Dynamic Stop Loss Line: The script plots a red dotted line representing the stop loss price on the chart, updating dynamically for the last bar.
Comprehensive Table Display: View key metrics, including account balance, risk percentage, amount at risk, current price, stop loss price, stop loss percentage, position size in INR, and the number of shares to buy, all in a neatly formatted table.
This tool is designed to enhance your trading strategy by providing precise position sizing, helping you manage risk effectively and make informed trading decisions. Use this script to optimize your trade sizes and improve your overall trading performance.
Machine Learning RSI [BackQuant]Machine Learning RSI
The Machine Learning RSI is a cutting-edge trading indicator that combines the power of Relative Strength Index (RSI) with Machine Learning (ML) clustering techniques to dynamically determine overbought and oversold thresholds. This advanced indicator adapts to market conditions in real-time, offering traders a robust tool for identifying optimal entry and exit points with increased precision.
Core Concept: Relative Strength Index (RSI)
The RSI is a well-known momentum oscillator that measures the speed and change of price movements, oscillating between 0 and 100. Typically, RSI values above 70 are considered overbought, and values below 30 are considered oversold. However, static thresholds may not be effective in all market conditions.
This script enhances the RSI by integrating a dynamic thresholding system powered by Machine Learning clustering, allowing it to adapt thresholds based on historical RSI behavior and market context.
Machine Learning Clustering for Dynamic Thresholds
The Machine Learning (ML) component uses clustering to calculate dynamic thresholds for overbought and oversold levels. Instead of relying on fixed RSI levels, this indicator clusters historical RSI values into three groups using a percentile-based initialization and iterative optimization:
Cluster 1: Represents lower RSI values (typically associated with oversold conditions).
Cluster 2: Represents mid-range RSI values.
Cluster 3: Represents higher RSI values (typically associated with overbought conditions).
Dynamic thresholds are determined as follows:
Long Threshold: The upper centroid value of Cluster 3.
Short Threshold: The lower centroid value of Cluster 1.
This approach ensures that the indicator adapts to the current market regime, providing more accurate signals in volatile or trending conditions.
Smoothing Options for RSI
To further enhance the effectiveness of the RSI, this script allows traders to apply various smoothing methods to the RSI calculation, including:
Simple Moving Average (SMA)
Exponential Moving Average (EMA)
Weighted Moving Average (WMA)
Hull Moving Average (HMA)
Linear Regression (LINREG)
Double Exponential Moving Average (DEMA)
Triple Exponential Moving Average (TEMA)
Adaptive Linear Moving Average (ALMA)
T3 Moving Average
Traders can select their preferred smoothing method and adjust the smoothing period to suit their trading style and market conditions. The option to smooth the RSI reduces noise and makes the indicator more reliable for detecting trends and reversals.
Long and Short Signals
The indicator generates long and short signals based on the relationship between the RSI value and the dynamic thresholds:
Long Signals: Triggered when the RSI crosses above the long threshold, signaling bullish momentum.
Short Signals: Triggered when the RSI falls below the short threshold, signaling bearish momentum.
These signals are dynamically adjusted to reflect real-time market conditions, making them more robust than static RSI signals.
Visualization and Clustering Insights
The Machine Learning RSI provides an intuitive and visually rich interface, including:
RSI Line: Plotted in real-time, color-coded based on its position relative to the dynamic thresholds (green for long, red for short, gray for neutral).
Dynamic Threshold Lines: The script plots the long and short thresholds calculated by the ML clustering process, providing a clear visual reference for overbought and oversold levels.
Cluster Plots: Each RSI cluster is displayed with distinct colors (green, orange, and red) to give traders insights into how RSI values are grouped and how the dynamic thresholds are derived.
Customization Options
The Machine Learning RSI is highly customizable, allowing traders to tailor the indicator to their preferences:
RSI Settings : Adjust the RSI length, source price, and smoothing method to match your trading strategy.
Threshold Settings : Define the range and step size for clustering thresholds, allowing you to fine-tune the clustering process.
Optimization Settings : Control the performance memory, maximum clustering steps, and maximum data points for ML calculations to ensure optimal performance.
UI Settings : Customize the appearance of the RSI plot, dynamic thresholds, and cluster plots. Traders can also enable or disable candle coloring based on trend direction.
Alerts and Automation
To assist traders in staying on top of market movements, the script includes alert conditions for key events:
Long Signal: When the RSI crosses above the long threshold.
Short Signal: When the RSI crosses below the short threshold.
These alerts can be configured to notify traders in real-time, enabling timely decisions without constant chart monitoring.
Trading Applications
The Machine Learning RSI is versatile and can be applied to various trading strategies, including:
Trend Following: By dynamically adjusting thresholds, this indicator is effective in identifying and following trends in real-time.
Reversal Trading: The ML clustering process helps identify extreme RSI levels, offering reliable signals for reversals.
Range-Bound Trading: The dynamic thresholds adapt to market conditions, making the indicator suitable for trading in sideways markets where static thresholds often fail.
Final Thoughts
The Machine Learning RSI represents a significant advancement in RSI-based trading indicators. By integrating Machine Learning clustering techniques, this script overcomes the limitations of static thresholds, providing dynamic, adaptive signals that respond to market conditions in real-time. With its robust visualization, customizable settings, and alert capabilities, this indicator is a powerful tool for traders seeking to enhance their momentum analysis and improve decision-making.
As always, thorough backtesting and integration into a broader trading strategy are recommended to maximize the effectiveness!
52 Week High/Low Tracking TableThis Indicator helps the User to Quickly view Current Closing Price Compared to the Mentioned Period High and Low.
"Bars Back" indicate the period you need to look back. In case of Daily charts 260 Bars Back usually indicate 52 Weeks/1 year. This is set a default. But you can change it as well.
The Indicator will show the data for below:-
1) High - Highest Close price for the Mentioned Period
2) % from High - The Percentage difference between the Current Close Price Vs Highest Close price for the Mentioned Period. (-) indicate that the current close price is lesser then then High Price.
3) Low - Lowest Close price for the Mentioned Period
4) % from Low - The Percentage difference between the Current Close Price Vs Highest Close price for the Mentioned Period. (-) indicate that the current close price is lesser then then High Price.
You can add this indicator to Quickly Scan multiple stocks to see were they stand.
TrigWave Suite [InvestorUnknown]The TrigWave Suite combines Sine-weighted, Cosine-weighted, and Hyperbolic Tangent moving averages (HTMA) with a Directional Movement System (DMS) and a Relative Strength System (RSS).
Hyperbolic Tangent Moving Average (HTMA)
The HTMA smooths the price by applying a hyperbolic tangent transformation to the difference between the price and a simple moving average. It also adjusts this value by multiplying it by a standard deviation to create a more stable signal.
// Function to calculate Hyperbolic Tangent
tanh(x) =>
e_x = math.exp(x)
e_neg_x = math.exp(-x)
(e_x - e_neg_x) / (e_x + e_neg_x)
// Function to calculate Hyperbolic Tangent Moving Average
htma(src, len, mul) =>
tanh_src = tanh((src - ta.sma(src, len)) * mul) * ta.stdev(src, len) + ta.sma(src, len)
htma = ta.sma(tanh_src, len)
Sine-Weighted Moving Average (SWMA)
The SWMA applies sine-based weights to historical prices. This gives more weight to the central data points, making it responsive yet less prone to noise.
// Function to calculate the Sine-Weighted Moving Average
f_Sine_Weighted_MA(series float src, simple int length) =>
var float sine_weights = array.new_float(0)
array.clear(sine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.sin((math.pi * (i + 1)) / length)
array.push(sine_weights, weight)
// Normalize the weights
sum_weights = array.sum(sine_weights)
for i = 0 to length - 1
norm_weight = array.get(sine_weights, i) / sum_weights
array.set(sine_weights, i, norm_weight)
// Calculate Sine-Weighted Moving Average
swma = 0.0
if bar_index >= length
for i = 0 to length - 1
swma := swma + array.get(sine_weights, i) * src
swma
Cosine-Weighted Moving Average (CWMA)
The CWMA uses cosine-based weights for data points, which produces a more stable trend-following behavior, especially in low-volatility markets.
f_Cosine_Weighted_MA(series float src, simple int length) =>
var float cosine_weights = array.new_float(0)
array.clear(cosine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.cos((math.pi * (i + 1)) / length) + 1 // Shift by adding 1
array.push(cosine_weights, weight)
// Normalize the weights
sum_weights = array.sum(cosine_weights)
for i = 0 to length - 1
norm_weight = array.get(cosine_weights, i) / sum_weights
array.set(cosine_weights, i, norm_weight)
// Calculate Cosine-Weighted Moving Average
cwma = 0.0
if bar_index >= length
for i = 0 to length - 1
cwma := cwma + array.get(cosine_weights, i) * src
cwma
Directional Movement System (DMS)
DMS is used to identify trend direction and strength based on directional movement. It uses ADX to gauge trend strength and combines +DI and -DI for directional bias.
// Function to calculate Directional Movement System
f_DMS(simple int dmi_len, simple int adx_len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, dmi_len)
plus = fixnan(100 * ta.rma(plusDM, dmi_len) / trur)
minus = fixnan(100 * ta.rma(minusDM, dmi_len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_len)
dms_up = plus > minus and adx > minus
dms_down = plus < minus and adx > plus
dms_neutral = not (dms_up or dms_down)
signal = dms_up ? 1 : dms_down ? -1 : 0
Relative Strength System (RSS)
RSS employs RSI and an adjustable moving average type (SMA, EMA, or HMA) to evaluate whether the market is in a bullish or bearish state.
// Function to calculate Relative Strength System
f_RSS(rsi_src, rsi_len, ma_type, ma_len) =>
rsi = ta.rsi(rsi_src, rsi_len)
ma = switch ma_type
"SMA" => ta.sma(rsi, ma_len)
"EMA" => ta.ema(rsi, ma_len)
"HMA" => ta.hma(rsi, ma_len)
signal = (rsi > ma and rsi > 50) ? 1 : (rsi < ma and rsi < 50) ? -1 : 0
ATR Adjustments
To minimize false signals, the HTMA, SWMA, and CWMA signals are adjusted with an Average True Range (ATR) filter:
// Calculate ATR adjusted components for HTMA, CWMA and SWMA
float atr = ta.atr(atr_len)
float htma_up = htma + (atr * atr_mult)
float htma_dn = htma - (atr * atr_mult)
float swma_up = swma + (atr * atr_mult)
float swma_dn = swma - (atr * atr_mult)
float cwma_up = cwma + (atr * atr_mult)
float cwma_dn = cwma - (atr * atr_mult)
This adjustment allows for better adaptation to varying market volatility, making the signal more reliable.
Signals and Trend Calculation
The indicator generates a Trend Signal by aggregating the output from each component. Each component provides a directional signal that is combined to form a unified trend reading. The trend value is then converted into a long (1), short (-1), or neutral (0) state.
Backtesting Mode and Performance Metrics
The Backtesting Mode includes a performance metrics table that compares the Buy and Hold strategy with the TrigWave Suite strategy. Key statistics like Sharpe Ratio, Sortino Ratio, and Omega Ratio are displayed to help users assess performance. Note that due to labels and plotchar use, automatic scaling may not function ideally in backtest mode.
Alerts and Visualization
Trend Direction Alerts: Set up alerts for long and short signals
Color Bars and Gradient Option: Bars are colored based on the trend direction, with an optional gradient for smoother visual feedback.
Important Notes
Customization: Default settings are experimental and not intended for trading/investing purposes. Users are encouraged to adjust and calibrate the settings to optimize results according to their trading style.
Backtest Results Disclaimer: Please note that backtest results are not indicative of future performance, and no strategy guarantees success.
RSI Wave Function Ultimate OscillatorEnglish Explanation of the "RSI Wave Function Ultimate Oscillator" Pine Script Code
Understanding the Code
Purpose:
This Pine Script code creates a custom indicator that combines the Relative Strength Index (RSI) with a wave function to potentially provide more nuanced insights into market dynamics.
Key Components:
* Wave Function: This is a custom calculation that introduces a sinusoidal wave component to the price data. The frequency parameter controls the speed of the oscillation, and the decay factor determines how quickly the influence of past prices diminishes.
* Smoothed Signal: The wave function is applied to the closing price to create a smoothed signal, which is essentially a price series modulated by a sine wave.
* RSI: The traditional RSI is then calculated on this smoothed signal, providing a measure of the speed and change of price movements relative to recent price changes.
Calculation Steps:
* Wave Function Calculation:
* A sinusoidal wave is generated based on the bar index and the frequency parameter.
* The wave is combined with the closing price using a weighted average, where the decay factor determines the weight given to previous values.
* RSI Calculation:
* The RSI is calculated on the smoothed signal using a standard RSI formula.
* Plotting:
* The RSI values are plotted on a chart, along with horizontal lines at 70 and 30 to indicate overbought and oversold conditions.
* The area between the RSI line and the overbought/oversold lines is filled with color to visually represent the market condition.
Interpretation and Usage
* Wave Function: The wave function introduces cyclical patterns into the price data, which can help identify potential turning points or momentum shifts.
* RSI: The RSI provides a measure of the speed and change of price movements relative to recent price changes. When applied to the smoothed signal, it can help identify overbought and oversold conditions, as well as potential divergences between price and momentum.
* Combined Indicator: The combination of the wave function and RSI aims to provide a more sensitive and potentially earlier indication of market reversals.
* Signals:
* Crossovers: Crossovers of the RSI line above or below the overbought/oversold lines can be used to generate buy or sell signals.
* Divergences: Divergences between the price and the RSI can indicate a weakening trend.
* Oscillations: The amplitude and frequency of the oscillations in the RSI can provide insights into the strength and duration of market trends.
How it Reflects Market Volatility
* Amplified Volatility: The wave function can amplify the volatility of the price data, making it easier to identify potential turning points.
* Smoothing: The decay factor helps to smooth out short-term fluctuations, allowing the indicator to focus on longer-term trends.
* Sensitivity: The combination of the wave function and RSI can make the indicator more sensitive to changes in market momentum.
In essence, this custom indicator attempts to enhance traditional RSI analysis by incorporating a cyclical component that can potentially provide earlier signals of market reversals.
Note: The effectiveness of this indicator will depend on various factors, including the specific market, time frame, and the chosen values for the frequency and decay parameters. It is recommended to conduct thorough backtesting and optimize the parameters to suit your specific trading strategy.
Average Bullish & Bearish Percentage ChangeAverage Bullish & Bearish Percentage Change
Processes two key aspects of directional market movements relative to price levels. Unlike traditional momentum tools, it separately calculates the average of positive and negative percentage changes in price using user-defined independent counts of actual past bullish and bearish candles. This approach delivers comprehensive and precise view of average percentage changes.
FEATURES:
Count-Based Averages: Separate averaging of bullish and bearish %𝜟 based on their respective number of occurrences ensures reliable and precise momentum calculations.
Customizable Averaging: User-defined number of candle count sets number of past bullish and bearish candles used in independent averaging.
Two Methods of Candle Metrics:
1. Net Move: Focuses on the body range of the candle, emphasizing the net directional movement.
2. Full Capacity: Incorporates wicks and gaps to capture full potential of the bar.
The indicator classifies Doji candles contextually, ensuring they are appropriately factored into the bullish or bearish metrics to avoid mistakes in calculation:
1. Standard Doji - open equals close.
2. Flat Close Doji - Candles where the close matches the previous close.
Timeframe Flexibility:
The indicator can be applied across any desired timeframe, allowing for seamless multi-timeframe analysis.
HOW TO USE
Select Method of Bar Metrics:
Net Move: For analyzing markets where price changes are consistent and bars are close to each other.
Full Capacity: Incorporates wicks and gaps, providing relevant figures for markets like stocks
Set the number of past candles to average:
🟩 Average Past Bullish Candles (Default: 10)
🟥 Average Past Bullish Candles (Default: 10)
Why Percentage Change Is Important
Standardized Measurement Across Assets:
Percentage change normalizes price movements, making it easier to compare different assets with varying price levels. For example, a $1 move in a $10 stock is significant, but the same $1 move in a $1,000 stock is negligible.
Highlights Relative Impact:
By measuring the price change as a percentage of the close, traders can better understand the relative impact of a move on the asset’s overall value.
Volatility Insights:
A high percentage change indicates heightened volatility, which can be a signal of potential opportunities or risks, making it more actionable than raw price changes. Percents directly reflect the strength of buying or selling pressure, providing a clearer view of momentum compared to raw price moves, which may not account for the relative size of the move.
By focusing on percentage change, this indicator provides a normalized, actionable, and insightful measure of market momentum, which is critical for comparing, analyzing, and acting on price movements across various assets and conditions.
Sequence Waves [OmegaTools]the sequence waves indicator, developed by omegatools, is a multi-functional tool designed to detect trends, sequences, and potential reversal signals based on price movements and volume. this indicator has two main modes, "trend" and "sequence," which determine how the indicator calculates directional changes. additional enhancements in this version include reversal signals, allowing users to identify potential long and short opportunities with specific entry cues.
input parameters
mode (mode): chooses the calculation basis for directional movement.
- "trend": uses a midline calculated from the highest high and lowest low over the "trend mode length" period to assess if the price is in an upward or downward trend.
- "sequence": compares the current price to the closing price of the previous "sequence mode length" period to detect shifts in direction.
counter mode (modec): sets whether the counter increments by a fixed amount (1 or -1) or the volume of the bar, impacting the indicator’s sensitivity.
- "fixed": increments or decrements the counter by 1.
- "volume": increments or decrements based on the period’s volume, making the indicator more responsive to high-volume periods.
percentile length (lntp): defines the lookback period for calculating overbought and oversold thresholds using a percentile method. shorter lengths make ob/os levels more reactive.
sensitivity (sens): controls the percentile-based ob/os thresholds, ranging from 10 to 100. higher values narrow ob/os zones, while lower values widen them, impacting signal frequency.
trend mode length (lnt1): sets the period length for midline calculation in trend mode, defaulting to 21. longer periods smooth the midline for detecting major trends.
sequence mode length (lnt2): sets the lookback period in sequence mode, with a default of 4. shorter lengths capture more frequent directional changes, while longer lengths smooth signals.
visual colors:
- up color (upc): sets the color for upward movements.
- down color (dnc): sets the color for downward movements.
calculation logic
midline calculation: in trend mode, a midline is derived from the average of the highest high and lowest low over the "trend mode length" period, acting as a reference to detect upward or downward movements.
counter calculation:
- in trend mode, if the close price is above the midline, the counter increases (or volume if volume mode is selected). it decreases when the price is below.
- in sequence mode, the counter increases if the close is above the closing price from "sequence mode length" periods ago and decreases if below.
the counter resets to zero on direction changes, creating clear directional transitions.
overbought/oversold percentiles: separate arrays track the counter’s values each time the direction changes, creating historical up and down values. ob and os thresholds are dynamically determined based on these arrays, with sizes limited by the percentile length and sensitivity inputs.
reversal signals: two new variables, "long" and "short," detect potential reversal points when the counter crosses specific thresholds:
- long: a long signal is generated when the counter switches to positive and exceeds the down percentile.
- short: a short signal is triggered when the counter switches to negative and exceeds the up percentile.
visual and display elements
counter plot: plots the counter value on the chart with color-coded columns, making it easy to spot directional momentum.
up and down percentiles: displays overbought (up percentile) and oversold (down percentile) thresholds to identify potential reversal zones.
regime background: the background color changes based on market regime:
- bullish (up percentile > down percentile): greenish background.
- bearish (down percentile > up percentile): reddish background.
- neutral (both percentiles equal): grayish background.
reversal signals: plotted as small triangles on the chart for visual confirmation of potential long (triangle up) and short (triangle down) reversal signals.
obs background: changes color when the counter exceeds ob or os thresholds, creating a visual cue for extreme market conditions:
- overbought: background changes to a faint down color.
- oversold: background changes to a faint up color.
status table: displayed on the right side of the chart, providing real-time status information:
- status: shows "overbought," "oversold," "long," "short," or "none" based on the current counter position.
- regime: indicates whether the market is in a "bullish," "bearish," or "neutral" state based on the percentile comparison.
- percentile up/down: displays the current up and down percentiles for quick reference.
how to use the indicator
trend following: in trend mode, use the midline-based counter to gauge if the market is in an uptrend (positive counter) or downtrend (negative counter).
reversal detection: the ob/os thresholds assist in identifying potential reversal points. when the counter exceeds the up percentile, it may indicate an overbought state, suggesting a bearish reversal. similarly, dropping below the down percentile may indicate an oversold state, suggesting a bullish reversal.
entry signals: use the long and short reversal signals for potential entry points, particularly in trending or range-bound markets. these signals are indicated by up and down triangles.
sequence trading: in sequence mode, the indicator tracks shorter-term directional shifts, making it suitable for detecting smaller momentum patterns based on recent price comparisons.
volume sensitivity: selecting volume mode enhances sensitivity to high-volume moves, allowing it to detect stronger market activity in both trend and sequence modes.
the sequence waves indicator is suited to both short-term and long-term traders. it allows for detailed trend analysis, reversal detection, and dynamic ob/os signals. the inclusion of visual reversal cues makes it a flexible tool adaptable to a variety of trading strategies.
Low Price VolatilityI highlighted periods of low price volatility in the Nikkei 225 futures trading.
It is Japan Standard Time (JST)
This script is designed to color-code periods in the Nikkei 225 futures market according to times when prices tend to be more volatile and times when they are less volatile. The testing period is from March 11, 2024, to November 1, 2024. It identifies periods and counts where price movement exceeded half of the ATR, and colors are applied based on this data. There are no calculations involved; it simply uses the results of the analysis to apply color.
Volume Bars [jpkxyz]
Multi-Timeframe Volume indicator by @jpkxyz
This script is a Multi-Timeframe Volume Z-Score Indicator. It dynamically calculates /the Z-Score of volume over different timeframes to assess how significantly current
volume deviates from its historical average. The Z-Score is computed for each
timeframe independently and is based on a user-defined lookback period. The
script switches between timeframes automatically, adapting to the chart's current
timeframe using `timeframe.multiplier`.
The Z-Score formula used is: (current volume - mean) / standard deviation, where
mean and standard deviation are calculated over the lookback period.
The indicator highlights periods of "significant" and "massive" volume by comparing
the Z-Score to user-specified thresholds (`zScoreThreshold` for significant volume
and `massiveZScoreThreshold` for massive volume). The script flags buy or sell
conditions based on whether the current close is higher or lower than the open.
Visual cues:
- Dark Green for massive buy volume.
- Red for massive sell volume.
- Green for significant buy volume.
- Orange for significant sell volume.
- Gray for normal volume.
The script also provides customizable alert conditions for detecting significant or massive buy/sell volume events, allowing users to set real-time alerts.