TREND CROSSES ALERTThe crossing of moving averages can help you determine the tendency of an instrument to trade.
The script has two configurable moving averages that will help you determine the trend and then take advantage of it in your strategy.
Remember to use the alerts.
Cerca negli script per "trend"
Trend Intensity Index by ParaticaTrend Intensity Index is very strong. It can see next coming trend very early
Trend Continuation FactorTrend Continuation Factor indicator script.
This indicator was originally developed by M.H. Pee (Stocks & Commodities V. 20:3 (58-64): Trend Continuation Factor).
Trend Trigger FactorTrend Trigger Factor indicator script. This indicator was originally developed by M. H. Pee (Stocks & Commodities V.22:12 (28-36): Trend Trigger Factor).
Trend Intensity IndexTrend Intensity Index indicator script. This indicator was originally developed by M. H. Pee (06/2002 issue of Stocks and Commodities Magazine)
Trend Intensity Index [DW]This study is a simple variation of M. H. Pee's Trend Intensity Index that includes two signal lines rather than one for additional trend confirmation.
Trend-following Microprofit w/ Smart DCA BACKTESTING VERSIONCompanion to the alert script:
Tradingview doesn't like backtesting with too little capital or trade sizes less than 1 share, so the "Net Profit" number may not be accurate right off the bat. To get a better idea, change the order size or initial capital so the strategy is trading the appropriate % of initial capital. For example, if your personal capital is $2000 and you are making $100 trades, your trades are 5% of initial capital. That is roughly equivalent to the defaults using orders of 1 BTC with $100,000 capital.
Tightening the stop level will improve the Net Profit to Max Drawdown ratio, making the strategy more suitable for large trade sizes.
This script does not provide alerts for Gunbot. Find the settings you like using this strategy script, then plug those values into the alert script.
If you like this you can buy me chocolate below. Cheers!
Trend Trading StrategyThis indicator identifies trade setup for my Trend Trading Strategy. Leave a like/comments!
io-trend-follow (1.5)Trend Follow script to be used across all market instruments and timeframes.
You can display long only, short only or both signals.
version 1.5 -> Filter by EMA 200 option added
version 1.4 -> Alerts added
version 1.2 -> Only one signal per trend (default) or multiple entry signals per trend
version 1.1 -> White theme option added
Trend Volume Accumulation R1 by JustUncleLThis simple indicator shows the Accumulated Volume within the current uptrend or downtrend. The uptrend/downtrend is detected by a change in direction of the candles which works very well with Heikin Ashi and Renko charts. Alternatively you can use a Moving average direction to indicate trend direction, which should work on any candle type.
You can select between 11 different types of moving average:
SMA = Simple Moving Average.
EMA = Exponential Moving Average.
WMA = Weighted Moving Average
VWMA = Volume Weighted Moving Average
SMMA = Smoothed Simple Moving Average.
DEMA = Double Exponential Moving Average
TEMA = Triple Exponential Moving Average.
HullMA = Hull Moving Average
SSMA = Ehlers Super Smoother Moving average
ZEMA = Near Zero Lag Exponential Moving Average.
TMA = Triangular (smoothed) Simple Moving Average.
Here is a sample chart using EMA length 6 for trend Direction:
Trend Pullback Reversal TPRThe TPR(Trend Pullback Reversal) indicator forms a possible price trend with support and resistance lines. It also comes with a unqiue band and center line as additional features.
TPR works on all timeframes and all symbols and all type of bar chart.
TPR never repaints.
There are 4 Parameters:
Period: umber of bars used for calculations
Factor: Multiplier factor, small number for short trend, large number for long trend
Source: the input series, default is Close
ShowBand: enable to show band and center line
Most trend indicators have similar plot, the difference is where and when they change the direction. Unlike other trend indicators, TPR will focus on main trend and filter out most minor price movements. The green cross-line represents an uptrend, the red cross-line represents a downtrend.
The additional band and center line may look like bollinger band, but the TPR band algorithm is completely different from bollingerband. There is no standard deviation in TPR band calculation.
Trend Trader Strategy Backtest This is plots the indicator developed by Andrew Abraham
in the Trading the Trend article of TASC September 1998
You can change long to short in the Input Settings
Please, use it only for learning or paper trading. Do not for real trading.
Trend, Stoch, Price Action or in short: TSPCombining the three most important factors that a trader usually needs in a single indicator.
Red = Trend
Blue = Stoch
Orange = Price Action
Trend Trader This is plots the indicator developed by Andrew Abraham
in the Trading the Trend article of TASC September 1998
[blackcat] L3 Trendmaster XOVERVIEW
The L3 Trendmaster X is an advanced trend-following indicator meticulously crafted to assist traders in identifying and capitalizing on market trends. This sophisticated tool integrates multiple technical factors, including Average True Range (ATR), volume dynamics, and price spreads, to deliver precise buy and sell signals. By plotting dynamic trend bands directly onto the chart, it offers a comprehensive visualization of potential trend directions, enabling traders to make informed decisions swiftly and confidently 📊↗️.
FEATURES
Customizable Input Parameters: Tailor the indicator to match your specific trading needs with adjustable settings:
Trendmaster X Multiplier: Controls the sensitivity of the ATR-based levels.
Trendmaster X Period: Defines the period over which the ATR is calculated.
Window Length: Specifies the length of the moving window for standard deviation calculations.
Volume Averaging Length: Determines how many periods are considered for averaging volume.
Volatility Factor: Adjusts the impact of volatility on the trend bands.
Core Technical Metrics:
Dynamic Range: Measures the range between high and low prices within each bar.
Candle Body Size: Evaluates the difference between open and close prices.
Volume Average: Assesses the cumulative On-Balance Volume relative to the dynamic range.
Price Spread: Computes the standard deviation of the price ranges over a specified window.
Volatility Factor: Incorporates volatility into the calculation of trend bands.
Advanced Trend Bands Calculation:
Upper Level: Represents potential resistance levels derived from the ATR multiplier.
Lower Level: Indicates possible support levels using the same ATR multiplier.
High Band and Low Band: Dynamically adjust to reflect current trend directions, offering a clear view of market sentiment.
Visual Representation:
Plots distinct green and red trend lines representing bullish and bearish trends respectively.
Fills the area between these trend lines and the middle line for enhanced visibility.
Displays clear buy ('B') and sell ('S') labels on the chart for immediate recognition of trading opportunities 🏷️.
Alert System:
Generates real-time alerts when buy or sell conditions are triggered, ensuring timely action.
Allows customization of alert messages and frequencies to align with individual trading strategies 🔔.
HOW TO USE
Adding the Indicator:
Open your TradingView platform and navigate to the "Indicators" section.
Search for " L3 Trendmaster X" and add it to your chart.
Adjusting Settings:
Fine-tune the input parameters according to your preferences and trading style.
For example, increase the Trendmaster X Multiplier for higher sensitivity during volatile markets.
Decrease the Window Length for shorter-term trend analysis.
Monitoring Trends:
Observe the plotted trend bands and labels on the chart.
Look for buy ('B') labels at potential support levels and sell ('S') labels at resistance levels.
Setting Up Alerts:
Configure alerts based on the generated buy and sell signals.
Choose notification methods (e.g., email, SMS) and set alert frequencies to stay updated without constant monitoring 📲.
Combining with Other Tools:
Integrate the Trendmaster X with other technical indicators like Moving Averages or RSI for confirmation.
Utilize fundamental analysis alongside the indicator for a holistic approach to trading.
Backtesting and Optimization:
Conduct thorough backtests on historical data to evaluate performance.
Optimize parameters based on backtest results to enhance accuracy and reliability.
Real-Time Application:
Apply the optimized settings to live charts and monitor real-time signals.
Execute trades based on confirmed signals while considering risk management principles.
LIMITATIONS
Market Conditions: The indicator might produce false signals in highly volatile or sideways-trending markets due to increased noise and lack of clear direction 🌪️.
Complementary Analysis: Traders should use this indicator in conjunction with other analytical tools to validate signals and reduce the likelihood of false positives.
Asset-Specific Performance: Effectiveness can vary across different assets and timeframes; therefore, testing on diverse instruments is recommended.
NOTES
Data Requirements: Ensure adequate historical data availability for accurate calculations and reliable signal generation.
Demo Testing: Thoroughly test the indicator on demo accounts before deploying it in live trading environments to understand its behavior under various market scenarios.
Parameter Customization: Regularly review and adjust parameters based on evolving market conditions and personal trading objectives.
Advanced Multi-Timeframe Trend DetectorThis script is designed to provide a multi-timeframe trend analysis, combining moving averages (MAs) and the Relative Strength Index (RSI) to determine market direction across different timeframes. Here's a breakdown of what the script does:
Key Components of the Script
Inputs:
Moving Averages: Short and long moving average lengths (9 and 21 periods).
ATR and RSI Lengths: ATR (Average True Range) and RSI (Relative Strength Index) lengths set to 14 periods.
RSI Levels: Overbought and oversold levels for the RSI set to 70 and 30, respectively.
Trend Determination:
A function called trendDirection evaluates the trend based on the closing prices of the current and previous periods, as well as the RSI value.
It classifies the trend as "Up", "Down", or "Sideways" based on the conditions:
Up: Current close is higher than the previous close and RSI is below the overbought level.
Down: Current close is lower than the previous close and RSI is above the oversold level.
Sideways: If neither condition is met.
Table Creation:
A table is created at the bottom right of the chart to display the trend for different timeframes (5m, 15m, 60m, 240m, and Daily).
The table is initialized with headers and then populated with the trend results for each timeframe.
Calculating Trends for Each Timeframe:
The script fetches the current and previous close prices for each timeframe using request.security().
It calculates the RSI for each timeframe and then calls the trendDirection function to determine the trend.
Displaying Trends:
The results are displayed in a table format, with each timeframe and its corresponding trend.
Summary
Overall, this script provides a concise way to visualize market trends across multiple timeframes, using MAs and RSI to offer a more nuanced view of potential market movements. This can help traders make more informed decisions based on the prevailing trends.
Universal Trend Following Strategy | QuantumRsearchUniversal All Assets Strategy by Rocheur
The Universal All Assets Strategy is a cutting-edge, trend-following algorithm designed to operate seamlessly across multiple asset classes, including equities, commodities, forex, and cryptocurrencies. This strategy leverages the power of eight unique indicators, offering traders robust, adaptive signals. Its dynamic logic, combined with a comprehensive risk management framework, allows for precision trading in a variety of market conditions.
Core Methodologies and Features
1. Eight Integrated Trend Indicators
At the heart of the Universal All Assets Strategy are eight sophisticated trend-following indicators, each designed to capture different facets of market behavior. These indicators work together to provide a multi-dimensional analysis of price trends, filtering out noise and reacting only to significant movements:
Directional Moving Averages : Tracks the primary market trend, offering a clear indication of long-term price direction, ideal for identifying sustained upward or downward movements.
Smoothed Moving Averages : Reduces short-term volatility and noise to reveal the underlying trend, enhancing signal clarity and helping traders avoid reacting to temporary price spikes.
RSI Loops : Utilizes the Relative Strength Index (RSI) to assess market momentum, using a unique for loop mechanism to smooth out data and enhance precision.
Supertrend Filters : This indicator dynamically adjusts to market volatility, closely following price action to detect significant breakouts or reversals. The Supertrend is a core component for identifying shifts in trend direction with minimal lag.
RVI for Loop : The Relative Volatility Index (RVI) measures the strength of market volatility. It is optimized with a for loop mechanism, which smooths out the data and improves directional cues, especially in choppy or sideways markets.
Hull for Loop : The Hull Moving Average is designed to minimize lag while offering a smooth, responsive trend line. The for loop mechanism further enhances this by making the Hull even more sensitive to trend shifts, ensuring faster reaction to market movements without generating excessive noise.
These indicators evaluate market conditions independently, assigning a score of 1 for bullish trends and -1 for bearish trends. The average score across all eight indicators is calculated for each time frame (or bar), and this score determines whether the strategy should enter, exit, or remain neutral in a trade.
2. Scoring and Signal Confirmation
The strategy’s confirmation system ensures that trades are initiated only when there is strong alignment across multiple indicators:
A Long Position (Buy) is initiated when the majority of indicators generate a bullish signal, i.e., the average score exceeds a predefined upper threshold.
A Short Position or Exit is triggered when the average score falls below a lower threshold, signaling a bearish trend or neutral market.
By using a majority-rule confirmation system, the strategy filters out weak signals, reducing the chances of reacting to market noise or false positives. This ensures that only robust trends—those supported by multiple indicators—trigger trades.
Adaptive Logic for All Asset Classes
The Universal All Assets Strategy stands out for its ability to adapt dynamically across different asset classes. Whether it’s applied to highly volatile assets like cryptocurrencies or more stable instruments like equities, the strategy fine-tunes its behavior to match the asset’s volatility profile and price behavior.
Volatility Filters : The system incorporates volatility-sensitive filters, such as the Average True Range (ATR) and standard deviation metrics, which dynamically adjust its sensitivity based on market conditions. This ensures the strategy remains responsive to significant price movements while filtering out inconsequential fluctuations.
This adaptability makes the Universal All Assets Strategy effective across diverse markets, providing consistent performance whether the market is trending, range-bound, or experiencing high volatility.
Customization and Flexibility
1. Directional Bias
The strategy offers traders the flexibility to set a customizable directional bias, allowing it to focus on:
Long-only trades during bullish markets.
Short-only trades during bear markets.
Bi-directional trades for those looking to capitalize on both uptrends and downtrends.
This bias can be fine-tuned based on market conditions, trader preference, or risk tolerance, without compromising the integrity of the overall signal-generation process.
2. Volatility Sensitivity
Traders can adjust the strategy’s volatility sensitivity through customizable settings. By modifying how the system reacts to volatility, traders can make the strategy more aggressive in high-volatility environments or more conservative in quieter markets, depending on their individual trading style.
Visual Representation of Component Behavior
One of the unique features of the strategy is its real-time visual representation of the eight indicators through a component table displayed on the chart. This table provides a clear overview of the current status of each indicator:
A score of 1 indicates a bullish signal.
A score of -1 indicates a bearish signal.
The table is updated at each time frame (bar), showing how each indicator is contributing to the overall trend decision. This real-time feedback allows traders to monitor the exact composition of the strategy’s signal, helping them better understand market dynamics.
Oscillator Visualization for Trend Detection
To complement the component table, the strategy includes a trend oscillator displayed beneath the price chart, offering a visual summary of the overall market direction:
Green bars represent bullish trends when the majority of indicators signal an uptrend.
Red bars represent bearish trends or a neutral (cash) position when the majority of indicators detect a downtrend.
This oscillator allows traders to quickly assess the market’s overall direction at a glance, without needing to analyze each individual indicator, providing a clear and immediate visual of the market trend.
Backtested and Forward-Tested for Real-World Conditions
The Universal All Assets Strategy has been thoroughly tested under real-world trading conditions, incorporating key factors like:
Slippage : Set at 20 ticks to represent real market fluctuations.
Order Size : Calculated as 10% of equity, ensuring appropriate risk exposure for realistic capital management.
Commission : A fee of 0.05% has been factored in to account for trading costs.
These settings ensure that the strategy’s performance metrics—such as the Sortino Ratio , Sharpe Ratio , Omega Ratio , and Profit Factor —are reflective of actual trading environments. The rigorous backtesting and forward-testing processes ensure that the strategy produces realistic results, making it compatible with the markets it is written for and demonstrating how the system would behave in live conditions. It also includes robust risk management tools to minimize drawdowns and preserve capital, making it suitable for both professional and retail traders.
Anti-Fragile Design and Realistic Expectations
The Universal All Assets Strategy is engineered to be anti-fragile, thriving in volatile markets by adjusting to turbulence rather than being damaged by it. This is a crucial feature that ensures the strategy remains effective even during times of significant market instability.
Moreover, the strategy is transparent about realistic expectations, acknowledging that no system can guarantee a 100% win rate and that past performance is not indicative of future results. This transparency fosters trust and provides traders with a realistic framework for long-term success, making it an ideal choice for traders looking to navigate complex market conditions with confidence.
Acknowledgment of External Code
Special credit goes to bii_vg, whose invite-only code was used with permission in the development of the Universal All Assets Strategy. Their contributions have been instrumental in refining certain aspects of this strategy, ensuring its robustness and adaptability across various markets.
Conclusion
The Universal All Assets Strategy by Rocheur offers traders a powerful, adaptable tool for capturing trends across a wide range of asset classes. Its eight-indicator confirmation system, combined with customizable settings and real-time visual representations, provides a comprehensive solution for traders seeking precision, flexibility, and consistency. Whether used in high-volatility markets or more stable environments, the strategy’s dynamic adaptability, transparent logic, and robust testing make it an excellent choice for traders aiming to maximize performance while managing risk effectively.
cphelperLibrary "cphelper"
ACPU helper library - for private use. Not so meaningful for others.
calculate_rr(targetArray, rrArray, breakevenOnTarget1)
calculates risk reward for given targets
Parameters:
targetArray (float ) : array of targets
rrArray (float ) : array of risk reward
breakevenOnTarget1 (simple bool) : option to breakeven
Returns: array rrArray
trendPairs(l1StartX, l1StartY, l1EndX, l1EndY, l2StartX, l2StartY, l2EndX, l2EndY, zgColor)
creates trendline pairs
Parameters:
l1StartX (int) : startX of first line
l1StartY (float) : startY of first line
l1EndX (int) : endX of first line
l1EndY (float) : endY of first line
l2StartX (int) : startX of second line
l2StartY (float) : startY of second line
l2EndX (int) : endX of second line
l2EndY (float) : endY of second line
zgColor (color) : line color
Returns:
find_type(l1t, l2t, channelThreshold)
Finds type based on trendline pairs
Parameters:
l1t (line) : line1
l2t (line) : line2
channelThreshold (simple float) : theshold for channel identification
Returns: pattern type and flags
getFlags(flags)
Flatten flags
Parameters:
flags (bool ) : array of flags
Returns: - flattened flags isChannel, isTriangle, isWedge, isExpanding, isContracting, isFlat, isRising, isFalling
getType(typeNum)
Get type based on type number
Parameters:
typeNum (int) : number representing type
Returns: String value of type
getStatus(status, maxStatus)
Get status based on integer value representations
Parameters:
status (int) : integer representing current status
maxStatus (int) : integer representing max status
Returns: String status value
calculate_simple_targets(trendLines, settingsMatrix, patternTypeMapping, patternType)
Calculate targets based on trend lines
Parameters:
trendLines (line ) : trendline pair array
settingsMatrix (matrix) : matrix containing settings
patternTypeMapping (string ) : array containing pattern type mapping
patternType (int) : pattern type
Returns: arrays containing long and short calculated targets
recalculate_position(patternTypeAndStatusMatrix, targetMatrix, index, pIndex, status, maxStatus, targetValue, stopValue, dir, breakevenOnTarget1)
Recalculate position values
Parameters:
patternTypeAndStatusMatrix (matrix) : matrix containing pattern type and status
targetMatrix (matrix) : matrix containing targets
index (int) : current index
pIndex (int) : pattern index
status (int) : current status
maxStatus (int) : max status reached
targetValue (float) : current target value
stopValue (float) : current stop value
dir (int) : direction
breakevenOnTarget1 (simple bool) : flag to breakeven upon target1
Returns: new status and maxStatus values
draw_targets(longTargets, shortTargets, index, labelColor, patternName, positionIndex, longMaxStatus, longStatus, shortMaxStatus, shortStatus, tempBoxes, tempLines, tempLabels)
Draw targets on chart
Parameters:
longTargets (matrix) : matrix containing long targets
shortTargets (matrix) : matrix containing short targets
index (int) : current index
labelColor (color) : color of lines and labels
patternName (string) : Pattern name
positionIndex (int) : position on the chart
longMaxStatus (int) : max status for long
longStatus (int) : long status value
shortMaxStatus (int) : max status for short
shortStatus (int) : short status value
tempBoxes (box ) : temporary box array
tempLines (line ) : temporary lines array
tempLabels (label ) : temporary labels array
Returns: void
populate_open_stats(patternIdArray, barMatrix, patternTypeAndStatusMatrix, patternColorArray, longTargets, shortTargets, patternRRMatrix, OpenStatPosition, lblSizeOpenTrades)
Populate open stats table
Parameters:
patternIdArray (int ) : pattern Ids
barMatrix (matrix) : matrix containing bars
patternTypeAndStatusMatrix (matrix) : matrix containing pattern type and status
patternColorArray (color ) : array containing current patter colors
longTargets (matrix) : matrix of long targets
shortTargets (matrix) : matrix of short targets
patternRRMatrix (matrix) : pattern risk reward matrix
OpenStatPosition (simple string) : table position
lblSizeOpenTrades (simple string) : text size
Returns: void
draw_pattern_label(trendLines, patternFlagMatrix, patternTypeAndStatusMatrix, patternColorArray, patternFlags, patternLabelArray, zgColor, patternType, drawLabel, clearOldPatterns, safeRepaint, maxPatternsReference)
Parameters:
trendLines (line )
patternFlagMatrix (matrix)
patternTypeAndStatusMatrix (matrix)
patternColorArray (color )
patternFlags (bool )
patternLabelArray (label )
zgColor (color)
patternType (int)
drawLabel (simple bool)
clearOldPatterns (simple bool)
safeRepaint (simple bool)
maxPatternsReference (simple int)
populate_closed_stats(patternTypeAndStatusMatrix, bullishCounts, bearishCounts, bullishRetouchCounts, bearishRetouchCounts, bullishSizeMatrix, bearishSizeMatrix, bullishRR, bearishRR, ClosedStatsPosition, lblSizeClosedTrades, showSelectivePatternStats, showPatternStats, showStatsInPercentage)
Parameters:
patternTypeAndStatusMatrix (matrix)
bullishCounts (matrix)
bearishCounts (matrix)
bullishRetouchCounts (matrix)
bearishRetouchCounts (matrix)
bullishSizeMatrix (matrix)
bearishSizeMatrix (matrix)
bullishRR (matrix)
bearishRR (matrix)
ClosedStatsPosition (simple string)
lblSizeClosedTrades (simple string)
showSelectivePatternStats (simple bool)
showPatternStats (simple bool)
showStatsInPercentage (simple bool)
reversalchartpatternsLibrary "reversalchartpatterns"
User Defined Types and Methods for reversal chart patterns - Double Top, Double Bottom, Triple Top, Triple Bottom, Cup and Handle, Inverted Cup and Handle, Head and Shoulders, Inverse Head and Shoulders
method delete(this)
Deletes the drawing components of ReversalChartPatternDrawing object
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method delete(this)
Deletes the drawing components of ReversalChartPattern object. In turn calls the delete of ReversalChartPatternDrawing
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method lpush(this, obj, limit, deleteOld)
Array push with limited number of items in the array. Old items are deleted when new one comes and exceeds the limit
Namespace types: array
Parameters:
this (array) : array object
obj (ReversalChartPattern) : ReversalChartPattern object which need to be pushed to the array
limit (int) : max items on the array. Default is 10
deleteOld (bool) : If set to true, also deletes the drawing objects. If not, the drawing objects are kept but the pattern object is removed from array. Default is false.
Returns: current ReversalChartPattern object
method draw(this)
Draws the components of ReversalChartPatternDrawing
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method draw(this)
Draws the components of ReversalChartPatternDrawing within the ReversalChartPattern object.
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method scan(zigzag, patterns, errorPercent, shoulderStart, shoulderEnd, allowedPatterns, offset)
Scans zigzag for ReversalChartPattern occurences
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from Trendoscope/Zigzag/11) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patterns (array) : Existing patterns array. Used for validating duplicates
errorPercent (float) : Error threshold for considering ratios. Default is 13
shoulderStart (float) : Starting range of shoulder ratio. Used for identifying shoulders, handles and necklines
shoulderEnd (float) : Ending range of shoulder ratio. Used for identifying shoulders, handles and necklines
allowedPatterns (array) : array of int containing allowed pattern types
offset (int) : Offset of zigzag to consider only confirmed pivots
Returns: int pattern type
method createPattern(zigzag, patternType, patternColor, properties, offset)
Create Pattern from ZigzagTypes.Zigzag object
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from Trendoscope/Zigzag/11) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patternType (int) : Type of pattern being created. 1 - Double Tap, 2 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders
patternColor (color) : Color in which the patterns are drawn
properties (ReversalChartTradeProperties)
offset (int)
Returns: ReversalChartPattern object created
method getName(this)
get pattern name of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string name of the pattern
method getDescription(this)
get consolidated description of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string consolidated description
method init(this)
initializes the ReversalChartPattern object and creates sub object types
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: ReversalChartPattern current object
ReversalChartPatternDrawing
Type which holds the drawing objects for Reversal Chart Pattern Types
Fields:
patternLines (array type from Trendoscope/Drawing/2) : array of Line objects representing pattern
entry (Line type from Trendoscope/Drawing/2) : Entry price Line
targets (array type from Trendoscope/Drawing/2)
stop (Line type from Trendoscope/Drawing/2) : Stop price Line
patternLabel (Label type from Trendoscope/Drawing/2)
ReversalChartTradeProperties
Trade properties of ReversalChartPattern
Fields:
riskAdjustment (series float) : Risk Adjustment for calculation of stop
useFixedTarget (series bool) : Boolean flag saying use fixed target type wherever possible. If fixed target type is not possible, then risk reward/fib ratios are used for calculation of targets
variableTargetType (series int) : Integer value which defines whether to use fib based targets or risk reward based targets. 1 - Risk Reward, 2 - Fib Ratios
variableTargetRatios (array) : Risk reward or Fib Ratios to be used for calculation of targets when fixed target is not possible or not enabled
entryPivotForWm (series int) : which Pivot should be considered as entry point for WM patterns. 0 refers to the latest breakout pivot where as 5 refers to initial pivot of the pattern
ReversalChartPattern
Reversal Chart Pattern master type which holds the pattern components, drawings and trade details
Fields:
pivots (array type from Trendoscope/Zigzag/11) : Array of Zigzag Pivots forming the pattern
patternType (series int) : Defines the main type of pattern 1 - Double Tap, 1 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders, 5- W/M Patterns, 6 - Full Trend, 7 - Half Trend
patternColor (series color) : Color in which the pattern will be drawn on chart
properties (ReversalChartTradeProperties)
drawing (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object which holds the drawing components
trade (Trade type from Trendoscope/TradeTracker/1) : TradeTracker.Trade object holding trade components
Market Structure - HH, HL, LH, LL with Trendlines & AlertsMarket Structure Script – HH, HL, LH, LL with Trendlines & Alerts
This Pine Script is designed to help identify key market structure patterns such as Higher Highs (HH), Higher Lows (HL), Lower Highs (LH), and Lower Lows (LL) on price charts. It also draws trendlines connecting the respective swing points and provides alerts when these important price patterns occur.
Key Features:
Swing High and Low Detection:
The script uses the ta.pivothigh and ta.pivotlow functions to identify significant swing highs and swing lows based on the pivot length (pivotLen). These points mark local peaks and troughs in the price action.
Dynamic Pivot Length:
The script adjusts the pivotLen (which defines the number of bars used to calculate swing points) based on the current timeframe of the chart. For example, for a 15-minute chart, it uses a pivot length of 5 bars, while for a daily chart, it uses 10 bars. This dynamic adjustment ensures that the script works across different timeframes.
Higher Highs (HH), Higher Lows (HL), Lower Highs (LH), Lower Lows (LL):
Higher High (HH): Identifies a price peak that is higher than the previous swing high, indicating an uptrend.
Higher Low (HL): Identifies a price trough that is higher than the previous swing low, supporting the idea of an ongoing uptrend.
Lower High (LH): Identifies a price peak that is lower than the previous swing high, suggesting a potential reversal or downtrend.
Lower Low (LL): Identifies a price trough that is lower than the previous swing low, indicating a downtrend.
Trendlines:
For each identified Higher High, Higher Low, Lower High, or Lower Low, the script automatically draws a trendline connecting the corresponding swing points. These trendlines provide a visual representation of the market’s price structure, showing support and resistance levels.
Labels:
The script places labels on the chart next to the respective swing points. These labels mark whether the point is a Higher High (HH), Higher Low (HL), Lower High (LH), or Lower Low (LL). This helps traders easily visualize the price pattern at a glance.
Alerts:
Alert conditions are set for when a Higher High (HH), Higher Low (HL), Lower High (LH), or Lower Low (LL) is detected. Users can set up alerts to be notified whenever one of these key market structure patterns forms. Alerts are an essential feature for traders who want to act quickly when important trend changes are happening.
TrendLibrary "Trend"
calculateSlopeTrend(source, length, thresholdMultiplier)
Parameters:
source (float)
length (int)
thresholdMultiplier (float)
Purpose:
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
Parameters:
`source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
`length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
`thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
Calculation Steps:
Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`:
If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
Return Value:
The function returns an integer representing the determined trend direction:
`1`: Upward trend
`-1`: Downward trend
`0`: Flat trend
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
Future Trend Indicator (FTI)Future Trend Indicator (FTI)
The Future Trend Indicator (FTI) is a versatile and innovative tool designed to analyze market trends, smooth out noise, and provide a forward-looking forecast of potential price movements. Built with advanced features such as polynomial regression, EMA smoothing, confidence bands, and cross-validation metrics, this indicator offers a comprehensive approach for traders to gain insights into future price trends while maintaining realistic error margins.
Key Features:
Exponential Moving Average (EMA) Integration
The FTI incorporates a user-configurable EMA to smooth out short-term price fluctuations and highlight the overall market trend. This provides a stable and reliable reference for assessing price action.
Noise Reduction via Median Filter
To improve signal clarity, the source data is processed using a Median Filter, effectively reducing the impact of outliers and market noise. This ensures that the forecast focuses on meaningful price movements.
Polynomial Regression Forecast
A polynomial regression model is used to project future price movements based on historical data. This advanced statistical approach models potential non-linear trends, offering a sophisticated and adaptive forecast for the next specified period.
Confidence Bands for Forecast Accuracy
Upper and lower confidence bands are calculated using standard deviation, visually representing the potential error margin around the forecast. This feature provides traders with an understanding of the forecast's reliability and the expected price range.
Dynamic Visualization
The indicator uses visually appealing and intuitive plotting techniques:
A forecast line dynamically shifts based on polynomial regression and historical data.
Confidence bands are displayed with semi-transparent green (upper) and red (lower) shading for quick visual interpretation.
The EMA is displayed as a blue line for smooth trend observation.
Cross-Validation with RMSE (Root Mean Square Error)
The indicator includes an error metric to measure the accuracy of its forecast against actual future price movements. The RMSE is displayed as a yellow label on the chart, helping traders evaluate the forecast's historical precision.
Flexible Data Source
By default, the FTI uses hlc3 (the average of high, low, and close prices) as its source, providing a balanced view of market activity. Traders can easily customize this input to suit their preferences.
Forecast Customization
Users can configure the length of the forecast, moving average, and EMA to tailor the indicator to different trading styles and timeframes.
EMA Length
Purpose: Smoothens the price action to identify the primary trend.
Recommendation:
Short-term traders (scalping/day trading): Use a shorter EMA length (e.g., 10 or 20) to make the indicator more responsive to recent price movements.
Medium-term traders (swing trading): Use a moderate EMA length (e.g., 50) to capture broader trends while avoiding short-term noise.
Long-term traders (position trading): Use a longer EMA length (e.g., 100 or 200) to focus on the dominant trend over a longer period.
Default Value: 20
Moving Average Length
Purpose: Used in trend calculations to smooth out data further.
Recommendation:
Similar to the EMA, shorter lengths provide faster signals but are more sensitive to noise, while longer lengths offer smoother signals but may lag.
For crypto or forex (volatile markets): Start with 10 to 20.
For stocks or indices (less volatile): Use 20 to 50 for more stable trends.
Default Value: 10
Forecast Length
Purpose: Determines how many bars into the future the indicator projects.
Recommendation:
Short-term trading: Use a smaller forecast length (e.g., 50) to project near-term price movements.
Medium- to long-term trading: Use a higher value (e.g., 100 to 200) to focus on longer-term forecasts.
Keep in mind that longer forecasts tend to have greater uncertainty. Confidence bands (enabled in this script) will widen as the forecast length increases, reflecting higher error potential.
Default Value: 100