Strategy LinReg ST@RLStrategy LinReg ST@RL
Strategy LinReg ST@RL is a visual trend following indicator.
It is compiled in PINE Script Version V5 language.
This indicator/strategy, based on Linear Regression Calculation, is intended to help beginners (and also the more experienced ones) to trade in the right direction of the market trend and test strategy. It allows you to avoid the mistakes of always trading against the trend.
Strategy based on an original idea of @KivancOzbilgic (SuperTrend) and DevLucem (@LucemAnb) (Lin Reg ++)
A special credit goes to - KivancOzbilgic and @LucemAnb which inspired me a lot to improve this indicator/Strategy.
This indicator can be configured to your liking,according to your needs or your tastes.
The indicator/Strategy works in multi time frame.
The settings (length, offset, deviation, smoothing) are identical for all time frames if “Conf Auto” is not checked.
In this case the default settings (time frame=H1 settings) apply for all time frames.
The choice of source setting is common for all time frames.
If “Auto Conf” is checked,
then the settings will be optimized for each selected time frame (1m-3m H2 H3 H1 H4 & Daily). Time frames, other than 1m-3m H2 H3 H1 H4 & Daily will be affected with the default settings corresponding to the H1 time frame and will therefore not be optimized! The default setting values of each time frame (1m-3m H2 H3 H1 H4 & Daily) can be configured differently and optimized by you.
REVERSAL mode: Signal Buy=Sell and Signal Sell=Buy.
This option may be better than the regular strategy. Default mode is Reversal option.
Note that only for 1m (1 minute) Time frame, the option REVERSAL is opposite as default choice in configuration. (If reversal option is checked, then option for time frame 1m is not reversal!)
Trend indications (potential sell or buy areas) are displayed as a background color (bullish: green or bearish: red), assume that the market is moving in one direction.
You can tune the input, style and visibility settings to match your own preferences or habits.
Label Info (Simple or Full) gives trend info for each Exit (or current trade)
The choice of indicator colors is suitable for a graph with a "dark" theme, which you will probably need to modify for visual comfort, if you are using a "Light" mode or a custom mode.
This script is an indicator that you can run on standard chart types. It also works on non-standard chart types but the results will be skewed and different.
Non-standard charts are:
• Heikin Ashi (HA)
• Renko
• Kagi
• Point & Figure
• Range
As a reminder: No indicator is capable of providing accurate signals 100% of the time. Every now and then, even the best will fail, leaving you with a losing deal. Whichever indicator you base yourself on, remember to follow the basic rules of risk management and capital allocation.
BINANCE:BTCUSDT
! Français !
Strategy LinReg ST@RL
Stratégie LinReg ST@RL est un indicateur visuel de suivi de tendance.
Il est compilé en langage PINE Script Version V5.
Stratégie basée sur une idée originale de @KivancOzbilgic (SuperTrend) et DevLucem (@LucemAnb) (Lin Reg ++) Un crédit spécial va à - KivancOzbilgic et @LucemAnb qui m'ont beaucoup inspiré pour améliorer cet indicateur/stratégie.
Cet indicateur/strategie, basé sur le calcul de régression linéaire, est destiné à aider les débutants (et aussi les plus expérimentés) à trader dans le bon sens de la tendance du marché et à tester la stratégie. Cela vous permet d'éviter les erreurs de toujours négocier à contre-courant.
Cet indicateur peut être configuré à votre guise, selon vos besoins ou vos goûts.
L'indicateur/Stratégie fonctionne sur plusieurs bases de temps.
Les réglages (longueur, décalage, déviation, lissage) sont identiques pour toutes les bases de temps si
« Conf Auto » n'est pas coché. Dans ce cas, les paramètres par défaut (intervalle de temps=paramètres H1) s'appliquent à toutes les bases de temps.
Le choix du réglage de la source est commun à toutes les bases de temps.
Si "Auto Conf" est coché, alors les paramètres seront optimisés pour chaque base de temps sélectionnée (1m-3m H2 H3 H1 H4 & Daily). Les bases de temps, autres que 1m-3m H2 H3 H1 H4 & Daily seront affectées par les paramètres par défaut correspondant à la base de temps H1 et ne seront donc pas optimisées ! Les valeurs de réglage par défaut de chaque période (1m-3m H2 H3 H1 H4 & Daily) peuvent être configurées différemment et optimisées par vous.
Mode REVERSAL : Signal Achat=Vente et Signal Vente=Achat. Cette option peut être meilleure que la stratégie habituelle. Le mode par défaut est l'option REVERSAL.
Notez que seulement pour la base de temps de 1m (1 minute), l'option REVERSAL est l’opposée du choix par défaut dans la configuration. (Si l'option REVERSAL est cochée, alors l'option pour la base de temps 1 m n'est pas REVERSAL !)
Les indications de tendance (zones potentielles de vente ou d'achat) sont affichées en couleur de fond (haussier : vert ou baissier : rouge), supposons que le marché évolue dans une direction. Vous pouvez ajuster les paramètres d'entrée, de style et de visibilité en fonction de vos propres préférences ou habitudes.
Les informations sur l'étiquette (simples ou complètes) donnent des informations sur de chaque clôture (ou position en cours)
Le choix des couleurs des indicateurs est adapté à un graphique avec un thème "sombre", qu'il vous faudra probablement modifier pour le confort visuel, si vous utilisez un mode "Clair" ou un mode personnalisé.
Ce script est un indicateur que vous pouvez exécuter sur des types de graphiques standard. Cela fonctionne également sur les types de graphiques non standard, mais les résultats seront faussés et différents.
Les graphiques non standard sont :
• Heikin Ashi (HA)
• Renko
• Kagi
• Point & Figure
• Range
Pour rappel : Aucun indicateur n'est capable de fournir des signaux précis 100% du temps. De temps en temps, même les meilleurs échoueront, vous laissant avec une affaire perdante. Quel que soit l'indicateur sur lequel vous vous basez, rappelez-vous de suivre les règles de base de la gestion des risques et de l'allocation du capital.
Regressions
Trend Line RegressionThis is a fast trend line regressor based on least squares regression.
(1) Supports setting regression from the Nth candle
(2) Supports the minimum and maximum regression candle interval length
(3) Supports finding the optimal regression region based on the length step among the minimum and maximum regression region lengths
(4) Supports displaying the optimal regression level
(5) The size of the regression region is 0.5 times the standard deviation by default
(6) You can filter the trend line by setting minimum trend line regression level
(6) Please properly set the parameters to avoid calculation timeout
Enjoy!
这是一个基于最小二乘法回归的快速趋势线回归
(1) 支持从第N根蜡烛开始设置回归
(2) 支持最小和最大的回归蜡烛区间长度
(3) 支持在最小和最大回归区间长度的基础上寻找最佳回归区域
(4) 支持显示最佳回归水平
(5) 回归区域的大小默认为标准差的0.5倍
(6) 可以通过设置最小趋势线回归等级来过滤趋势线
(6) 请正确设置参数以避免计算超时
使用愉快!
Price Region RegressionThis is an optimized price range regressor based on least squares regression.
(1) Supports setting regression from the Nth candle
(2) Supports the minimum and maximum regression candle interval length
(3) Supports finding the optimal regression region based on the length step among the minimum and maximum regression region lengths
(4) Supports displaying the optimal regression level
(5) The size of the regression region is two times the standard deviation by default
这是一个基于最小二乘回归的价格区间回归指标
(1) 支持设置从第N个蜡烛开始回归
(2) 支持最小和最大回归蜡烛的区间长度
(3) 在最小和最大回归区间长度中,根据长度步进寻找最优的回归区间
(4) 支持显示最优回归等级
(5) 回归区间的大小默认为2倍标准差
StrengthA mathematically elegant, native & modern way how to measure velocity/ strength/ momentum. As you can see it looks like MACD, but !suddenly! has N times shorter code (disregard the functions), and only 1 parameter instead of 3. OMG HOW DID HE DO IT?!?
MACD: "Let's take one filter (1 parameter), than another filter (2 parameters), then let's take dem difference, then let's place another filter over the difference (3rd parameter + introduction of a nested calculation), and let's write a whole book about it, make thousands of multi-hours YouTube videos about it, and let's never mention about the amount of uncertainty being introduced by multiple parameters & introduction of the nested calculation."
Strength: "let's get real, let's drop a weighted linear regression & usual linear regression over the data of the same length, take dem slopes, then make the difference over these slopes, all good. And then share it with people w/o putting an ® sign".
Fyi, regressions were introduced centuries ago, maybe decades idk, the point is long time ago, and computational power enough to calculate what I'm saying is slightly more than required for macd.
Rationale.
Linearly weighted linear regression has steeper slope (W) than the usual linear regression slope (S) due to the fact that the recent datapoints got more weight. This alone is enough of a metric to measure velocity. But still I've recalled macd and decided to make smth like it cuz I knew it'll might make you happy. I realized that S can be used instead of smoothing the W, thus eliminating the nested calculation and keeping entropy & info loss in place. And see, what we get is natural, simple, makes sense and brings flex. I also wanna remind you that by applying regression we maximize the info gain by using all the data in the window, instead of taking difference between the first and the last datapoints.
This script is dedicated to my friend Fabien. Man, you were the light in the darkness in that company. You'll get your alien green Lambo if you'll really want it, no doubts on my side bout that.
Good hunting
End Point Moving Average [EPMA]The End Point Moving Average was introduced in the October 95 issue of Technical Analysis of Stocks &
Commodities in the article "The End Point Moving Average", by Patrick E. Lafferty.
The Time Series Forecast takes this value and the slope of the regression line to forecast the next day and then plots this forecasted price as today's value.
For interpretation refer to Mr. Lafferty's article.
Please note
From line 10 starts my personal experemental modifications to this script, all above is original formula by Patrick E. Lafferty.
Bitcoin Best Value CorridorHere is my interpretation of the "Best Time To Buy" Bitcoin over its lifetime using a logarithmic regression trendline. The upper and lower lines are 10% deviations from the centre line. I calculated the trendline in excel and then coded my results into pine script.
Top 40 High Low Strategy for SPY, 5minThis strategy is developed based on my High Low Index SPY Top 40 indicator
Notes:
- this strategy is only developed for SPY on the 5 min chart . It seems to work with QQQ as well, but it isn't optimized for it
- P/L shown is based on 10 SPY option contracts, call or put, with strike price closest to the entry SPY price and expiry of 0 to 1 day. This includes commissions (can be changed). This is only an estimate calculated using an arbitrary multiplier factor, this can be changed in the setting
- P/L is based on $5000 initial capital
- Works with both regular / extended trading session turned on/off. However, max drawdown is 1/2 with extended trading session ON
- there is still a bug that doesn't allow alert to be created due to calculation error, will update once fixed
This strategy combines signals from the following indicators to determine entry signals:
- High Low Index SPY Top 40
- MACD
- Linear Regression Slope
Entry signal is triggered when:
- High Low Index line crosses the EMA line
- MACD trending in the same direction
- Linear Regression slope is accelerating above a threshold in the same direction, indicating a strong trend
Profit target(PT) and stop loss(SL) are determined using ATR value, with 2:1 Reward to Risk ratio as default.
Exit signal may be triggered prior to PT or SL trigger when:
- High Low Index SPY Top 40 shows a reversal after overbought or oversold conditions (optional)
- Opposite entry signal is triggered
There are a number of optional settings:
- Turn on/off "option trading", P/L will be calculated using share price only without multiplication factor for trading option contracts
- # of options per trade, default to 10
- Reinvest with profit made
- Trade with trailing SL after PT hit
- Take profit early based on Top 40 overbought/oversold
- Trade 0/1 day expiry. This will signal exit by the end of the day on Mon/Wed/Fri, and only exits 1/2 of positions (if in profit) on Tues/Thurs
- Can reduce the SL level without impacting PT
- No entry between 10:05 - 10:20 (don't ask me why, but statistically it performs better)
Consider donating me some of your profit if you make $$$ hahaha~ ;)
Enjoy~~
Bitcoin Power Law Bands (BTC Power Law) Indicator█ OVERVIEW
The 'Bitcoin Power Law Bands' indicator is a set of three US dollar price trendlines and two price bands for bitcoin , indicating overall long-term trend, support and resistance levels as well as oversold and overbought conditions. The magnitude and growth of the middle (Center) line is determined by double logarithmic (log-log) regression on the entire USD price history of bitcoin . The upper (Resistance) and lower (Support) lines follow the same trajectory but multiplied by respective (fixed) factors. These two lines indicate levels where the price of bitcoin is expected to meet strong long-term resistance or receive strong long-term support. The two bands between the three lines are price levels where bitcoin may be considered overbought or oversold.
All parameters and visuals may be customized by the user as needed.
█ CONCEPTS
Long-term models
Long-term price models have many challenges, the most significant of which is getting the growth curve right overall. No one can predict how a certain market, asset class, or financial instrument will unfold over several decades. In the case of bitcoin , price history is very limited and extremely volatile, and this further complicates the situation. Fortunately for us, a few smart people already had some bright ideas that seem to have stood the test of time.
Power law
The so-called power law is the only long-term bitcoin price model that has a chance of survival for the years ahead. The idea behind the power law is very simple: over time, the rapid (exponential) initial growth cannot possibly be sustained (see The seduction of the exponential curve for a fun take on this). Year-on-year returns, therefore, must decrease over time, which leads us to the concept of diminishing returns and the power law. In this context, the power law translates to linear growth on a chart with both its axes scaled logarithmically. This is called the log-log chart (as opposed to the semilog chart you see above, on which only one of the axes - price - is logarithmic).
Log-log regression
When both price and time are scaled logarithmically, the power law leads to a linear relationship between them. This in turn allows us to apply linear regression techniques, which will find the best-fitting straight line to the data points in question. The result of performing this log-log regression (i.e. linear regression on a log-log scaled dataset) is two parameters: slope (m) and intercept (b). These parameters fully describe the relationship between price and time as follows: log(P) = m * log(T) + b, where P is price and T is time. Price is measured in US dollars , and Time is counted as the number of days elapsed since bitcoin 's genesis block.
DPC model
The final piece of our puzzle is the Dynamic Power Cycle (DPC) price model of bitcoin . DPC is a long-term cyclic model that uses the power law as its foundation, to which a periodic component stemming from the block subsidy halving cycle is applied dynamically. The regression parameters of this model are re-calculated daily to ensure longevity. For the 'Bitcoin Power Law Bands' indicator, the slope and intercept parameters were calculated on publication date (March 6, 2022). The slope of the Resistance Line is the same as that of the Center Line; its intercept was determined by fitting the line onto the Nov 2021 cycle peak. The slope of the Support Line is the same as that of the Center Line; its intercept was determined by fitting the line onto the Dec 2018 trough of the previous cycle. Please see the Limitations section below on the implications of a static model.
█ FEATURES
Inputs
• Parameters
• Center Intercept (b) and Slope (m): These log-log regression parameters control the behavior of the grey line in the middle
• Resistance Intercept (b) and Slope (m): These log-log regression parameters control the behavior of the red line at the top
• Support Intercept (b) and Slope (m): These log-log regression parameters control the behavior of the green line at the bottom
• Controls
• Plot Line Fill: N/A
• Plot Opportunity Label: Controls the display of current price level relative to the Center, Resistance and Support Lines
Style
• Visuals
• Center: Control, color, opacity, thickness, price line control and line style of the Center Line
• Resistance: Control, color, opacity, thickness, price line control and line style of the Resistance Line
• Support: Control, color, opacity, thickness, price line control and line style of the Support Line
• Plots Background: Control, color and opacity of the Upper Band
• Plots Background: Control, color and opacity of the Lower Band
• Labels: N/A
• Output
• Labels on price scale: Controls the display of current Center, Resistance and Support Line values on the price scale
• Values in status line: Controls the display of current Center, Resistance and Support Line values in the indicator's status line
█ HOW TO USE
The indicator includes three price lines:
• The grey Center Line in the middle shows the overall long-term bitcoin USD price trend
• The red Resistance Line at the top is an indication of where the bitcoin USD price is expected to meet strong long-term resistance
• The green Support Line at the bottom is an indication of where the bitcoin USD price is expected to receive strong long-term support
These lines envelope two price bands:
• The red Upper Band between the Center and Resistance Lines is an area where bitcoin is considered overbought (i.e. too expensive)
• The green Lower Band between the Support and Center Lines is an area where bitcoin is considered oversold (i.e. too cheap)
The power law model assumes that the price of bitcoin will fluctuate around the Center Line, by meeting resistance at the Resistance Line and finding support at the Support Line. When the current price is well below the Center Line (i.e. well into the green Lower Band), bitcoin is considered too cheap (oversold). When the current price is well above the Center Line (i.e. well into the red Upper Band), bitcoin is considered too expensive (overbought). This idea alone is not sufficient for profitable trading, but, when combined with other factors, it could guide the user's decision-making process in the right direction.
█ LIMITATIONS
The indicator is based on a static model, and for this reason it will gradually lose its usefulness. The Center Line is the most durable of the three lines since the long-term growth trend of bitcoin seems to deviate little from the power law. However, how far price extends above and below this line will change with every halving cycle (as can be seen for past cycles). Periodic updates will be needed to keep the indicator relevant. The user is invited to adjust the slope and intercept parameters manually between two updates of the indicator.
█ RAMBLINGS
The 'Bitcoin Power Law Bands' indicator is a useful tool for users wishing to place bitcoin in a macro context. As described above, the price level relative to the three lines is a rough indication of whether bitcoin is over- or undervalued. Users wishing to gain more insight into bitcoin price trends may follow the author's periodic updates of the DPC model (contact information below).
█ NOTES
The author regularly posts on Twitter using the @DeFi_initiate handle.
█ THANKS
Many thanks to the following individuals, who - one way or another - made the 'Bitcoin Power Law Bands' indicator possible:
• TradingView user 'capriole_charles', whose open-source 'Bitcoin Power Law Corridor' script was the basis for this indicator
• Harold Christopher Burger, whose Bitcoin’s natural long-term power-law corridor of growth article (2019) was the basis for the 'Bitcoin Power Law Corridor' script
• Bitcoin Forum user "Trololo", who posted the original power law model at Logarithmic (non-linear) regression - Bitcoin estimated value (2014)
MM Chop Filter Range BoxesMatch with the MM Chop Filter
This draw Non repainting range boxes when the oscillator see a range.
-Breakout Buy/Sell Signals and Exit signals when prices enters a range just in case you did get into a trade. .
-Alarms to match the signals
How to use
Match with the oscillator and always trade the trend with your strategy confirmation and the breakout this indicator provides
Weighted Least Squares Moving AverageLinearly Weighted Ordinary Least Squares Moving Regression
aka Weighted Least Squares Moving Average -> WLSMA
^^ called it this way just to for... damn, forgot the word
Totally pwns LSMA for some purposes here's why (just look up):
- 'realistically' the same smoothness;
- less lag;
- less overshoot;
- more or less same computationally intensive.
"Pretty cool, huh?", Bucky Roberts©, thenewboston
Now, would you please (just look down) and see the comparison of impulse & step responses:
Impulse responses
Step responses
Ain't it beautiful?
"Motivation behind the concept & rationale", by gorx1
Many been trippin' applying stats methods that require normally distributed data to time series, hence all these B*ll**** Bands and stuff don't really work as it should, while people blame themselves and buy snake oil seminars bout trading psychology, instead of using proper tools. Price... Neither population nor the samples are neither normally nor log-normally distributed. So we can't use all the stuff if we wanna get better results. I'm not talking bout passing each rolling window to a stat test in order to get the proper descriptor, that's the whole different story.
Instead we can leverage the fact that our data is time-series hence we can apply linear weighting, basically we extract another info component from the data and use it to get better results. Volume, range weighting don't make much sense (saying that based on both common sense and test results). Tick count per bar, that would be nice tho... this is the way to measure "intensity". But we don't have it on TV unfortunately.
Anyways, I'm both unhappy that no1 dropped it before me during all these years so I gotta do it myself, and happy that I can give smth cool to every1
Here is it, for you.
P.S.: the script contains standalone functions to calculate linearly weighted variance, linearly weighted standard deviation, linearly weighted covariance and linearly weighted correlation.
Good hunting
Linear Regression Channel Breakout StrategyThis strategy is based on LonesomeTheBlue's Linear Regression Channel Indicator. First of all, I would like to thank LonesomeTheBlue. Breaking the Linear Regression Channel to close the candle triggers a Long or Short signal. If the slope of the Linear Regression Channel is positive, it is Short when it breaks out the lower line, and when the slope is negative, it is Long when it breaks out the upper line. The default is optimized for 8-hour candles, and for other hour candles, find the optimal value yourself. Below is a description of LonesomeTheBlue's Linear Regression Channel.
이 전략은 LonesomeTheBlue의 Linear Regression Channel Indicator를 기반으로 만들어졌습니다. 우선 LonesomeTheBlue님께 감사의 말씀을 드립니다. Linear Regression Channel을 돌파하여 봉 마감하면 Long 또는 Short 신호를 트리거합니다. Linear Regression Channel의 기울기가 양인 경우 하단 라인을 돌파하면 Short이고 그 기울기가 음인 경우 상단 라인을 돌파하면 Long입니다. 기본값은 8시간봉에 최적화 되어 있으며, 다른 시간봉은 직접 최적값을 찾아보십시오. 아래는 LonesomeTheBlue의 Linear Regression Channel에 대한 설명을 퍼왔습니다.
________________________________________________
There are several nice Linear Regression Channel scripts in the Public Library. and I tried to make one with some extra features too. This one can check if the Price breaks the channel and it shows where is was broken. Also it checks the momentum of the channel and shows it's increasing/decreasing/equal in a label, shape of the label also changes. The line colors change according to direction.
using the options, you can;
- Set the Source (Close, HL2 etc)
- Set the Channel length
- Set Deviation
- Change Up/Down Line colors
- Show/hide broken channels
- Change line width
meaning of arrows:
⇑ : Uptrend and moment incresing
⇗ : Uptrend and moment decreasing
⇓ : Downtrend and moment incresing
⇘ : Downtrend and moment decreasing
⇒ : No trend
[RS]Long Term Price Range Analysis (MML)Study on Price range Regression and range (deviation multiplier needs to be accommodate manually to fit price action)
study was made for time frames above weekly
[RS]Linear Regression Bands V1experiment with linear regression, the purpose was to catch break outs early, but it creates to much visual noise
same as version 0 but with added margin filter and signal to mark entrys