Half Trend Regression [AlgoAlpha]Introducing the Half Trend Regression indicator by AlgoAlpha, a cutting-edge tool designed to provide traders with precise trend detection and reversal signals. This indicator uniquely combines linear regression analysis with ATR-based channel offsets to deliver a dynamic view of market trends. Ideal for traders looking to integrate statistical methods into their analysis to improve trade timing and decision-making.
Key Features
🎨 Customizable Appearance : Adjust colors for bullish (green) and bearish (red) trends to match your charting preferences.
🔧 Flexible Parameters : Configure amplitude, channel deviation, and linear regression length to tailor the indicator to different time frames and trading styles.
📈 Dynamic Trend Line : Utilizes linear regression of high, low, and close prices to calculate a trend line that adapts to market movements.
🚀 Trend Direction Signals : Provides clear visual signals for potential trend reversals with plotted arrows on the chart.
📊 Adaptive Channels : Incorporates ATR-based channel offsets to account for market volatility and highlight potential support and resistance zones.
🔔 Alerts : Set up alerts for bullish or bearish trend changes to stay informed of market shifts in real-time.
How to Use
🛠 Add the Indicator : Add the Half Trend Regression indicator to your chart from the TradingView library. Access the settings to customize parameters such as amplitude, channel deviation, and linear regression length to suit your trading strategy.
📊 Analyze the Trend : Observe the plotted trend line and the filled areas under it. A green fill indicates a bullish trend, while a red fill indicates a bearish trend.
🔔 Set Alerts : Use the built-in alert conditions to receive notifications when a trend reversal is detected, allowing you to react promptly to market changes.
How It Works
The Half Trend Regression indicator calculates linear regression lines for the high, low, and close prices over a specified period to determine the general direction of the market. It then computes moving averages and identifies the highest and lowest points within these regression lines to establish a dynamic trend line. The trend direction is determined by comparing the moving averages and previous price levels, updating as new data becomes available. To account for market volatility, the indicator calculates channels above and below the trend line, offset by a multiple of half the Average True Range (ATR). These channels help visualize potential support and resistance zones. The area under the trend line is filled with color corresponding to the current trend direction—green for bullish and red for bearish. When the trend direction changes, the indicator plots arrows on the chart to signal a potential reversal, and alerts can be set up to notify you. By integrating linear regression and ATR-based channels, the indicator provides a comprehensive view of market trends and potential reversal points, aiding traders in making informed decisions.
Enhance your trading strategy with the Half Trend Regression indicator by AlgoAlpha and gain a statistical edge in the markets! 🌟📊
Linear
Alpine Predictive BandsAlpine Predictive Bands - ADX & Trend Projection is an advanced indicator crafted to estimate potential price zones and trend strength by integrating dynamic support/resistance bands, ADX-based confidence scoring, and linear regression-based price projections. Designed for adaptive trend analysis, this tool combines multi-timeframe ADX insights, volume metrics, and trend alignment for improved confidence in trend direction and reliability.
Key Calculations and Components:
Linear Regression for Price Projection:
Purpose: Provides a trend-based projection line to illustrate potential price direction.
Calculation: The Linear Regression Centerline (LRC) is calculated over a user-defined lookbackPeriod. The slope, representing the rate of price movement, is extended forward using predictionLength. This projected path only appears when the confidence score is 70% or higher, revealing a white dotted line to highlight high-confidence trends.
Adaptive Prediction Bands:
Purpose: ATR-based bands offer dynamic support/resistance zones by adjusting to volatility.
Calculation: Bands are calculated using the Average True Range (ATR) over the lookbackPeriod, multiplied by a volatilityMultiplier to adjust the width. These shaded bands expand during higher volatility, guiding traders in identifying flexible support/resistance zones.
Confidence Score (ADX, Volume, and Trend Alignment):
Purpose: Reflects the reliability of trend projections by combining ADX, volume status, and EMA alignment across multiple timeframes.
ADX Component: ADX values from the current timeframe and two higher timeframes assess trend strength on a broader scale. Strong ADX readings across timeframes boost the confidence score.
Volume Component: Volume strength is marked as “High” or “Low” based on a moving average, signaling trend participation.
Trend Alignment: EMA alignment across timeframes indicates “Bullish” or “Bearish” trends, confirming overall trend direction.
Calculation: ADX, volume, and trend alignment integrate to produce a confidence score from 0% to 100%. When the score exceeds 70%, the white projection line is activated, underscoring high-confidence trend continuations.
User Guide
Projection Line: The white dotted line, which appears only when the confidence score is 70% or higher, highlights a high-confidence trend.
Prediction Bands: Adaptive bands provide potential support/resistance zones, expanding with market volatility to help traders visualize price ranges.
Confidence Score: A high score indicates a stronger, more reliable trend and can support trend-following strategies.
Settings
Prediction Length: Determines the forward length of the projection.
Lookback Period: Sets the data range for calculating regression and ATR.
Volatility Multiplier: Adjusts the width of bands to match volatility levels.
Disclaimer: This indicator is for educational purposes and does not guarantee future price outcomes. Additional analysis is recommended, as trading carries inherent risks.
Linear Regression ChannelLinear Regression Channel Indicator
Overview:
The Linear Regression Channel Indicator is a versatile tool designed for TradingView to help traders visualize price trends and potential reversal points. By calculating and plotting linear regression channels, bands, and future projections, this indicator provides comprehensive insights into market dynamics. It can highlight overbought and oversold conditions, identify trend direction, and offer visual cues for future price movements.
Key Features:
Linear Regression Bands:
Input: Plot Linear Regression Bands
Description: Draws bands based on linear regression calculations, representing overbought and oversold levels.
Customizable Parameters:
Length: Defines the look-back period for the regression calculation.
Deviation: Determines the width of the bands based on standard deviations.
Linear Regression Channel:
Input: Plot Linear Regression Channel
Description: Plots a channel using linear regression to visualize the main trend.
Customizable Parameters:
Channel Length: Defines the look-back period for the channel calculation.
Deviation: Determines the channel's width.
Future Projection Channel:
Input: Plot Future Projection of Linear Regression
Description: Projects a linear regression channel into the future, aiding in forecasting potential price movements.
Customizable Parameters:
Length: Defines the look-back period for the projection calculation.
Deviation: Determines the width of the projected channel.
Arrow Direction Indicator:
Input: Plot Arrow Direction
Description: Displays directional arrows based on future projection, indicating expected price movement direction.
Color-Coded Price Bars:
Description: Colors the price bars based on their position within the regression bands or channel, providing a heatmap-like visualization.
Dynamic Visualization:
Colors: Uses a gradient color scheme to highlight different conditions, such as uptrend, downtrend, and mid-levels.
Labels and Markers: Plots visual markers for significant price levels and conditions, enhancing interpretability.
Usage Notes
Setting the Length:
Adjust the look-back period (Length) to suit the timeframe you are analyzing. Shorter lengths are responsive to recent price changes, while longer lengths provide a broader view of the trend.
Interpreting Bands and Channels:
The bands and channels help identify overbought and oversold conditions. Price moving above the upper band or channel suggests overbought conditions, while moving below the lower band or channel indicates oversold conditions.
Using the Future Projection:
Enable the future projection channel to anticipate potential price movements. This can be particularly useful for setting target prices or stop-loss levels based on expected trends.
Arrow Direction Indicator:
Use the arrow direction indicator to quickly grasp the expected price movement direction. An upward arrow indicates a potential uptrend, while a downward arrow suggests a potential downtrend.
Color-Coded Price Bars:
The color of the price bars changes based on their relative position within the regression bands or channel. This heatmap visualization helps quickly identify bullish, bearish, and neutral conditions.
Dynamic Adjustments:
The indicator dynamically adjusts its visual elements based on user settings and market conditions, ensuring that the most relevant information is always displayed.
Visual Alerts:
Pay attention to the labels and markers on the chart indicating significant events, such as crossovers and breakouts. These visual alerts help in making informed trading decisions.
The Linear Regression Channel Indicator is a powerful tool for traders looking to enhance their technical analysis. By offering multiple regression-based visualizations and customizable parameters, it helps identify key market conditions, trends, and potential reversal points. Whether you are a day trader or a long-term investor, this indicator can provide valuable insights to improve your trading strategy.
Periodic Linear Regressions [LuxAlgo]The Periodic Linear Regressions (PLR) indicator calculates linear regressions periodically (similar to the VWAP indicator) based on a user-set period (anchor).
This allows for estimating underlying trends in the price, as well as providing potential supports/resistances.
🔶 USAGE
The Periodic Linear Regressions indicator calculates a linear regression over a user-selected interval determined from the selected "Anchor Period".
The PLR can be visualized as a regular linear regression (Static), with a fit readjusting for new data points until the end of the selected period, or as a moving average (Rolling), with new values obtained from the last point of a linear regression fitted over the calculation interval. While the static method line is prone to repainting, it has value since it can further emphasize the linearity of an underlying trend, as well as suggest future trend directions by extrapolating the fit.
Extremities are included in the indicator, these are obtained from the root mean squared error (RMSE) between the price and calculated linear regression. The Multiple setting allows the users to control how far each extremity is from the other.
Periodic Linear Regressions can be helpful in finding support/resistance areas or even opportunities when ranging in a channel.
The anchor - where a new period starts - can be shown (in this case in the top right corner).
The shown bands can be visualized by enabling Show Extremities in settings ( Rolling or Static method).
The script includes a background gradient color option for the bands, which only applies when using the Rolling method.
The indicator colors can be suggestive of the detected trend and are determined as follows:
Method Rolling: a gradient color between red and green indicates the trend; more green if the output is rising, suggesting an uptrend, and more red if it is decreasing, suggesting a downtrend.
Method Static: green if the slope of the line is positive, suggesting an uptrend, red if negative, suggesting a downtrend.
🔶 DETAILS
🔹 Anchor Type
When the Anchor Type is set to Periodic , the indicator will be reset when the "Anchor Period" changes, after which calculations will start again.
An anchored rolling line set at First Bar won't reset at a new session; it will continue calculating the linear regression from the first bar to the last; in other words, every bar is included in the calculation. This can be useful to detect potential long-term tops/bottoms.
Note that a linear regression needs at least two values for its calculation, which explains why you won't see a static line at the first bar of the session. The rolling linear regression will only show from the 3rd bar of the session since it also needs a previous value.
🔹 Rolling/Static
When Anchor Type is set at Periodic , a linear regression is calculated between the first bar of the chosen session and the current bar, aiming to find the line that best fits the dataset.
The example above shows the lines drawn during the session. The offered script, though, shows the last calculated point connected to the previous point when the Rolling method is chosen, while the Static method shows the latest line.
Note that linear regression needs at least two values, which explains why you won't see a static line at the first bar of the session. The rolling line will only show from the 3rd bar of the session since it also needs a previous value.
🔶 SETTINGS
Method: Indicator method used, with options: "Static" (straight line) / "Rolling" (rolling linear regression).
Anchor Type: "Periodic / First Bar" (the latter works only when "Method" is set to "Rolling").
Anchor Period: Only applicable when "Anchor Type" is set at "Periodic".
Source: open, high, low, close, ...
Multiple: Alters the width of the bands when "Show Extremities" is enabled.
Show Extremities: Display one upper and one lower extremity.
🔹 Color Settings
Mono Color: color when "Bicolor" is disabled
Bicolor: Toggle on/off + Colors
Gradient: Background color when "Show extremities" is enabled + level of gradient
🔹 Dashboard
Show Dashboard
Location of dashboard
Text size
FVG Price & Volume Graph [LuxAlgo]The FVG Price & Volume Graph tool plot recently detected fair value gaps relative to the volume traded within their area during their formation. This allows us to effectively visualize significant fair value gaps caused by high liquidity.
The indicator also returns levels from the fair value gaps areas average with the highest associated volume.
Do note that the indicator can consider the chart's visible range when being computed, which will recalculate the indicator when the chart's visible range changes.
🔶 USAGE
Fair Value Gaps (FVG) are core price action concepts occurring when the disparity between supply and demand is significant. Price has a tendency to come back to those areas and mitigating them, that is filling them.
The provided tools allow for effective visualization of both FVG's area's height as well as the volume originating from their creation, which is defined by the total traded volume located within the FVG during its creation. FVG's with more associated volume are displayed to the rightmost of the chart.
Users can determine the amount of most recent FVG's to display from the "Display Amount" setting. Disabling the "Consider Mitigation" setting will return mitigated FVGs in the plot, which can be useful to know where most FVGs were located.
We can use the area average of the FVGs with the most associated volume as potential support/resistance levels. Users can extend more FVG's averages by increasing the "Highest Volume Averages" setting.
🔹 Visualizing Volume/Price Relationships of FVG's
A linear regression is fit between FVG's areas average and their associated volume, with this linear regression helping us see where FVG's with specific volume might be located in the future based on existing FVG's.
Note that FVG's do not tend to exhibit linear relationships with their associated volume, the provided linear regression can give a general sense of tendency, but nothing necessarily accurate.
🔶 DETAILS
🔹 Intrabar Data TF
Given a formation of three candles causing an FVG, the volume traded within that FVG area is obtained by looking at the lower timeframe intrabar candles located within the intermediary candle of the formation. The volume of the intrabar candles located within the FVG areas is added up to obtain the associated volume of the FVG.
Using a lower "Intrabar Data TF" allows obtaining more precise volume results, at the cost of computation time and data availability (if there is a high difference between the "Intrabar Data TF" and the chart TF then less FVG can have their associated volume calculated due to Tradingview limitations).
🔹 Display
Users have access to multiple graphical settings affecting how the indicator is displayed.
The "Graph Resolution" setting determines the length of the X axis, with higher values returning more precise results on the location of FVGs over the X axis. Users can also control the number of labels displayed on the X-axis using the numerical input to the right of "Show X-Axis Labels".
Additionally, users can color FVG areas using a gradient relative to the size of the area, or the volume associated with the FVG.
🔶 SETTINGS
Display Amount: Amount of most recent FVGs to display.
Highest Volume Averages: Amount of FVG averages levels with the highest volume to display and extend.
Consider Mitigation: Only display unmitigated FVGs.
Filter FVGs Outside Visible Range: Only display FVGs areas that are located within the user chart visible range.
Intrabar Data TF: Timeframe used to obtain intrabar data. Should be lower than the user chart timeframe.
Multi-Regression StrategyIntroducing the "Multi-Regression Strategy" (MRS) , an advanced technical analysis tool designed to provide flexible and robust market analysis across various financial instruments.
This strategy offers users the ability to select from multiple regression techniques and risk management measures, allowing for customized analysis tailored to specific market conditions and trading styles.
Core Components:
Regression Techniques:
Users can choose one of three regression methods:
1 - Linear Regression: Provides a straightforward trend line, suitable for steady markets.
2 - Ridge Regression: Offers a more stable trend estimation in volatile markets by introducing a regularization parameter (lambda).
3 - LOESS (Locally Estimated Scatterplot Smoothing): Adapts to non-linear trends, useful for complex market behaviors.
Each regression method calculates a trend line that serves as the basis for trading decisions.
Risk Management Measures:
The strategy includes nine different volatility and trend strength measures. Users select one to define the trading bands:
1 - ATR (Average True Range)
2 - Standard Deviation
3 - Bollinger Bands Width
4 - Keltner Channel Width
5 - Chaikin Volatility
6 - Historical Volatility
7 - Ulcer Index
8 - ATRP (ATR Percentage)
9 - KAMA Efficiency Ratio
The chosen measure determines the width of the bands around the regression line, adapting to market volatility.
How It Works:
Regression Calculation:
The selected regression method (Linear, Ridge, or LOESS) calculates the main trend line.
For Ridge Regression, users can adjust the lambda parameter for regularization.
LOESS allows customization of the point span, adaptiveness, and exponent for local weighting.
Risk Band Calculation:
The chosen risk measure is calculated and normalized.
A user-defined risk multiplier is applied to adjust the sensitivity.
Upper and lower bounds are created around the regression line based on this risk measure.
Trading Signals:
Long entries are triggered when the price crosses above the regression line.
Short entries occur when the price crosses below the regression line.
Optional stop-loss and take-profit mechanisms use the calculated risk bands.
Customization and Flexibility:
Users can switch between regression methods to adapt to different market trends (linear, regularized, or non-linear).
The choice of risk measure allows adaptation to various market volatility conditions.
Adjustable parameters (e.g., regression length, risk multiplier) enable fine-tuning of the strategy.
Unique Aspects:
Comprehensive Regression Options:
Unlike many indicators that rely on a single regression method, MRS offers three distinct techniques, each suitable for different market conditions.
Diverse Risk Measures: The strategy incorporates a wide range of volatility and trend strength measures, going beyond traditional indicators to provide a more nuanced view of market dynamics.
Unified Framework:
By combining advanced regression techniques with various risk measures, MRS offers a cohesive approach to trend identification and risk management.
Adaptability:
The strategy can be easily adjusted to suit different trading styles, timeframes, and market conditions through its various input options.
How to Use:
Select a regression method based on your analysis of the current market trend (linear, need for regularization, or non-linear).
Choose a risk measure that aligns with your trading style and the market's current volatility characteristics.
Adjust the length parameter to match your preferred timeframe for analysis.
Fine-tune the risk multiplier to set the desired sensitivity of the trading bands.
Optionally enable stop-loss and take-profit mechanisms using the calculated risk bands.
Monitor the regression line for potential trend changes and the risk bands for entry/exit signals.
By offering this level of customization within a unified framework, the Multi-Regression Strategy provides traders with a powerful tool for market analysis and trading decision support. It combines the robustness of regression analysis with the adaptability of various risk measures, allowing for a more comprehensive and flexible approach to technical trading.
Multiple Non-Linear Regression [ChartPrime]This indicator is designed to perform multiple non-linear regression analysis using four independent variables: close, open, high, and low prices. Here's a breakdown of its components and functionalities:
Inputs:
Users can adjust several parameters:
Normalization Data Length: Length of data used for normalization.
Learning Rate: Rate at which the algorithm learns from errors.
Smooth?: Option to smooth the output.
Smooth Length: Length of smoothing if enabled.
Define start coefficients: Initial coefficients for the regression equation.
Data Normalization:
The script normalizes input data to a range between 0 and 1 using the highest and lowest values within a specified length.
Non-linear Regression:
It calculates the regression equation using the input coefficients and normalized data. The equation used is a weighted sum of the independent variables, with coefficients adjusted iteratively using gradient descent to minimize errors.
Error Calculation:
The script computes the error between the actual and predicted values.
Gradient Descent: The coefficients are updated iteratively using gradient descent to minimize the error.
// Compute the predicted values using the non-linear regression function
predictedValues = nonLinearRegression(x_1, x_2, x_3, x_4, b1, b2, b3, b4)
// Compute the error
error = errorModule(initial_val, predictedValues)
// Update the coefficients using gradient descent
b1 := b1 - (learningRate * (error * x_1))
b2 := b2 - (learningRate * (error * x_2))
b3 := b3 - (learningRate * (error * x_3))
b4 := b4 - (learningRate * (error * x_4))
Visualization:
Plotting of normalized input data (close, open, high, low).
The indicator provides visualization of normalized data values (close, open, high, low) in the form of circular markers on the chart, allowing users to easily observe the relative positions of these values in relation to each other and the regression line.
Plotting of the regression line.
Color gradient on the regression line based on its value and bar colors.
Display of normalized input data and predicted value in a table.
Signals for crossovers with a midline (0.5).
Interpretation:
Users can interpret the regression line and its crossovers with the midline (0.5) as signals for potential buy or sell opportunities.
This indicator helps users analyze the relationship between multiple variables and make trading decisions based on the regression analysis. Adjusting the coefficients and parameters can fine-tune the model's performance according to specific market conditions.
Linear Regression Oscillator [ChartPrime]Linear Regression Oscillator Indicator
Overview:
The Linear Regression Oscillator is a custom TradingView indicator designed to provide insights into potential mean reversion and trend conditions. By calculating a linear regression on the closing prices over a user-defined period, this oscillator helps identify overbought and oversold levels and highlights trend changes. The indicator also offers visual cues and color-coded price bars to aid in quick decision-making.
Key Features:
◆ Customizable Look-Back Period:
Input: Length
Default: 20
Description: Determines the period over which the linear regression is calculated. A longer period smooths the oscillator but may lag, while a shorter period is more responsive but may be noisier.
◆ Overbought and Oversold Thresholds:
Inputs: Upper Threshold and Lower Threshold
Default: 1.5 and -1.5 respectively
Description: Define the upper and lower bounds for identifying overbought and oversold conditions. Values outside these thresholds suggest potential reversals.
◆ Candlestick Color Plotting:
Input: Plot Bar Color
Default: false
Description: Option to color the price bars based on the oscillator's value, providing a visual representation of market conditions. Bars turn cyan for positive oscillator values and blue for negative.
◆ Mean Reversion and Trend Signals:
Visual markers and labels indicate when the oscillator suggests mean reversion or trend changes, aiding in identifying key market turning points.
◆ Invalidation Levels:
Tracks the highest and lowest prices over a recent period to set levels where the current trend signal would be considered invalidated.
◆ Gradient Color Coding:
Utilizes gradient color coding to enhance the visualization of oscillator values, making it easier to interpret overbought and oversold conditions.
◆ Usage Notes:
Setting the Look-Back Period:
Adjust the "Length" input based on the timeframe and the type of trading you are conducting. Shorter periods are more suited for intraday trading, while longer periods can be used for swing trading.
Interpreting Thresholds:
Use the upper and lower threshold inputs to fine-tune the sensitivity of the overbought and oversold signals. Higher absolute values reduce the number of signals but increase their reliability.
Candlestick Coloring:
Enabling the "Plot Bar Color" option can help quickly identify the current state of the oscillator in relation to the zero line. This visual aid can be particularly useful in fast-moving markets.
Mean Reversion and Trend Signals:
Pay attention to the symbols and labels on the chart indicating mean reversion and trend changes. These signals are designed to highlight potential entry and exit points.
Invalidation Levels:
Use the plotted invalidation levels as stop-loss or signal invalidation points. If the price moves beyond these levels, the current trend signal is likely invalid.
This indicator helps traders identify overbought and oversold conditions, potential mean reversions, and trend changes based on the linear regression of the closing prices over a specified look-back period.
[MAD] Entrytool / Bybit-LinearThis indicator, "Entry Tool," was coded at request for Sandmann .
It is designed to provide traders with real-time feedback for strategizing entries, exits, and liquidation levels for trades initiated at that given moment.
The tool visualizes average entry prices, stop-loss levels, multiple take-profit targets, and potential liquidation prices, offering a comprehensive overview of possible trade outcomes. It aids traders in pre-planning their trades by visually simulating the impact of different trading decisions directly on the live chart. Each setting and parameter can be customized to align with individual trading strategies and risk tolerances, making this tool versatile for various trading styles, including day trading, swing trading, and position trading.
------------------------------
Steps to Use the Indicator:
1. Basic Setup:
Setup Type: Choose between "Long" or "Short" to set the direction of the trade.
Leverage: Adjust the leverage to understand its impact on your potential returns and liquidation price.
Tracking follows the close price, alternative you can enter a specific price.
2. Position Setup:
Initial Entry Amount: Set the starting amount for the trade.
Distance: First Increment Percentage from Entry price
Amount: Define the increase for the first incremental addition to the position and specify the amount to be added.
Distance: Second Increment Percentage from Entry
Amount: Set the increase for the second incremental addition and the corresponding amount.
3. Risk Management:
Stop-Loss (SL) Percentage: Set the percentage below or above the average entry price at which the position should be closed to minimize losses.
Take-Profit (TP) Percentages: Define up to four different profit target levels by specifying the percentage above or below the average entry price.
4. Visual Settings:
Box Colors: Customize the colors of the boxes that represent long and short positions to differentiate easily on the chart.
Box Extension: Determine the length by which the box extends beyond the current bar, which helps in visualizing the potential price movement.
Line Colors and Extensions: Select colors for various lines such as the Average Entry Line, Stop-Loss Line, Take-Profit Lines, and Liquidations Line. Adjust the length of these lines for better visibility.
Label Settings: Configure the distance of labels from their corresponding lines and set the font size for better readability.
5. Additional Features:
Liquidation Price Visualization: This new feature calculates and displays the liquidation price based on the current leverage and margin settings, giving traders a critical insight into their risk exposure.
Interactive Drag Point: Adjust the start price manually by dragging the point on the chart, which dynamically updates entry and exit levels as well as risk metrics.
Detailed Leverage Data Array: Input different scenarios with specific leverage, initial margin, and maintenance rates to see how these factors impact potential liquidation points.
6. Informations about leverage calculation
The data used are fetched from Bybit for Linear pairs to calculate the liquidations like in their documentation.
Keep in mind that other exchanges may calulate based on another formular.
regressionsLibrary "regressions"
This library computes least square regression models for polynomials of any form for a given data set of x and y values.
fit(X, y, reg_type, degrees)
Takes a list of X and y values and the degrees of the polynomial and returns a least square regression for the given polynomial on the dataset.
Parameters:
X (array) : (float ) X inputs for regression fit.
y (array) : (float ) y outputs for regression fit.
reg_type (string) : (string) The type of regression. If passing value for degrees use reg.type_custom
degrees (array) : (int ) The degrees of the polynomial which will be fit to the data. ex: passing array.from(0, 3) would be a polynomial of form c1x^0 + c2x^3 where c2 and c1 will be coefficients of the best fitting polynomial.
Returns: (regression) returns a regression with the best fitting coefficients for the selecected polynomial
regress(reg, x)
Regress one x input.
Parameters:
reg (regression) : (regression) The fitted regression which the y_pred will be calulated with.
x (float) : (float) The input value cooresponding to the y_pred.
Returns: (float) The best fit y value for the given x input and regression.
predict(reg, X)
Predict a new set of X values with a fitted regression. -1 is one bar ahead of the realtime
Parameters:
reg (regression) : (regression) The fitted regression which the y_pred will be calulated with.
X (array)
Returns: (float ) The best fit y values for the given x input and regression.
generate_points(reg, x, y, left_index, right_index)
Takes a regression object and creates chart points which can be used for plotting visuals like lines and labels.
Parameters:
reg (regression) : (regression) Regression which has been fitted to a data set.
x (array) : (float ) x values which coorispond to passed y values
y (array) : (float ) y values which coorispond to passed x values
left_index (int) : (int) The offset of the bar farthest to the realtime bar should be larger than left_index value.
right_index (int) : (int) The offset of the bar closest to the realtime bar should be less than right_index value.
Returns: (chart.point ) Returns an array of chart points
plot_reg(reg, x, y, left_index, right_index, curved, close, line_color, line_width)
Simple plotting function for regression for more custom plotting use generate_points() to create points then create your own plotting function.
Parameters:
reg (regression) : (regression) Regression which has been fitted to a data set.
x (array)
y (array)
left_index (int) : (int) The offset of the bar farthest to the realtime bar should be larger than left_index value.
right_index (int) : (int) The offset of the bar closest to the realtime bar should be less than right_index value.
curved (bool) : (bool) If the polyline is curved or not.
close (bool) : (bool) If true the polyline will be closed.
line_color (color) : (color) The color of the line.
line_width (int) : (int) The width of the line.
Returns: (polyline) The polyline for the regression.
series_to_list(src, left_index, right_index)
Convert a series to a list. Creates a list of all the cooresponding source values
from left_index to right_index. This should be called at the highest scope for consistency.
Parameters:
src (float) : (float ) The source the list will be comprised of.
left_index (int) : (float ) The left most bar (farthest back historical bar) which the cooresponding source value will be taken for.
right_index (int) : (float ) The right most bar closest to the realtime bar which the cooresponding source value will be taken for.
Returns: (float ) An array of size left_index-right_index
range_list(start, stop, step)
Creates an from the start value to the stop value.
Parameters:
start (int) : (float ) The true y values.
stop (int) : (float ) The predicted y values.
step (int) : (int) Positive integer. The spacing between the values. ex: start=1, stop=6, step=2:
Returns: (float ) An array of size stop-start
regression
Fields:
coeffs (array__float)
degrees (array__float)
type_linear (series__string)
type_quadratic (series__string)
type_cubic (series__string)
type_custom (series__string)
_squared_error (series__float)
X (array__float)
Trend AngleThe "Trend Angle" indicator serves as a tool for traders to decipher market trends through a methodical lens. It quantifies the inclination of price movements within a specified timeframe, making it easy to understand current trend dynamics.
Conceptual Foundation:
Angle Measurement: The essence of the "Trend Angle" indicator is its ability to compute the angle between the price trajectory over a defined period and the horizontal axis. This is achieved through the calculation of the arctangent of the percentage price change, offering a straightforward measure of market directionality.
Smoothing Mechanisms: The indicator incorporates options for "Moving Average" and "Linear Regression" as smoothing mechanisms. This adaptability allows for refined trend analysis, catering to diverse market conditions and individual preferences.
Functional Versatility:
Source Adaptability: The indicator affords the flexibility to select the desired price source, enabling users to tailor the angle calculation to their analytical framework and other indicators.
Detrending Capability: With the detrending feature, the indicator allows for the subtraction of the smoothing line from the calculated angle, highlighting deviations from the main trend. This is particularly useful for identifying potential trend reversals or significant market shifts.
Customizable Period: The 'Length' parameter empowers traders to define the observation window for both the trend angle calculation and its smoothing, accommodating various trading horizons.
Visual Intuition: The optional colorization enhances interpretability, with the indicator's color shifting based on its relation to the smoothing line, thereby providing an immediate visual cue regarding the trend's direction.
Interpretative Results:
Market Flatness: An angle proximate to 0 suggests a flat market condition, indicating a lack of significant directional movement. This insight can be pivotal for traders in assessing market stagnation.
Trending Market: Conversely, a relatively high angle denotes a trending market, signifying strong directional momentum. This distinction is crucial for traders aiming to capitalize on trend-driven opportunities.
Analytical Nuance vs. Simplicity:
While the "Trend Angle" indicator is underpinned by mathematical principles, its utility lies in its simplicity and interpretative clarity. However, it is imperative to acknowledge that this tool should be employed as part of a comprehensive trading strategy , complemented by other analytical instruments for a holistic market analysis.
In essence, the "Trend Angle" indicator exemplifies the harmonization of simplicity and analytical rigor. Its design respects the complexity of market behaviors while offering straightforward, actionable insights, making it a valuable component in the arsenal of both seasoned and novice traders alike.
LTI_FiltersLinear Time-Invariant (LTI) filters are fundamental tools in signal processing that operate with consistent behavior over time and linearly respond to input signals. They are crucial for analyzing and manipulating signals in various applications, ensuring the output signal's integrity is maintained regardless of when an input is applied or its magnitude. The Windowed Sinc filter is a specific type of LTI filter designed for digital signal processing. It employs a Sinc function, ideal for low-pass filtering, truncated and shaped within a finite window to make it practically implementable. This process involves multiplying the Sinc function by a window function, which tapers off towards the ends, making the filter finite and suitable for digital applications. Windowed Sinc filters are particularly effective for tasks like data smoothing and removing unwanted frequency components, balancing between sharp cutoff characteristics and minimal distortion. The efficiency of Windowed Sinc filters in digital signal processing lies in their adept use of linear algebra, particularly in the convolution process, which combines input data with filter coefficients to produce the desired output. This mathematical foundation allows for precise control over the filtering process, optimizing the balance between filtering performance and computational efficiency. By leveraging linear algebra techniques such as matrix multiplication and Toeplitz matrices, these filters can efficiently handle large datasets and complex filtering tasks, making them invaluable in applications requiring high precision and speed, such as audio processing, financial signal analysis, and image restoration.
Library "LTI_Filters"
offset(length, enable)
Calculates the time offset required for aligning the output of a filter with its input, based on the filter's length. This is useful for centered filters where the output is naturally shifted due to the filter's operation.
Parameters:
length (simple int) : The length of the filter.
enable (simple bool) : A boolean flag to enable or dissable the offset calculation.
Returns: The calculated offset if enabled; otherwise, returns 0.
lti_filter(filter_type, source, length, prefilter, centered, fc, window_type)
General-purpose Linear Time-Invariant (LTI) filter function that can apply various filter types to a data series. Can be used to apply a variety of LTI filters with different characteristics to financial data series or other time series data.
Parameters:
filter_type (simple string) : Specifies the type of filter. ("Sinc", "SMA", "WMA")
source (float) : The input data series to filter.
length (simple int) : The length of the filter.
prefilter (simple bool) : Boolean indicating whether to prefilter the input data.
centered (simple bool) : Determines whether the filter coefficients are centered.
fc (simple float) : Filter cutoff. Expressed like a length.
window_type (simple string) : Type of window function to apply. ("Hann", "Hamming", "Blackman", "Triangular", "Lanczos", "None")
Returns: The filtered data series.
lti_sma(source, length, prefilter)
Applies a Simple Moving Average (SMA) filter to the data series. Useful for smoothing data series to identify trends or for use as a component in more complex indicators.
Parameters:
source (float) : The input data series to filter.
length (simple int) : The length of the SMA filter.
prefilter (simple bool) : Boolean indicating whether to prefilter the input data.
Returns: The SMA-filtered data series.
lti_wma(source, length, prefilter, centered)
Applies a Weighted Moving Average (WMA) filter to a data series. Ideal for smoothing data with emphasis on more recent values, allowing for dynamic adjustments to the weighting scheme.
Parameters:
source (float) : The input data series to filter.
length (simple int) : The length of the WMA filter.
prefilter (simple bool) : Boolean indicating whether to prefilter the input data.
centered (simple bool) : Determines whether the filter coefficients are centered.
Returns: The WMA-filtered data series.
lti_sinc(source, length, prefilter, centered, fc, window_type)
Applies a Sinc filter to a data series, optionally using a window function. Particularly useful for signal processing tasks within financial analysis, such as smoothing or trend identification, with the ability to fine-tune filter characteristics.
Parameters:
source (float) : The input data series to filter.
length (simple int) : The length of the Sinc filter.
prefilter (simple bool) : Boolean indicating whether to prefilter the input data.
centered (simple bool) : Determines whether the filter coefficients are centered.
fc (simple float) : Filter cutoff. Expressed like a length.
window_type (simple string) : Type of window function to apply. ("Hann", "Hamming", "Blackman", "Triangular", "Lanczos", "None")
Returns: The Sinc-filtered data series.
Scalper's Volatility Filter [QuantraSystems]Scalpers Volatility Filter
Introduction
The 𝒮𝒸𝒶𝓁𝓅𝑒𝓇'𝓈 𝒱𝑜𝓁𝒶𝓉𝒾𝓁𝒾𝓉𝓎 𝐹𝒾𝓁𝓉𝑒𝓇 (𝒮𝒱𝐹) is a sophisticated technical indicator, designed to increase the profitability of lower timeframe trading.
Due to the inherent decrease in the signal-to-noise ratio when trading on lower timeframes, it is critical to develop analysis methods to inform traders of the optimal market periods to trade - and more importantly, when you shouldn’t trade.
The 𝒮𝒱𝐹 uses a blend of volatility and momentum measurements, to signal the dominant market condition - trending or ranging.
Legend
The 𝒮𝒱𝐹 consists of a signal line that moves above and below a central zero line, serving as the indication of market regime.
When the signal line is positioned above zero, it indicates a period of elevated volatility. These periods are more profitable for trading, as an asset will experience larger price swings, and by design, trend-following indicators will give less false signals.
Conversely, when the signal line moves below zero, a low volatility or mean-reverting market regime dominates.
This distinction is critical for traders in order to align strategies with the prevailing market behaviors - leveraging trends in volatile markets and exercising caution or implementing mean-reversion systems in periods of lower volatility.
Case Study
Here we can see the indicator's unique edge in action.
Out of the four potential long entries seen on the chart - displayed via bar coloring, two would result in losses.
However, with the power of the 𝒮𝒱𝐹 a trader can effectively filter false signals by only entering momentum-trades when the signal line is above zero.
In this small sample of four trades, the 𝒮𝒱𝐹 increased the win rate from 50% to 100%
Methodology
The methodology behind the 𝒮𝒱𝐹 is based upon three components:
By calculating and contrasting two ATR’s, the immediate market momentum relative to the broader, established trend is calculated. The original method for this can be credited to the user @xinolia
A modified and smoothed ADX indicator is calculated to further assess the strength and sustainability of trends.
The ‘Linear Regression Dispersion’ measures price deviations from a fitted regression line, adding further confluence to the signals representation of market conditions.
Together, these components synthesize a robust, balanced view of market conditions, enabling traders to help align strategies with the prevailing market environment, in order to potentially increase expected value and win rates.
ATR TrendTL;DR - An average true range (ATR) based trend
ATR trend uses a (customizable) ATR calculation and highest high & lowest low prices to calculate the actual trend. Basically it determines the trend direction by using highest high & lowest low and calculates (depending on the determined direction) the ATR trend by using a ATR based calculation and comparison method.
The indicator will draw one trendline by default. It is also possible to draw a second trendline which shows a 'negative trend'. This trendline is calculated the same way the primary trendline is calculated but uses a negative (-1 by default) value for the ATR calculation. This trendline can be used to detect early trend changes and/or micro trends.
How to use:
Due to its ATR nature the ATR trend will show trend changes by changing the trendline direction. This means that when the price crosses the trendline it does not automatically mean a trend change. However using the 'negative trend' option ATR trend can show early trend changes and therefore good entry points.
Some notes:
- A (confirmed) trend change is shown by a changing color and/or moving trendline (up/down)
- Unlike other indicators the 'time period' value is not the primary adjustment setting. This value is only used to calculate highest high & lowest low values and has medium impact on trend calculation. The primary adjustment setting is 'ATR weight'
- Every settings has a tooltip with further explanation
- I added additional color coding which uses a different color when the trend attempts to change but the trend change isn't confirmed (yet)
- Default values work fine (at least in my back testing) but the recommendation is to adjust the settings (especially ATR weight) to your trading style
- You can further finetune this indicator by using custom moving average types for the ATR calculation (like linear regression or Hull moving average)
- Both trendlines can be used to determine future support and resistance zones
- ATR trend can be used as a stop loss finder
- Alerts are using buy/sell signals
- You can use fancy color filling ;)
Happy trading!
Daniel
Linear Regression Channel 200█ OVERVIEW
This a simplified version of linear regression channel which use length 200 instead of traditional length 100.
█ FEATURES
Color change depends light / dark mode.
█ LIMITATIONS
Limited to source of closing price and max bars back is 1500.
█ SIMILAR
Regression Channel Alternative MTF
Regression Channel Alternative MTF V2
Predictive Channels [LuxAlgo]The Predictive Channels indicator is a real-time estimate of a trend channel. The indicator returns 2 resistances, 2 supports, and an average line.
🔶 USAGE
The Predictive Channels attempt to find a real-time estimate of an underlying linear trend in the price, the returned supports/resistances are constructed from this estimate.
The area between the price and the estimated trend is also highlighted, with a green color when the price is above the estimated trend, indicating a bullish variation relative to the trend, and a red color indicating a bearish variation.
Price deviating significantly from an estimated trend will return new channels. The Factor setting controls the allowed distance between the price and the trend estimate, with higher values allowing for greater distances and less frequent channels.
The Slope setting will affect the steepness of the channels, with lower values returning steeper channels, this can cause the price to more quickly deviate from the estimated trend, increasing the frequency at which new channels are created.
🔶 SETTINGS
Factor: Multiplicative factor, determines the allowed distance between the price and an estimated trend before a new channel is constructed.
Slope: Controls the line steepness of the channels, with lower values returning steeper lines.
YinYang RSI Volume Trend StrategyThere are many strategies that use RSI or Volume but very few that take advantage of how useful and important the two of them combined are. This strategy uses the Highs and Lows with Volume and RSI weighted calculations on top of them. You may be wondering how much of an impact Volume and RSI can have on the prices; the answer is a lot and we will discuss those with plenty of examples below, but first…
How does this strategy work?
It’s simple really, when the purchase source crosses above the inner low band (red) it creates a Buy or Long. This long has a Trailing Stop Loss band (the outer low band that's also red) that can be adjusted in the Settings. The Stop Loss is based on a % of the inner low band’s price and by default it is 0.1% lower than the inner band’s price. This Stop Loss is not only a stop loss but it can also act as a Purchase Available location.
You can get back into a trade after a stop loss / take profit has been hit when your Reset Purchase Availability After condition has been met. This can either be at Stop Loss, Entry or None.
It is advised to allow it to reset in case the stop loss was a fake out but the call was right. Sometimes it may trigger stop loss multiple times in a row, but you don’t lose much on stop loss and you gain lots when the call is right.
The Take Profit location is the basis line (white). Take Profit occurs when the Exit Source (close, open, high, low or other) crosses the basis line and then on a different bar the Exit Source crosses back over the basis line. For example, if it was a Long and the bar’s Exit Source closed above the basis line, and then 2 bars later its Exit Source closed below the basis line, Take Profit would occur. You can disable Take Profit in Settings, but it is very useful as many times the price will cross the Basis and then correct back rather than making it all the way to the opposing zone.
Longs:
If for instance your Long doesn’t need to Take Profit and instead reaches the top zone, it will close the position when it crosses above the inner top line (green).
Please note you can change the Exit Source too which is what source (close, open, high, low) it uses to end the trades.
The Shorts work the same way as the Long but just opposite, they start when the purchase source crosses under the inner upper band (green).
Shorts:
Shorts take profit when it crosses under the basis line and then crosses back.
Shorts will Stop loss when their outer upper band (green) is crossed with the Exit Source.
Short trades are completed and closed when its Exit Source crosses under the inner low red band.
So, now that you understand how the strategy works, let’s discuss why this strategy works and how it is profitable.
First we will discuss Volume as we deem it plays a much bigger role overall and in our strategy:
As I’m sure many of you know, Volume plays a huge factor in how much something moves, but it also plays a role in the strength of the movement. For instance, let’s look at two scenarios:
Bitcoin’s price goes up $1000 in 1 Day but the Volume was only 10 million
Bitcoin’s price goes up $200 in 1 Day but the Volume was 40 million
If you were to only look at the price, you’d say #1 was more important because the price moved x5 the amount as #2, but once you factor in the volume, you know this is not true. The reason why Volume plays such a huge role in Price movement is because it shows there is a large Limit Order battle going on. It means that both Bears and Bulls believe that price is a good time to Buy and Sell. This creates a strong Support and Resistance price point in this location. If we look at scenario #2, when there is high volume, especially if it is drastically larger than the average volume Bitcoin was displaying recently, what can we decipher from this? Well, the biggest take away is that the Bull’s won the battle, and that likely when that happens we will see bullish movement continuing to happen as most of the Bears Limit Orders have been fulfilled. Whereas with #2, when large price movement happens and Bitcoin goes up $1000 with low volume what can we deduce? The main takeaway is that Bull’s pressured the price up with Market Orders where they purchased the best available price, also what this means is there were very few people who were wanting to sell. This generally dictates that Whale Limit orders for Sells/Shorts are much higher up and theres room for movement, but it also means there is likely a whale that is ready to dump and crash it back down.
You may be wondering, what did this example have to do with YinYang RSI Volume Trend Strategy? Well the reason we’ve discussed this is because we use Volume multiple times to apply multiplications in our calculations to add large weight to the price when there is lots of volume (this is applied both positively and negatively). For instance, if the price drops a little and there is high volume, our strategy will move its bounds MUCH lower than the price actually dropped, and if there was low volume but the price dropped A LOT, our strategy will only move its bounds a little. We believe this reflects higher levels of price accuracy than just price alone based on the examples described above.
Don’t believe us?
Here is with Volume NOT factored in (VWMA = SMA and we remove our Volume Filter calculation):
Which produced -$2880 Profit
Here is with our Volume factored in:
Which produced $553,000 (55.3%)
As you can see, we wen’t from $-2800 profit with volume not factored to $553,000 with volume factored. That's quite a big difference! (Please note previous success does not predict future success we are simply displaying the $ amounts as example).
Now how about RSI and why does it matter in this strategy?
As I’m sure most of you are aware, RSI is one of the leading indicators used in trading. For this reason we figured it would only make sense to incorporate it into our calculations. We fiddled with RSI for quite awhile and sometimes what logically seems to be the right way to use it isn’t. Now, because of this, our RSI calculation is a little odd, but basically what we’re doing is we calculate the RSI, then turn it into a percentage (between 0-1) that can easily be multiplied to the price point we need. The price point we use is the difference between our high purchase zone and our low purchase zone. This allows us to see how much price movement there is between zones. We multiply our zone size with our RSI multiplication and we get the amount we will add +/- to our basis line (white line). This officially creates the NEW high and low purchase zones that we are actually using and displaying in our trades.
If you found that confusing, here are some examples to why it is an important calculation for this strategy:
Before RSI factored in:
Which produced 27.8% Profit
After RSI factored in:
Which produced 553% Profit
As you can see, the RSI makes not only the purchase zones more accurate, but it also greatly increases the profit the strategy is able to make. It also helps ensure an relatively linear profit slope so you know it is reliable with its trades.
This strategy can work on pretty much anything, but you should tweak the values a bit for each pair you are trading it with for best results.
We hope you can find some use out of this simple but effective strategy, if you have any questions, comments or concerns please let us know.
HAPPY TRADING!
Regression Line (Log)This indicator is based on the "Linear Regression Channel (Log)," which, in turn, is derived from TradingView's "Linear Regression Channel."
The "Regression Line (Log)" indicator is a valuable tool for traders and investors seeking to gain insights into long-term market trends. This indicator is personally favored for its ability to provide a comprehensive view of price movements over extended periods. It offers a unique perspective compared to traditional linear regression lines and moving averages, making it a valuable addition to the toolkit of experienced traders and investors.
Indicator Parameters:
Before delving into the details, it's worth noting that the chosen number of periods (2870) is a personal preference. This specific value is utilized for the S&P 500 index due to its alignment with various theories regarding the beginning of the modern economic era in the stock market. Different analysts propose different starting points, such as the 1950s, 1970s, or 1980s. However, users are encouraged to adjust this parameter to suit their specific needs and trading strategies.
How It Works:
The "Regression Line (Log)" indicator operates by transforming the closing price data into a logarithmic scale. This transformation can make the linear regression more suitable for data with exponential trends or rapid growth. Here's a breakdown of its functioning and why it can be advantageous for long-term trend analysis:
1. Logarithmic Transformation : The indicator begins by applying a logarithmic transformation to the closing price. This transformation helps capture price movements proportionally, making it especially useful for assets that exhibit exponential or rapid growth. This transformation can render linear regression more suitable for data with exponential or fast-paced trends.
2. Linear Regression on Log Scale : After the logarithmic transformation, the indicator calculates a linear regression line (lrc) on this log-transformed data. This step provides a smoother representation of long-term trends compared to a linear regression line on a linear scale.
3. Exponential Reversion : To present the results in a more familiar format, the indicator reverts the log-transformed regression line back to a linear scale using the math.exp function. This final output is the "Linear Regression Curve," which can be easily interpreted on standard price charts.
Advantages:
- Long-Term Trend Clarity : The logarithmic scale better highlights long-term trends and exponential price movements, making it a valuable tool for investors seeking to identify extended trends.
- Smoothing Effect : The logarithmic transformation and linear regression on a log scale smooth out price data, reducing noise and providing a clearer view of underlying trends.
- Adaptability : The indicator allows traders and investors to customize the number of periods (length) to align with their preferred historical perspective or trading strategy.
- Complementary to Other Tools : While not meant to replace other technical indicators, the "Regression Line (Log)" indicator complements traditional linear regression lines and moving averages, offering an alternative perspective for more comprehensive analysis.
Conclusion:
In summary, the "Regression Line (Log)" indicator is a versatile tool that can enhance your ability to analyze long-term market trends. Its logarithmic transformation provides a unique perspective on price data, particularly suited for assets with exponential growth patterns. While the choice of the number of periods is a personal one, it can be adapted to fit various historical viewpoints. This indicator is best utilized as part of a well-rounded trading strategy, in conjunction with other technical tools, to aid in informed decision-making.
Linear RegressionThis indicator can be used to determine the direction of the current trend.
The indicator plots two different histograms based on the linear regression formula:
- The colored ones represent the direction of the short-term trend
- The gray one represents the direction of the long-term trend
In the settings, you can change the length of the short-term value, which also influences the long-term as a basis that will be multiplied
Linear Regression IndicatorThis tool can be used to determine the direction of the current trend.
The indicator changes the color of the candles based on the direction of the linear regression formula. This is made settings the length of the short-term linear regression in the settings, the longer one is also based on that parameter but significantly larger.
The indicator also plots the average between the two linear regression lines used in the candle coloring formula, and can be used both for support and resistance or as a trend line used to analyze breakouts.
Linear Cross Trading StrategyLinear Cross Trading Strategy
The Linear Cross trading strategy is a technical analysis strategy that uses linear regression to predict the future price of a stock. The strategy is based on the following principles:
The price of a stock tends to follow a linear trend over time.
The slope of the linear trend can be used to predict the future price of the stock.
The strategy enters a long position when the predicted price crosses above the current price, and exits the position when the predicted price crosses below the current price.
The Linear Cross trading strategy is implemented in the TradingView Pine script below. The script first calculates the linear regression of the stock price over a specified period of time. The script then plots the predicted price and the current price on the chart. The script also defines two signals:
Long signal: The long signal is triggered when the predicted price crosses above the current price.
Short signal: The short signal is triggered when the predicted price crosses below the current price.
The script enters a long position when the long signal is triggered and exits the position when the short signal is triggered.
Here is a more detailed explanation of the steps involved in the Linear Cross trading strategy:
Calculate the linear regression of the stock price over a specified period of time.
Plot the predicted price and the current price on the chart.
Define two signals: the long signal and the short signal.
Enter a long position when the long signal is triggered.
Exit the long position when the short signal is triggered.
The Linear Cross trading strategy is a simple and effective way to trade stocks. However, it is important to note that no trading strategy is guaranteed to be profitable. It is always important to do your own research and backtest the strategy before using it to trade real money.
Here are some additional things to keep in mind when using the Linear Cross trading strategy:
The length of the linear regression period is a key parameter that affects the performance of the strategy. A longer period will smooth out the noise in the price data, but it will also make the strategy less responsive to changes in the price.
The strategy is more likely to generate profitable trades when the stock price is trending. However, the strategy can also generate profitable trades in ranging markets.
The strategy is not immune to losses. It is important to use risk management techniques to protect your capital when using the strategy.
I hope this blog post helps you understand the Linear Cross trading strategy better. Booost and share with your friend, if you like.
AI Moving Average (Expo)█ Overview
The AI Moving Average indicator is a trading tool that uses an AI-based K-nearest neighbors (KNN) algorithm to analyze and interpret patterns in price data. It combines the logic of a traditional moving average with artificial intelligence, creating an adaptive and robust indicator that can identify strong trends and key market levels.
█ How It Works
The algorithm collects data points and applies a KNN-weighted approach to classify price movement as either bullish or bearish. For each data point, the algorithm checks if the price is above or below the calculated moving average. If the price is above the moving average, it's labeled as bullish (1), and if it's below, it's labeled as bearish (0). The K-Nearest Neighbors (KNN) is an instance-based learning algorithm used in classification and regression tasks. It works on a principle of voting, where a new data point is classified based on the majority label of its 'k' nearest neighbors.
The algorithm's use of a KNN-weighted approach adds a layer of intelligence to the traditional moving average analysis. By considering not just the price relative to a moving average but also taking into account the relationships and similarities between different data points, it offers a nuanced and robust classification of price movements.
This combination of data collection, labeling, and KNN-weighted classification turns the AI Moving Average (Expo) Indicator into a dynamic tool that can adapt to changing market conditions, making it suitable for various trading strategies and market environments.
█ How to Use
Dynamic Trend Recognition
The color-coded moving average line helps traders quickly identify market trends. Green represents bullish, red for bearish, and blue for neutrality.
Trend Strength
By adjusting certain settings within the AI Moving Average (Expo) Indicator, such as using a higher 'k' value and increasing the number of data points, traders can gain real-time insights into strong trends. A higher 'k' value makes the prediction model more resilient to noise, emphasizing pronounced trends, while more data points provide a comprehensive view of the market direction. Together, these adjustments enable the indicator to display only robust trends on the chart, allowing traders to focus exclusively on significant market movements and strong trends.
Key SR Levels
Traders can utilize the indicator to identify key support and resistance levels that are derived from the prevailing trend movement. The derived support and resistance levels are not just based on historical data but are dynamically adjusted with the current trend, making them highly responsive to market changes.
█ Settings
k (Neighbors): Number of neighbors in the KNN algorithm. Increasing 'k' makes predictions more resilient to noise but may decrease sensitivity to local variations.
n (DataPoints): Number of data points considered in AI analysis. This affects how the AI interprets patterns in the price data.
maType (Select MA): Type of moving average applied. Options allow for different smoothing techniques to emphasize or dampen aspects of price movement.
length: Length of the moving average. A greater length creates a smoother curve but might lag recent price changes.
dataToClassify: Source data for classifying price as bullish or bearish. It can be adjusted to consider different aspects of price information
dataForMovingAverage: Source data for calculating the moving average. Different selections may emphasize different aspects of price movement.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Extrapolated Previous Trend [LuxAlgo]The Extrapolated Previous Trend indicator extrapolates the estimated linear trend of the prices within a previous interval to the current interval. Intervals can be user-defined.
🔶 USAGE
Returned lines can be used to provide a forecast of trends, assuming trends are persistent in sign and slope.
Using them as support/resistance can also be an effecting usage in case the trend in a new interval does not follow the characteristic of the trend in the previous interval.
The indicator includes a dashboard showing the degree of persistence between segmented trends for uptrends and downtrends. A higher value is indicative of more persistent trend signs.
A lower value could hint at an anti-persistent behavior, with uptrends over an interval often being followed by a down-trend and vice versa. We can invert candle colors to determine future trend direction in this case.
🔶 DETAILS
This indicator can be thought of as a segmented linear model ( a(n)t + b(n) ), where n is the specific interval index. Unlike a regular segmented linear regression model, this indicator is not subject to lookahead bias, coefficients of the model are obtained on previous intervals.
The quality of the fit of the model is dependent on the variability of its coefficients a(n) and b(n) . Coefficients being less subject to change over time are more indicative of trend persistence.
🔶 SETTINGS
Timeframe: Determine the frequency at which new trends are estimated.