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.
Linear Regression
Advanced Trend Detection StrategyThe Advanced Trend Detection Strategy is a sophisticated trading algorithm based on the indicator "Percent Levels From Previous Close".
This strategy is based on calculating the Pearson's correlation coefficient of logarithmic-scale linear regression channels across a range of lengths from 50 to 1000. It then selects the highest value to determine the length for the channel used in the strategy, as well as for the computation of the Simple Moving Average (SMA) that is incorporated into the strategy.
In this methodology, a script is applied to an equity in which multiple length inputs are taken into consideration. For each of these lengths, the slope, average, and intercept are calculated using logarithmic values. Deviation, the Pearson's correlation coefficient, and upper and lower deviations are also computed for each length.
The strategy then selects the length with the highest Pearson's correlation coefficient. This selected length is used in the channel of the strategy and also for the calculation of the SMA. The chosen length is ultimately the one that best fits the logarithmic regression line, as indicated by the highest Pearson's correlation coefficient.
In short, this strategy leverages the power of Pearson's correlation coefficient in a logarithmic scale linear regression framework to identify optimal trend channels across a broad range of lengths, assisting traders in making more informed decisions.
MACD TrueLevel StrategyThis strategy uses the MACD indicator to determine buy and sell signals. In addition, the strategy employs the use of "TrueLevel Bands," which are essentially envelope bands that are calculated based on the linear regression and standard deviation of the price data over various lengths.
The TrueLevel Bands are calculated for 14 different lengths and are plotted on the chart as lines. The bands are filled with a specified color to make them more visible. The highest upper band and lowest lower band values are stored in variables for easy access.
The user can input the lengths for the TrueLevel Bands and adjust the multiplier for the standard deviation. They can also select the bands they want to use for entry and exit, and enable long and short positions.
The entry conditions for a long position are either a crossover of the MACD line over the signal line or a crossover of the price over the selected entry lower band. The entry conditions for a short position are either a crossunder of the MACD line under the signal line or a crossunder of the price under the selected exit upper band.
The exit conditions for both long and short positions are not specified in the code and are left to the user to define.
Overall, the strategy aims to capture trends by entering long or short positions based on the MACD and TrueLevel Bands, and exiting those positions when the trend reverses.
RSI TrueLevel StrategyThis strategy is a momentum-based strategy that uses the Relative Strength Index (RSI) indicator and a TrueLevel envelope to generate trade signals.
The strategy uses user-defined input parameters to calculate TrueLevel envelopes for 14 different lengths. The TrueLevel envelope is a volatility-based technical indicator that consists of upper and lower bands. The upper band is calculated by adding a multiple of the standard deviation to a linear regression line of the price data, while the lower band is calculated by subtracting a multiple of the standard deviation from the same regression line.
The strategy generates long signals when the RSI crosses above the oversold level or when the price crosses above the selected lower band of the TrueLevel envelope. It generates short signals when the RSI crosses below the overbought level or when the price crosses below the selected upper band of the TrueLevel envelope.
The strategy allows for long and short trades and sets the trade size as a percentage of the account equity. The colors of the bands and fills are also customizable through user-defined input parameters.
In this strategy, the 12th TrueLevel band was chosen due to its ability to capture significant price movements while still providing a reasonable level of noise reduction. The strategy utilizes a total of 14 TrueLevel bands, each with varying lengths. The 12th band, with a length of 2646, strikes a balance between sensitivity to market changes and reducing false signals, making it a suitable choice for this strategy.
RSI Parameters:
In this strategy, the RSI overbought and oversold levels are set at 65 and 40, respectively. These values were chosen to filter out more noise in the market and focus on stronger trends. Traditional RSI overbought and oversold levels are set at 70 and 30, respectively. By raising the oversold level and lowering the overbought level, the strategy aims to identify more significant trend reversals and potential trade opportunities.
Of course, the parameters can be adjusted to suit individual preferences.
Pairs Trading (basic OLS regression)Pairs trading using hedge ratio.
Firstly, it calculates hedge ration using OLS linear regression.
Then it calculates spread and z-score of spread.
if spread in specific range (which it's possible to change in settings) it makes Long/Short orders.
The very basic script.
MACandles-LinearRegression-StrategyThis is combination of multiple indicators and strategies. Mainly useful for indexes and to time the entry and exits of indexes. No stoploss used - makes it less desirable for leveraged trades or trading individual stocks.
Let us rewind and look back at some of the indicators/strategies published earlier.
1. Moving Average Candles - this is one of my favourite tool for general trend filtering. Applying supertrend on moving average candles is one of the easiest ways to find reversal in trending market without exiting positions too early. Few scripts published on this basis are:
MA Candles Supertrend
MA Candles Supertrend Strategy
2. VixFix and Linear Regression - this itself is combination of two indicators.
Williams-Vix-Fix-Finds-Market-Bottoms - by @ChrisMoody
Squeeze-Momentum-Indicator - by @LazyBear
I have combined these two indicators to derive VIX-Fix linear regression to find absolute market bottoms. More description here:
VixFixLinReg-Strategy
VixFixLinReg-Indicator
Now, in this strategy, we combine all these together.
Derive moving average candles
Derive momentum of moving average candles
Derive Linear regression on momentum
Optionally, also calculate VIX Fix and Linear regression on VixFix momentum
To find market bottom:
There are two options
1. Use when momentum of MA candles hit bottom (red) and slowly turn up (orange). In aggressiveLong mode, signals are also generated when momentum starts going positive from negative.
2. Use Vix Fix linear regression of MA candles as described in the original script of VixFixLinReg-Strategy
To find market top
Here only Ma candles momentum decreasing is used as signal. If looking for longTrades , exit signal is generated only when momentum is turning negative extreme(orange). Or else, exit signal is generated when momentum has turned neutral.
At this stage, it is very much experimental - use it with caution :)
VixFixLinReg-StrategyThis idea came up while discussing about strategies with one of the trading enthusiast from tradingview community.
Strategy basically uses existing script of Vix Fix by Chris Moody:
VixFix is a great indicator for finding the market bottoms. But, sometimes it generates signal too early. But, we can apply linear regression on vix fix to find vix fix top to make timing much better.
Entry condition:
Wait for Vix fix bar to turn lime.
Once vix fix is turned lime, then wait for linear regression (shown below 0) to turn lime from green. This indicates VIX-Fix has started declining.
Go long once above two conditions are satisfied
Exit Condition:
ATR Based Stop
Applied only if linear regression is green - which means VixFix rising.
Note: This is ideal for identifying market bottom. May not yield good results on individual stocks.
Moving Regression Band Breakout strategyFollowing the introduction of the Moving Regression Prediction Bands indicator (see link below), I'd like to propose how to utilize it in a simple band breakout strategy :
Go long after the candle closes above the upper band . The lower band (alternatively, the lower band minus the 14-period ATR or the central line ) will serve as a support line .
Exit as soon as the candle closes below the support line .
To manage the risk of false breakouts, a fixed stop loss is set to the value of the support line at the time of opening a position. When the support line moves above the position opening price, shift the stop loss to breakeven.
The same logic but in reverse applies to short positions.
As an option, it is possible to allow long entries only when the slope of the Moving Regression curve is positive (and short entries when the slope is negative).
Model parameters:
Length and Polynomial Order define the lag and smoothness of the model.
Multiplier specifies the width of the channel.
As the default model parameter values, I set those that I found to provide optimal risk / reward ratio on the daily timeframe (for both trending and range-bound market). However, the settings are very flexible and can be well-adjusted to particular market conditions. Feel free to play around and leave feedback in the comments!
Here's the original Moving Regression Prediction Bands script:
Linear Regression - Reverse Up/Down StrategyFor my first foray into pine script I took the code from the generic "Consecutive up/down" and flipped the logic. I added a linear regression filter to try and stay with the overall trend. ATR added for visual, I eventually want to use it as part of the money management.
Rules to open trade or close the opposite:
IF the linear regression slope is >=0 AND the last candle closes lower, BUY
IF the linear regression slope is <=0 AND the last candle closes higher SELL
Rules to close the opposite:
IF the linear regression slope is >=0 AND the last candle closes higher, close any open SELL
IF the linear regression slope is <=0 AND the last candle closes lower, close any open BUY
Function Polynomial Regression StrategyTo be clear I'm using the code from Richard Santos for the functional polynomial regression. I really loved his script idea (given that I'm into linear regression myself). I took his code and made a strategy which applies to bitcoin on the 5 minute chart (but you could adjust this for any asset), and you could make this work on anytime frame by adjusting the 'length' property of the regression until you get good results.
This strategy is very simple.
I drew lines to represent the bottom most part of the regression (green line), and top most part (red line). If the close crosses under the red line then you short. The reverse if it crosses above the green line then you go long.
Very simple but effective. To understand this script be sure to add Richard santos function polynomial regression so you can see what is going on and what I'm trying to do.
For example, on BTC with a length of 61 if you bought and held you would have only had 5% gain, instead with this strategy you are looking at very close to 60% gains! Now this could be a weird fluke of over-optimizing but I'm not sure this is the case because you can adjust the length from there +/- about 10 and still have good results. It's just certain lengths are the correct trading rhythms for different assets.
I'm excited to see how you guys use this and if you have any success. Be sure to thank Richard Santos for his great work!
Close Trade at end of day script serves as an example how we can close trades at end of day.
can be session controlled or the time controlled.
the session should be adjusted to be earlier than the candle time.
Pair Trade cryptoPair trade for crypto with inputs:
* length of correlation and moving average
* trade pair
* spread threshold to enter long / short
* spread threshold to exit long / short
Pair TradePair trade with inputs:
* length of correlation and moving average
* trade pair
* spread threshold to enter long / short
* spread threshold to exit long / short
Linear Regression Pearson's R - Trend Channel StrategyThis script takes advantage of the Pearson's R attribute of the data set you provide.
Pearson's R attempts to find how correlated data is with a potential pattern. If the number is negative the correlation is upwards . If it's positive the correlation is downwards . Pearson's R can only be a number between -1 and 1. It should be impossible to ever reach -1 or 1 as that would be a perfect correlation.
This particular strategy involves using linear regression and Pearson's R to keep recalculating steps back from the current position until the Pearson's R reaches the desired amount. For example, in my experience I have found that 0.85 for as a buy point is very good as it means the trend is very reliable and solid. When the market tends to be bullish it tends to do so longer then when it's bearish.
Likewise when a downtrend is more real, I found that 0.71 for the negative Pearson's R value is ideal and gives the best results.
These can all be changed in the settings section (with the gear icon) next to when you set your results.
This strategy is really fun/useful to watch if you have the replay bar mode enabled for TradingView. This script supports this and all you have to do is go into the settings and enable realtime mode . Doing this you can actually see the trend lines change in realtime and comes in very handy for seeing long term reversals as you will see the Pearson's R value start to go down or up indicating the path it's going on.
WARNING: This script is very intensive on the processing power of your machine. If you find that it's to slow you may have to go into the settings of the script and adjust the 'step by' parameter so that it calculates a little faster. It won't be as accurate but it will be good enough. I feel I've optimized it with it's current setting as an example of what you want to aim for.
If there are any questions do no hesitate to message or ask me. I love feedback on the community for new features and ideas!
This works best with with XBTUSD on the 4 hourly chart . It does not seem to work well if you go below hourly or go above daily.
Center of Gravity BF 🚀Thanks to HPotter for the code I based this strategy on.
Center of Gravity calculation is based here on a linear regression function using the least squares method.
We use this to calculate a channel consisting of 2 lines, green and red on the chart
This strategy employs a dynamic stop loss function that measures stop loss placement based on recent ATR.
How signals are generated:
Price closes above green line = Go Long
Price closes below red line = Go Short
Yellow dotted line = stop loss based on long entry
Orange dotted line = stop loss based on short entry
INSTRUCTIONS
Green background = Go Long, put your stop loss at the yellow dotted line
Red background = Go Short, put your stop loss at the orange dotted line
NB: The stop losses printed on the chart are calculated from the point of entry on a trade, if you make a different entry to what is indicated, the corresponding stop loss will be different to what the indicator displays.
Sniper & Strategy SniperTrading permite detectar los momentos exactos de compra y venta obteniendo un buen rendimiento.
Como aplicarlo:
* Realice una compra cuando el indicador de COMPRA aparezca en la pantalla.
* Realice una venta cuando el indicador de VENTA aparezca en la pantalla.
Linear Regression (Backtest / Trailing Stop)A Strategy with Backtest and Trailing Stop for Long/Short
Credits: Study by RafaelZioni - Thanks buddy!