Indicators Combination Framework v3 IND  [DTU]Hello All,
This script is a framework to analyze and see the results by combine selected indicators for (long, short, longexit, shortexit) conditions. 
I was designed this for beginners and users to facilitate to see effects of the technical indicators combinations on the chart  WITH NO CODE 
You can improve your strategies according the results of this system by connecting the framework to a strategy framework/template such as Pinecoder, Benson, daveatt or custom.
This is enhanced version of my previous indicator "Indicators & Conditions Test Framework  "
Currently there are 93 indicators (23 newly added) connected over library. You can also import an External Indicator or add Custom indicator (In the source)
It is possible to change it from Indicator to strategy (simple one) by just remarking strategy parts in the source code and see real time profit of your combinations
Feel free to change or use it in your source
Special thanks goes to Pine wizards:  Trading view (built-in Indicators),  @Rodrigo, @midtownsk8rguy, @Lazybear, @Daveatt and others for their open source codes and contributions
 SIMPLE USAGE 
1. SETTING: Show Alerts= True (To see your entries and Exists)
2. Define your Indicators (ex: INDICATOR1: ema(close,14), INDICATOR2: ema(close,21), INDICATOR3: ema(close,200)
3. Define Your Combinations for long & Short Conditions
	a. For Long: (INDICATOR1 crossover INDICATOR2) AND (INDICATOR3 < close)
	b. For Short: (INDICATOR1 crossunder INDICATOR2) AND (INDICATOR3 > close)
4. Select Strategy/template (Import strategy to chart) that you export your signals from the list
5. Analyze the best profit by changing Indicators values
 SOME INDICATORS DETAILS 
Each Indicator includes: 
-  Factorization : Converting the selected indicator to Double, triple Quadruple such as EMA to DEMA, TEMA QEMA
-  Log : Simple or log10 can be used for calculation on function entries
-  Plot Type : You can overlay the indicator on the chart (such ema) or you can use stochastic/Percentrank approach to display in the variable hlines range
-  Extended Parametes : You can use default parameters or you can use extended (P1,P2) parameters regarding to indicator type and your choice
-  Color : You can define indicator color and line properties
-  Smooth : you can enable swma smooth 
-  indicators : you can select one of the 93 function like ema(),rsi().. to define your indicator 
-  Source : you can select from already defined indicators (IND1-4), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...) 
 CONDITION DETAILS 
- There are are 4 type of conditions, long entry, short entry, long exit, short exit.
- Each condition are built up from 4 combinations that joined with "AND" & "OR" operators
- You can see the results by enabling show alerts check box
- If you only wants to enter long entry and long exit, just fill these conditions
- If "close on opposite" checkbox selected on settings, long entry will be closed on short entry and vice versa
 COMBINATIONS DETAILS 
- There are 4 combinations that joined with "AND" & "OR" operators for each condition
- combinations are built up from compare 1st entry with 2nd one by using operator
- 1st and 2nd entries includes already defined indicators (IND1-5), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...) 
- Operators are comparison values such as >,<, crossover,...
- 2nd entry include "VALUE" parameter that will use to compare 1st indicator with value area
- If 2nd indicator selected different than "VALUE",  value are will mean previous value of the selection. (ex: value area= 2, 2nd entry=close, means close )
- Selecting "NONE" for the 1st entry will disable  calculation of current and following combinations
 JOINS DETAILS 
- Each combination will join wiht the following one with the JOIN (AND, OR) operator (if the following one is not equal "NONE")
 CUSTOM INDICATOR 
- Custom Indicator defines harcoded in the source code.
- You can call it with "CUST" in the Indicator definition source or combination entries source 
- You can change or implement your custom indicator by updating the source code
 EXTERNAL INDICATOR 
- You can import an external indicator by selecting it from the ext source.
- External Indicator should be already imported to the chart and it have an plot function to output its signal
 EXPORTING SIGNAL 
- You can export your result to an already defined strategy template such as Pine coders, Benson, Daveatt Strategy templates 
- Or you can define your custom export for other future strategy templates
 ALERTS 
- By enabling show alerts checkbox, you can see long entry exits on the bottom, and short entry exits aon the top of the chart
 ADDITIONAL INFO 
- You can see all off the inputs descriptions in the tooltips. (You can also see the previous version for details)
- Availability to set start, end dates
- Minimize repainting by using security function options (Secure, Semi Secure, Repaint) 
- Availability of use timeframes
- 
Version 3 INDICATORS LIST (More to be added):
▼▼▼ OVERLAY INDICATORS ▼▼▼
alma(src,len,offset=0.85,sigma=6).-------Arnaud Legoux Moving Average 
ama(src,len,fast=14,slow=100).-----------Adjusted Moving Average
accdist().-------------------------------Accumulation/distribution index. 
cma(src,len).----------------------------Corrective Moving average    
dema(src,len).---------------------------Double EMA  (Same as EMA with 2 factor)
ema(src,len).----------------------------Exponential Moving Average 
gmma(src,len).---------------------------Geometric Mean Moving Average
highest(src,len).------------------------Highest value for a given number of bars back.   
hl2ma(src,len).--------------------------higest lowest moving average
hma(src,len).----------------------------Hull Moving Average.
lagAdapt(src,len,perclen=5,fperc=50).----Ehlers Adaptive Laguerre filter
lagAdaptV(src,len,perclen=5,fperc=50).---Ehlers Adaptive Laguerre filter variation
laguerre(src,len).-----------------------Ehlers Laguerre filter
lesrcp(src,len).-------------------------lowest exponential esrcpanding moving line
lexp(src,len).---------------------------lowest exponential expanding moving line 
linreg(src,len,loffset=1).---------------Linear regression
lowest(src,len).-------------------------Lovest value for a given number of bars back.
mcginley(src, len.-----------------------McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
percntl(src,len).------------------------percentile nearest rank. Calculates percentile using method of Nearest Rank.
percntli(src,len).-----------------------percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
previous(src,len).-----------------------Previous n (len) value of the source   
pivothigh(src,BarsLeft=len,BarsRight=2).-Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
pivotlow(src,BarsLeft=len,BarsRight=2).--Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
rema(src,len).---------------------------Range EMA (REMA)   
rma(src,len).----------------------------Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sar(start=len, inc=0.02, max=0.02).------Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)    
sma(src,len).----------------------------Smoothed Moving Average
smma(src,len).---------------------------Smoothed Moving Average
super2(src,len).-------------------------Ehlers super smoother, 2 pole 
super3(src,len).-------------------------Ehlers super smoother, 3 pole
supertrend(src,len,period=3).------------Supertrend indicator
swma(src,len).---------------------------Sine-Weighted Moving Average
tema(src,len).---------------------------Triple EMA  (Same as EMA with 3 factor)
tma(src,len).----------------------------Triangular Moving Average
vida(src,len).---------------------------Variable Index Dynamic Average   
vwma(src,len).---------------------------Volume Weigted Moving Average
volstop(src,len,atrfactor=2).------------Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
wma(src,len).----------------------------Weigted Moving Average 
vwap(src_).------------------------------Volume Weighted Average Price (VWAP) is  used to measure the average price weighted by volume     
▼▼▼ NON OVERLAY INDICATORS ▼▼
adx(dilen=len, adxlen=14, adxtype=0).----adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
angle(src,len).--------------------------angle of the series   (Use its Input as another indicator output)
aroon(len,dir=0).------------------------aroon indicator. Aroons major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
atr(src,len).----------------------------average true range. RMA of true range.                
awesome(fast=len=5,slow=34,type=0).------Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
bbr(src,len,mult=1).---------------------bollinger %%
bbw(src,len,mult=2).---------------------Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci(src,len).----------------------------commodity channel index
cctbbo(src,len).-------------------------CCT Bollinger Band Oscilator
change(src,len).-------------------------A.K.A. Momentum. Difference between current value and previous, source - source . is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security
cmf(len=20).-----------------------------Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
cmo(src,len).----------------------------Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog(src,len).----------------------------The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
copcurve(src,len).-----------------------Coppock Curve.  was originally developed by Edwin Sedge Coppock (Barrons Magazine, October 1962).
correl(src,len).-------------------------Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count(src,len).--------------------------green avg - red avg
cti(src,len).----------------------------Ehler s Correlation Trend Indicator by 
dev(src,len).----------------------------ta.dev()  Measure of difference between the series and its ta.sma
dpo(len).--------------------------------Detrended Price OScilator is used to remove trend from price.   
efi(len).--------------------------------Elders Force Index (EFI) measures the power behind a price movement using price and volume.
eom(len=14,div=10000).-------------------Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
falling(src,len).------------------------ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
fisher(len).-----------------------------Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
histvol(len).----------------------------Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
kcr(src,len,mult=2).---------------------Keltner Channels Range  
kcw(src,len,mult=2).---------------------ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
klinger(type=len).-----------------------Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
macd(src,len).---------------------------MACD (Moving Average Convergence/Divergence)
mfi(src,len).----------------------------Money Flow Index s a tool used for measuring buying and selling pressure
msi(len=10).-----------------------------Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
nvi().-----------------------------------Negative Volume Index
obv().-----------------------------------On Balance Volume
pvi().-----------------------------------Positive Volume Index 
pvt().-----------------------------------Price Volume Trend
ranges(src,upper=len, lower=-5).---------ranges of the source. src=src, upper=len, v1:lower=upper .  returns: -1 source=upper otherwise 0
rising(src,len).-------------------------ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc(src,len).----------------------------Rate of Change
rsi(src,len).----------------------------Relative strength Index
rvi(src,len).----------------------------The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
smi_osc(src,len,fast=5, slow=34).--------smi Oscillator
smi_sig(src,len,fast=5, slow=34).--------smi Signal
stc(src,len,fast=23,slow=50).------------Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from 
stdev(src,len).--------------------------Standart deviation
trix(src,len) .--------------------------the rate of change of a triple exponentially smoothed moving average.
tsi(src,len).----------------------------The True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend.
ultimateOsc(len.-------------------------Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
variance(src,len).-----------------------ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
willprc(src,len).------------------------Williams %R
wad().-----------------------------------Williams Accumulation/Distribution.
wvad().----------------------------------Williams Variable Accumulation/Distribution.
 HISTORY 
v3.01
ADD:  23 new indicators added to indicators list from the library. Current Total number of Indicators are 93. (to be continued to adding)
ADD:  2 more Parameters (P1,P2) for indicator calculation added. Par:(Use Defaults) uses only indicator(Source, Length) with library's default parameters. Par:(Use Extra Parameters P1,P2) use indicator(Source,Length,p1,p2) with additional parameters if indicator needs.
ADD:  log calculation (simple, log10) option added on indicator function entries  
ADD:  New Output Signals added for compatibility on exporting condition signals to different Strategy templates.
ADD:  Alerts Added according to conditions results
UPD:  Indicator source inputs now display with indicators descriptions 
UPD:  Most off the source code rearranged and some functions moved to the new library. Now system work like a little bit frontend/backend
UPD:  Performance improvement made on factorization and other source code
UPD:  Input GUI rearranged
UPD:  Tooltips corrected
REM:  Extended indicators removed 
UPD:  IND1-IND4 added to indicator data source. Now it is possible to create new indicators with the previously defined indicators value. ex: IND1=ema(close,14) and IND2=rsi(IND1,20) means IND2=rsi(ema(close,14),20) 
UPD:  Custom Indicator (CUST) added to indicator data source and Combination Indicator source. 
UPD:  Volume added to indicator data source and Combination Indicator source. 
REM:  Custom indicators removed and only one custom indicator left
REM:  Plot Type "Org. Range (-1,1)" removed
UPD:  angle, rising, falling type operators moved to indicator library
Cari dalam skrip untuk "one一季度财报"
Scanner/Screener of Over 40 Coins Per Script I am very scatter-brained by nature and sporadic in my thought processes but if these benefit the community and ya'll ask for more perhaps I will get better and even out a tad....probably not....but you never know. Firstly, allow me to apologize to all the vet/more sophisticated coders out there whose eyes and brains might just be overly taxed due to my poor coding structure. Im just getting started for the first time in ANY sort of coding...so cut me a little slack. Also, if anyone sees any mistakes or the functionality is not as I proclaimed, PLEASE do let me know. In these past 12mo of me learning my 1st coding language (Pinescript) I would say that I have been intently focused on creating all types/sorts of scanners/screeners. Ive always hoped to be a benefit to the community as I was always SO grateful to those who have come before me that have led me to the little bit of progress I have made with Pinescript. This script is not necessarily something that should be traded with as it is just a thrown together example showing a scanner/screener whose results produce plot outputs (ie, Rate of Change / oscillators as well / etc) and how they can be used in the alert system so that only 1 alert has to be set per iteration of the script but more importantly how to use/scan/screen with over 40 coins per script. My intent is not to  trick anyone here. So to be PERFECTLY CLEAR, more than 40 coins CAN in fact be screened/scanned from one script (here I am doing all of KUCOIN's Margin Coins...72 total I look at)...BUT...(heres the catch) it must be added to the chart however many times EQUAL to the amount of "sets" you have in your script. (Heres the limitation by TV) There cannot be more than 40 coins in each "set". The less coins you have per set, the quicker the script will startup and run, thus, the quicker alerts will be received if automating the process. Though, if you only have the free plan and can only have MAX 3 indicators per chart then the MAX you can screen at a time is 120 coins if you use 40 coins per set. So, this is the first one I would like to introduce. For this one your screener/scanner must be using some sort of plots as output that is being screened for. (original inspiration of ALL my variations mainly come from  @QuantNomad, @daveatt, and @LonesomeTheBlue (and a few others I may be forgetting at the moment). Thanks for the inspiration through countless publications that ya'll have created for us in the community.
 Some of my variations are more complex/elegant than others but there are MANY very different ones that I would like to share with the community. If you leave a comment and wonder why I have not responded but did so to every comment around yours...see if you are one of the individuals in this next few sentences...and if you are then perhaps someone else would like to waste their time responding to your comment...but basically, if you don't want to spend the time helping yourself by reading the title, description section, AND the comments section (at least scanning them) then I am MOST DEFINITELY not going to help you down your path of destruction that is most likely soon to be your blown-up trading account. I was called a "masochist" after asking for guidance on if its worth the headache to publish anything on TV bc there will NO DOUBT be comments that'll make me wish I didn't (ie. someone CLEARLY not reading the description (or seemingly even the title sometimes) bc they make a comment that has been explicitly addressed, or someone asking to rebuild the code compatible for another charting software or whatnot, or how about those asking if it repaints (this one is almost always addressed in the comments section but I can understand this question more than others as Im only 1 yr into learning any sort of coding for the first time in the beginning I saw people ask on EVERY script about if it repainted and it was worrisome at the lest (esp bc I didn't even understand what it was not so long ago, or my favorite...what TF it works best on...these people CLEARLY need not be trading yet if your still asking questions as such...Ill end it there). Point being, Ive got some truly VERY useful scripts that I want to share and as long as these people don't make me regret doing so in the beginning, then whats mine...will soon be yours. Though, I will take a little time between the releases.  
          YOU GUYS (TV and its community) ARE AWESOME (most of you anyways ;) 
                                                      MUCH LOVE, 
                                                           ChasinAlts
(1) INPUTS
Here is where the "sets" come in. I am looking at all of KUCOIN's Margin Coins (72 of them at least) so am splitting them up into 3 sets/iterations and a copy of the script must be added equal to amount of "sets" you have here. This is the ONLY workaround I have found to be able to scan/screen with more than 40 coins per script (due to TV's limitation of 40 Security Calls per script)  ***So for everyone saying it's impossible scan more than 40 Coins per scipt...it' MOST DEFINITELY possible....BUT ONLY by adding this script multiple times on the chart and selecting 1 of each of the "sets" in the script settings via the chart window. To save the much needed room you must push each iteration of the script into 1 window and merging the scales of each into 1 scale(ie. "Scale A") within the settings of the script name on the chart(3 horizontal dots) 
(2) FUNCTION
(2.1) COLORIDs
This is just to set up all my Colors of plots which are being matched with their respective labels. I have a diff color for each of the 72 coins Im plotting so Im telling the function, "depending on which set of coins I select...give me this color out of the colors I input later into the function" 
(2.2) TICKERID CONSTRUCTION
I construct the tickerID this way so that the labels on my plots have only the Coin's name vs the label having the (Exchange Name):(Coin Name)(Base Pair Name). If you are using more than 1 Base pair (ie. XRP/BTC and XRP/USDT and XRP/ETH) OR more than 1 Exchange OR want your plots to show MORE THAN just the Trading Coin's name, then the tickerID MUST BE constructed differently
		
(2.3) SECURITY CALL & PLOT OUTPUT VARIABLES
If using a Higher Time Frame in Security Call then it MUST BE adjusted to permit or dissallow repainting if you so wish (BEYOND THE SCOPE OF THIS PUBLICATION so Do Your Own Researh). If your MAIN LOGIC is more complex than simply using a TV built-in function), THEN it MUST BE built into its own function outside of this function and called on within the "expression" slot of this Security Call  OR can also be built into this function and called on in the "expression" slot of this Security call (BEYOND THE SCOPE OF THIS PUB SO DYOR).  FURTHERMORE...when you are using a series(ie high/low/close/open/hl2/etc) / bar_index / time / etc that will be specific to the Coin/tickerID, then they MUST BE explicitly used within the "expression" slot of the Security Function when calling on your Main Logic or else it will pull the series/time/bar_index/etc from the Coin that the Chart is presently on (BEYOND THE SCOPE OF THIS PUB SO DYOR)
(2.4) PLOT LABEL
This is the Plot's Label that will be next to the end of the plot on the LAST bar_index.  ***Notice in the "text" slot of the label I have "_coin" (without the quotes obviously)...this is where have JUST the Coin's name comes into effect on the label vs the (Exchange Name):(Coin Name)(Base Pair Name) which looks MUCH cleaner
(2.5) ALERT LOGIC / ALERT LABEL
Your alert logic need not be as complex as this... I just wanted to create a decent enough timing for this system and wanted to simply print the labels displaying which coin produced the alert at the same time the alerts would go off.  Alert is set up to Trigger Bullish when the ROC is below the Threshold and _chg > _chg  X=length of bars inputted in "Rising/Falling Length" setting and vise versa for Bearish Alerts. If _chg plot only goes past threshold for a VERY few amount of bars NOT providing enough time for initial Alert to trigger, then alert/label triggers on crossing of threshold back towards 0(zero).  ONLY 1 alert needs to be set per script to be able to scan ALL 72 of the coins as I have them in this script. Timing of Alert is inline with the name label printed past the thresholds.
(3) VARIABLES FROM MAIN FUNCTION
This is the tuple of the Main Function that outputs the variables from 3 lines up to be able to plot the lines and color them according to the colors on the labels.  *** As of now, we CANNOT plot from within the function so MUST BE done this way to produce the variables and colors needed. The plots are the ONLY thing in this script that cannot be executed from within the function
(4) LINE PLOTS
ALL output variables from our Main Function are used here for the line plots
Elder Impulse System + ATR BandsDisregard the above chart, I am not sure why it isn't showing the one I want, which is linked below:
  
This is as far as I can tell the closest representation to Dr. Alexander Elder's updated "Elder Impulse System" that has added ATR-volatility bands up to 3x deviations from price.  I got the idea from watching this recent video (www.youtube.com) of Dr. Elder reviewing some recent trades and noticed he had updated his system from his original books.  The Impulse System colour coding was inspired by AstralLoverFlow and LazyBear.  ATR Bands are pre-programmed Keltner Channels with some modifications such as filing in the ATR Zones with user-selected colour bands and modifying the ATR value to better suit the volatility of the market being traded.  
The script has several components, which I will detail below:
 Exponential Moving Averages: 
1) A 13-period EMA that is used as a staple in all of Dr. Elder's technical analysis.  He uses this EMA as the basis for all of his indicators and why it is included here.
2) A 26-period EMA which can be used as a base-line of sorts to filter when to go long or when to go short.  For instance, price over the 26-EMA, price is strong and the rally upwards is likely to continue, underneath it, price is weak and likely to continue downwards for a time.
 Volatility Bands: 
By definition these are nothing more than 3 separate Keltner Channels of a 13-period EMA each set to one additional multiplier from the moving average.  This gives us a 1x, 2x, and 3x multiplier of average volatility from the 13-period EMA based on a 14-period Average True Range (ATR) reading.  The ATR was chosen as it accommodates price gaps and also is the standard formula calculation in TradingView.  The values of the bands cannot be adjusted but the colour coding of them can be.
 Elder Impulse System: 
These colour-coded bars show you the strength and direction of the current chart resolution, calculated by the slope of a 13-period EMA and the slope of a MACD histogram.  These are used not as a buying or selling recommendation alone but as trend filters, as per Dr. Elder's own description of them.  
Green Bars = The 13-period EMA is sloping positively and the MACD histogram is rising compared to previous bars.  The trader should only consider buying/long opportunities when a green bar is most recent.
Red Bars = The 13-period EMA is sloping negatively and the MACD histogram is falling compared to previous bars.  The trader should only consider selling/short opportunities when a red bar is most recent.
Blue Bars = The 13-period EMA and the MACD histogram are not aligned.  One of the indicators is sloping opposite to the other indicator.  These are known as indecision bars and are typically seen near the end of a previously established trend.  The trader can choose to wait for either a green or red bar to shape their trading bias if they are more risk-averse while a counter-trend trader may decide to try opening a position against the currently-established trend.
 How To Trade the System: 
This system is unique in that it is so versatile and will fit the styles of many traders, be it trend following traders (generally the original Elder Impulse System design) or mean-reversion/counter-trend trading (the original Keltner Channel design).  None of the examples below or in the chart above are financial advice and are just there for demonstration purposes only.  
1) The most basic signal given would be the moving average cross up or down.  A cross of the 13-EMA over the 26-EMA signals upward trend strength and the trader could look for buying opportunities.  Conversely, the 13-EMA under the 26-EMA shows downward trend strength and the trader could look for selling opportunities.
2) Following the Elder Impulse system in conjunction with the EMAs.  Look for long opportunities when a green bar is printed and price is over both of the 13- and 26-period EMAs.  Look for short opportunities when a red bar is printed and price is below both of the 13- and 26-period EMAs.  Keep in mind this does not necessarily need a moving average cross to be viable, a green or red bar over both EMAs is a valid signal in this system, usually.  Examine price more closely for better entry signals when a blue bar is printed and price is either above or below both EMAs if you are a trend trader.  This is how Dr. Elder originally intended the system to be used in conjunction with his famous Triple Screen Trading System.  I am not going into detail here as it is a deep subject but I would suggest an interested trader to examine this Triple Screen System further as it is widely accepted as a strong strategy.
3) Mean Reversion and Counter-Trend Trading.  Dr. Elder mentions that the zone between the two EMAs is called the Value Zone.  A mean reversion trader could look for buying opportunities if price has generally been in an uptrend and falls back to value, conversely, they could look for shorting opportunities if price has generally been in a downtrend and rises back to value.  These are your very basic pull backs found in trends that create your higher lows in an uptrend or your lower highs in a downtrend.  A mean reversion/scalper trader may also look to use the upper and lower most ATR bands as an indication of price being overbought or oversold and could look to enter a counter-trend trade here once a blue indecision bar is printed and to ride that move back down to the Value Zone.
 Taking Profits and Risk Management 
This system again is very versatile and will fit a wide range of trading styles.  It has built in take profit levels and risk management depending on your style of trading.
1a) In original Triple Screen Trading (and the original Elder Impulse system), a trader was to place a buy order one tick above a newly printed green bar with a stop loss one tick below the most recent 2-day low, and vice-versa for red bars on short selling. as long as other criteria were met, that I will not go into.  It is all over YouTube and in his books and on Investopedia if you want more information.  The general idea is to continue the trend in the direction if price is strong and you are bought into that move with a close stop, or if price falls back a little bit, you can get in at a better price.  This would be a system typically better suited to a scalper.
1b) The updated risk management according to the above video is to place a stop loss at least 2ATR away from price.  These bands already have calculated these values so a trader can place a stop one tick below the 2 or even 3ATR zones depending on their risk appetite.  This is assuming you have already received a strong buy signal based on the system you follow.  This would be a system typically better suited to a trend-trader.
2a) Taking profits if you are a trend trader has several possibilities.  The first, as Dr. Elder suggests, is to place a price target 2ATR values away from your entry giving you approximately a 1:1 risk-reward ratio.  
2b) The second possibility if the trade is successful is to ride the trend upwards until a blue bar is printed, suggesting indecision in the market.  A modified version of this that could let a winning trade run longer is to wait for the price to close under the 13-EMA in fast markets, or close under the 26-EMA in slightly slower markets to maximize potential winnings.
2c) A scalper trader may wish to have a target at either the value zone if they are playing an extended buy/short back to the mean, or if they are being at the mean, to sell or cover when price extends back out to the 2x or 3x zone.
3) Trend traders can additionally use the ATR zones as a sort of safety guidelines for entering a trade.  Anything within the 1ATR zone is typically a safer entry as the market is less volatile at this time.  Entering when price has gone into the 2ATR zone is signaled as a strong momentum move and can signal a stronger move in the direction of the current closing bar.  While not always the case, it is suggested by Dr. Elder to not enter trend trades at the 3ATR zone as this is where you will be likely looking for a counter-trend retracement back to value and a trader entering here in the direction of the trade has a higher chance of being stopped out or not getting in at the best possible price.
AB=CD Pattern Educational (Source Code)This indicator was intended as educational purpose only for AB=CD Patterns.
AB=CD Patterns were explained and modernized starting from The Harmonic Trader and Harmonic Trading: Volume One until Volume Three written by Scott M Carney.
 Indikator ini bertujuan sebagai pendidikan sahaja untuk AB=CD Pattern.
AB=CD Patterns telah diterangkan dan dimodenkan bermula dari The Harmonic Trader dan Harmonic Trading: Volume One hingga Volume Three ditulis oleh Scott M Carney. 
Indicator features :
1. List AB=CD patterns including ratio and reference page.
2. For desktop display only, not for mobile.
 Kemampuan indikator :
1. Senarai AB=CD pattern termasuk ratio and rujukan muka surat.
2. Untuk paparan desktop sahaja, bukan untuk mobile. 
 FAQ 
1. Credits /  Kredit 
Scott M Carney
Scott M Carney, Harmonic Trading: Volume One until Volume Three
2. Pattern and Chapter involved /  Pattern dan Bab terlibat 
Ideal      AB=CD                 - The Harmonic Trader - Page 118 & 129
Standard   AB=CD                 - The Harmonic Trader - Page 116, 117, 127 & 128, Harmonic Trading: Volume One - Page 42, 51, Harmonic Trading: Volume Three - Page 76 & 78
Alternate  AB=CD                 - The Harmonic Trader - Page 142 & 145,           Harmonic Trading: Volume One - Page 62, 63
Perfect    AB=CD                 - Harmonic Trading: Volume One - Page 64 & 66
Reciprocal AB=CD                 - Harmonic Trading: Volume Two - Page 74 & 76
AB=CD with ab=cd                 - The Harmonic Trader - Page 149 & 153
AB=CD with BC Layering Technique - Harmonic Trading: Volume Three - Page 81 & 84
3. Code Usage / Penggunaan Kod
Free to use for personal usage but credits are most welcomed especially for credits to Scott M Carney.
 Bebas untuk kegunaan peribadi tetapi kredit adalah amat dialu-alukan terutamanya kredit kepada Scott M Carney. 
Bullish / Bearish Ideal AB=CD
  
Bullish / Bearish Standard AB=CD
  
Bullish / Bearish Alternate AB=CD
  
Bullish / Bearish Perfect AB=CD
  
Bullish / Bearish Reciprocal AB=CD (Additional value for reciprocal retracement 3.140 and 3.618)
  
Bullish / Bearish AB=CD with ab=cd 
  
Bullish / Bearish AB=CD with BC Layering Technique 
 
72s Strat: Backtesting Adaptive HMA+ pt.1This is a follow up to my previous publication of  Adaptive HMA+  few months ago, as a mean to provide some kind of initial backtesting tools. Which can be use to explore many possible strategies, optimise its settings to better conform user's pair/tf, and hopefully able to help tweaking your general strategy.
If you haven't read the study or use the indicator, kindly go  here  first to get the overall idea.
The first strategy introduce in this backtest is one most basic already described in the study; buy/sell is when movement is there and everything is on the right side; When RSI has turned to other side, we can use it as exit point (if in profit of course, else just let it hit our TP/SL, why would we exit before profit). Also, base on RSI when we make entry, we can further differentiate type of signals. --Please check all comments in code directly where the  signals ,  entries , and  exits  section are. 
Second additional strategy to check; is when we also use second faster Adaptive HMA+ for exit. So this is like a double orders on a signal but with different exit-rule (/more on this on snapshots below). Alternatively, you can also work the code so to only use this type of exit. 
There's also an additional feature which you can enable its visuals, the  Distance Zone , is to help measuring price distance to our xHMA+. It's just a simple atr based envelope really, I already put the sample code in study's comment section, but better gonna update it there directly for non-coder too, after this.
In this sample I use  Lot  for order quantity size just because that's what I use on my broker. Also what few friends use while we forward-testing it since the study is published, so we also checked/compared each profit/loss report by real number. To use default or other unit of measurement, change the entry code accordingly.
If you change your order size, you should also change the  commission  in Properties Tab. My broker commission is 5 USD per order/lot, so in there with example order size 0.1 lot I put commission 0.5$ per order (I'll put 2.5$ for 0.5 lot, 10$ for 2 lot, and so on). Crypto usually has higher charge. --It is important that you should fill it base on your broker. 
 SETTINGS 
I'm trying to keep it short. Please explore it further again. (Beginner should also first get acquaintance with terms use here.)
 
 ORDERS:  
 Base Minimum Profit Before Exit:  
The number is multiplier of ongoing ATR. Means that when basic exit condition is met, algo will check whether you're already in minimum profit or not, if not, let it still run to TP or SL, or until it meets subsequent exit condition, then it will check again.  
 Default Target Profit:  
Multiplier of ATR at signal. If reached before any  eligible exit condition  is met, exit TP.
 Base StopLoss Point:  
You can change directly in code to use other like ATR Trailing SL, fix percent SL, or whatever. In the sample, 4 options provided.
 Maximum StopLoss:  
This is like a safety-net, that if at some point your chosen SL point from input above happens to be exceeding this maximum input that you can tolerate, then this max point is the one will be use as SL.
 Activate 2nd order...:  
The additional doubling of certain buy/sell with different exits as described above. If enable, you should also set pyramiding to at least: 2. If not, it does nothing.
 ADAPTIVE HMA+ PERIOD 
Many users already have their own settings for these. So in here I only sample the default as first presented in the study. Make it to your adaptive.
 MARKET MOVEMENT 
(1) Now you can check in realtime how much slope degree is best to define your specific pair/tf is out of congestion (yellow) area. And (2) also able to check directly what ATR lengths are more suitable defining your pair's volatility.
 DISTANCE ZONE 
Distance Multiplier. Each pair/tf has its own best distance zone (in xHMA+ perspective). The zone also determine whether a signal should appear or not. (Or what  type  of signal, if you wanna go more detail in constructing your strategy)
 
 USAGE 
(Provided you already have your own comfortable settings for minimum-maximum period of Adaptive HMA+. Best if you already have backtested it manually too and/or apply as an add-on to your working strategy)
1. In our experiences, first most important to define is both elements in the  Market Movement Settings . These also tend to be persistent for whole season since it's kinda describing that pair/tf overall behaviour. Don't worry if you still get a low Profit Factor here, but by tweaking you should start to see positive changes in one of Max Drawdown and Net Profit, or Percent Profitable.
2. Afterwards, find your pair/tf  Distance Zone . When optimising this, what we seek is just a "not to bad" equity curves to start forming. At least Max Drawdown should lessen more. Doesn't have to be great already, but should be better, no red in Net Profit. 
3. Then go manage the "Trailing Minimum Profit", TP, SL, and max SL. 
4. Repeat 1,2,3. 👻
5. Manage order size, commission, and/or enable double-order (need pyramiding) if you like. Check if your equity can handle max drawdown before margin call.
6. After getting an acceptable backtest result, go to  List of Trades  tab and find the biggest loss or when many sequencing loss in a row happened. Click on it to go to exact point on chart,  observe why the signal failed and get at least general idea how it can be prevented . The rest is yours, you should know your pair/tf more than other.
You can also re-explore your minimum-maximum period for both Major and minor xHMA+.
Keep in mind that all numbers in Setting are conceptually in a form of  range . You don't want to get superb equity curves but actually a "fragile" , means one can easily turn it to disaster just by changing only a fraction in one/two of the setting. 
---
If you just wanna test the strength of the indicator alone, you can disable "Use StopLoss" temporarily while optimising settings. 
Using no SL might be tempting in overall result data in some cases, but NOTE: It is  not  recommended to not using SL, don't forget that we deliberately enter when it's in high volatility. If want to add flexibility or trading for long-term, just maximise your SL. ie.: chose SL Point>ATR only and set it maximum. (Check your max drawdown after this).
      I think this is quite important specially for beginners, so here's an example; Hypothetically in below scenario, because of some settings, the buy order after the loss sell signal didn't appear. Let's say if our initial capital only 1000$ using leverage and order size 0,5 lot (risky position sizing already), moreover if this happens at the beginning of your trading season,  that's half of account gone already in one trade . Your max SL should've made you exit after that pumping bar.
  
The Trailing Minimum Profit is actually look like this. Search in the code if you want to plot it. I just don't like too many lines on chart.
  
To maximise profit we can try enabling double-order. The only added rule coded is: RSI should rising when buy and falling when sell. 2nd signal will appears above or below default buy/sell signal. (Of course it's also prone to double-loss, re-check your max drawdown after. Profit factor play its part in here for a long run). Snapshot in comparison:
  
Two default sell signals on left closed at RSI exit, the additional sell signal closed later on when price crossover minor xHMA+. On buy side, price haven't met our minimum profit when first crossunder minor xHMA+. If later on we hit SL on this "+buy" signal, at least we already profited from default buy signal. You can also consider/treat this as multiple TP points. 
For longer-term trading, what you need to maximise is the  Minimum Profit , so it won't exit whenever an exit condition happened, it can happen several times before reaching minimum profit. Hopefully this snapshot can explain:
  
Notice in comparison default sell and buy signal now close in average after 3 days. What's best is when we also have confirmation from higher TF. It's like targeting higher TF by entering from smaller TF. 
As also mention in the study, we can still experiment via original HMA by putting same value for minimum-maximum period setting. This is experimental EU 1H with Major xHMA+: 144-144, Flat market 13, Distance multiplier 3.6, with 2nd order activated.
  
Kiwi was a bit surprising for me. It's flat market is effectively below 6, with quite far distance zone of 3.5. Probably because I'm using big numbers in adaptive period.
  
---
The result you see in strategy tester report below for EURUSD 15m is using just default settings you see in code, as follow:
 
  0,1 lot for each order (which is the smallest allowed by my broker).
  No pyramiding. Commission: 0.5 usd per order. Slippage: 3
  Opening position is only using basic strategy #1 (RSI exit). Additional exit not activated.
  Minimum Profit: 1. TP: 3. 
  SL use: Half-distance zone. Max SL: 4.5.
  Major xHMA+: 172-233. minor xHMA+: 89-121
  Distance Zone Multiplier: 2.7
  RSI: Standard 14.
 
(From our forward-testing, the difference we get from net profit is because of the spread, our entry isn't exactly at the close/open price. Not so much though, but not the same. If somebody can direct me to any example where we can code our entry via current bid/ask price, that would be awesome!)
It's already a long post (sorry), think I'm gonna pause here. Check out the code :)
---
DISCLAIMER:  Past performance is no guarantee of future results , and so on.. you know the drill ;)
Please read whole description first before using, don't take 1-2 paragraph and claim it's the whole logic, you are responsible of your own actions and understanding.
+ BB %B: MA selection, bar coloring, multi-timeframe, and alerts+ %B is, at its simplest, the classic Bollinger Bands %B indicator with a few added bells and whistles.
However, the right combination of bells and whistles will often improve and make a more adaptable indicator.
Classically, Bollinger Bands %B is an indicator that measures volatility, and the momentum and strength of a trend, and/or price movements.
It shows "overbought" and "oversold" spots on a chart, and is also useful for identifying divergences between price and trend (similar to RSI).
With + %B I've added the options to select one or two moving averages, candle coloring, and a host of others.
Let's start with the moving averages:
There are options for two: one faster and one slower. Or combine them how you will, or omit one or both of them entirely.
Here you will find options for SMA, EMA (as well as double and triple), Hull MA, Jurik MA, Least Squares MA, Triangular MA, Volatility Adjusted MA, and Weighted MA.
A moving average essentially helps to define trend by smoothing the noise of movements of the underlying asset, or, in this case, the output of the indicator.
All of these MAs available track this in a different way, and it's up to the trader to figure out which makes most sense to him/her.
MA's, in my opinion, improve the basic %B by providing a clearer picture of what the indicator is actually "seeing", and may be useful for providing entries and exits.
Next up is candle coloring:
I've added the option for this indicator to color candles on the chart based on where the %B is in relation to its upper and lower bounds, and median line.
If the %B is above the median but below the upper bound, candles will be green (showing bullish market structure). If %B is below the median but above the lower bound, candles will be red (denoting bearish market structure).
Overbought and oversold candles will also be colored on the chart, so that a quick glance will tell you whether price action is bullish/bearish or "oversold"/"overbought".
I've also added functionality that enables candles to be colored based on if the %B has crossed up or crossed down the primary moving average.
One example as a way to potentially use these features is if the candles are showing oversold coloration followed by the %B crossing up your moving average coloration. You might consider a long there (or exit a short position if you are short).
And the last couple of tweaks:
You may set the timeframe to whatever you wish, so maybe you're trading on the hourly, but you want to know where the %B is on the 4h chart. You can do that.
The background fill for the indicator is split into bullish and bearish halves. Obviously you may turn the background off, or make it all one color as well.
I've also added alerts, so you may set alerts for "overbought" and "oversold" conditions.
You may also set alerts for %B crossing over or under the primary moving average, or for crossing the median line.
All of these things may be turned on and off. You can pretty much customize this to your heart's delight. I see no reason why anyone would use the standard %B after playing with this.
I am no coder. I had this idea in my head, though, and I made it happen through referencing another indicator I was familiar with, and watching tutorials on YouTube.
Credits:
Firstly, thanks to www.tradingview.com for his brilliant, free tutorials on YouTube.
Secondly, thanks to www.tradingview.com for his beautiful SSL Hybrid indicator (and his clean code) from which I obtained the MAs.
Please enjoy this indicator, and I hope that it serves you well. :)
Uber Stochastic Index v2 + HistogramRealized how useful a histogram could be for a Stochastic, so I added it to my Uber Stochastic. It actually has two histograms - one on the primary stochastic, and one on a stochastic of the stochastic. So you can histogram while you histogram and stoch while you stoch.
The second stoch is actually really useful sometimes as a early warning but can get ugly on some settings. The histograms are also quite fast on fast settings.
What separates the Uber from the standard stoch? Well, you get 7 K stochastics, technically, to weigh together into one. Looks like one, but I assure you its 7 complete stochastics. You can have a long term stochastic with short term influence or a short term with long term influence, or have one thats all-encompassing.
Why histograms? Stochastic is already read similar to MACD, with crossover signals derived from two lines reflected in one another, one slower then the other. It just makes sense. This way, with a slower running histogram, you can more readily "see" it close in. After all, the best trades are rarely made when the stochastic crosses, but rather as it approaches crossing.
I included a lot of settings for max tweaking. The histograms seem to shift in size considerably depending how you have it set, hence the resolution settings for each. I actually recommend setting the 2nd histogram to inverted resolution, that way you can see them more clearly, but you will also see them on both sides of 0. 
And yes, I offset the stochastic so the histogram would look right.
"Wealth beyond measure, Outlander" -Unknown Dunmer
ACD - Layers 1 & 2An implementation of layers 1 & 2 of ACD strategy of Mark Fisher, based on the book "The Logical Trader".
This implementation contains:
- OR lines
- A lines
- C lines
- Daily pivot range
- N days pivot range
- Customizable trading session
Strategy summary (This implementation):
There is 3 main concepts, each of which represented as two price levels.
1) OR (Opening Range) is the range of the first bar of the day. In other words, it's just "high - low" of the first resolution (usually 15min.) bar of the day. So, OR lines (Aqua color) visualize this range for each trading session.
As stated by Mark Fisher in his book, this range is meant to be a statistically significant range such that when price breaks the range in one direction, This is UNUSUAL to infiltrate it again AND break through the other side. So we can consider it as a potential enter signal (long or short).
2) A lines (Blue color) are drawn above and below OR lines with difference of 10% 0f 10 days ATR. The ATR period and the A multiplier (usually 10%) is customizable.
3) C lines (Gray color) are drawn above and below OR lines at 15% of 10 Days ATR difference. These lines help detecting AND confirming that UNUSUAL situation.
These concepts form the layer 1, which you can spot potential opportunities with it.
There is also two ranges to show support and resistance levels based on price action of previous days. Pivot ranges are rolling ranges that calculated and last for each day separately. They only differ in calculation period - the first one is daily (yellow color area) and the other one (red color area) is customizable, but is usually 3 or 5 days.
Each range consists of two price levels, valid for the current trading session. One of theme is HL2 , and the other one is "HLC3 + abs(HLC3 - HL2 )".
These two ranges, "Daily pivot range" and "N days pivot range", form the layer 2, which you can see them as two dynamic support/resistance ranges - one for daily, and the other for N days. They help filtering opportunities spotted from layer 1.
There is 2 more layers in the ACD strategy, which is omitted in this free implementation.
Trend Reversal Indicator (EMA of slopes)Good morning Traders
Inspirated by  lukescream  EMA-slope strategy, today I want to share with you this simple indicator whose possible use-case would be for detecting in advance possible trend reversals, specially on higher timeframes.  
Once that you've chosen the desired source (RSI, EMA or Stochastic k or d), the indicator will calculate its "slope" approximating its first order derivative by the division between the last variation of the series and its last value.
You can see the slope as a white line by enabling the relative checkmark (it's disabled by default since it simply messes up the the graph)
Then, the slope itself becomes the source for two exponential moving averages: the fast one (in blue) has a period of 20 while the slow one (in red, it becomes similiar to a horizontal line actually) has a period of 500
Why the slope? Since all the sources mentioned before are directly or indirectly calculated on the price action, a more aggressiveness in the price movement would be translated into a more (positive/negative) steepness of those indicator (of course this effect would be far more evident if the indicators are calculated on low periods, but really low periods could compromise the consistency of the signals). 
In this way, the slope would mirror the decisiveness of price movements and a comparison between two averages calculated from it (the first one based on more recent values, the second one that conisders also older values) could tell you in advance what direction the market is possibly about to take 
The usage is simple: once that the fast moving average crosses upward the slow one, this could be a sign of potential trend reversal from bearish to bullish. On the contrary, if the fast EMA crosses downward the slow one, this could be a sign of potential trend reversal from bullish to bearish.
What I suggest you is to integrate this indicator with Exponential Moving Averages plotted on the price candles, in order to have a general bias for opening long or short positions, and with an oscillator as well such as the Stochastisc RSI in order to detect the overbought/oversold zones for opening/closing positions at the right moment.
Happy Trading! 
|AG| Previous Analysis█  OVERVIEW 
Analysis of previous levels is one of the best strategies in order to get good entries or take profits levels. This analysis involves Monthly and Weekly Previous Levels and One User Definition Option. So u could select any period like Daily or even hours according to ur trading style. The previous levels are High and Low. And the Current (NOT PREVIOUS) open level.
This script also includes one Fibonacci Selector that will calculate the Fibbo level between previous High and Low Levels of the user selection. Almost everything could be modified in the input panel. 
 Input Options 
A detailed explanation of input settings:
 • # Of Previous
   • This option leads us to select the number of previous weeks, months, or the user selection back.
      • Example: If we select Previous High, Low WEEKLY so if # Of previous is one is going to be the past levels but if is 2 so consequently 2 previous levels.
       • In the case of 0 is going to be the actual levels 
 • Fibbo & Label Selector
  Here we can select the period.
   • Monthly, Weekly, And User Definition is available.
      • Fibonacci Selector :
      • Here we could choose between different levels of Fibonacci or No_Plot Option
 • Label Offset
      • Here we select the amount of distance between label and actual price
 • Time Start
      • Here we could highlight one period START and END like one Week start day and end day.
      • User Definition Value in order to be more flexible. 
Interesting Code Lines:
 • Fibonacci function
 
getFib(a, b)=>
    fib1 = a + (b - a) * -0.618
    fib2 = a + (b - a) * -0.270
    fib3 = a + (b - a) *  0.114
    fib4 = a + (b - a) *  0.214
    fib5 = a + (b - a) *  0.382
    fib6 = a + (b - a) *  0.500
    fib7 = a + (b - a) *  0.618
    fib8 = a + (b - a) *  0.786
    fib9 = a + (b - a) *  0.886
    ext_ = a + (b - a) *  1.270
    ext1 = a + (b - a) *  1.618
      
 
 • Exact Distance and % Distance
 
f_dist (_src, _src3) =>
    float _dist = _src3 - _src
    float _perc = _dist / _src3 //* 100
     
Difference over barsDescription:
One of my followers asked about an indicator that shows the difference between the open and a previous close and didn't find one so I wrote this one. This is similar to a momentum indicator except it offers more flexibility. While the standard momentum indicator calculates a difference between current close and a previous close (sometimes customizable to work on open, high or lows instead of close), this allows to mix and match between open, high, low and close. It also offers multiple kinds of moving averages.
Settings:
 
  Current point of reference  
  Previous point of reference  
  Difference over how many bars?
 
How it works:
The indicator calculates the difference between the current point of reference and a previous (n-bars back) point of reference (where n is given by the "Difference over how many bars?").
How to use it:
 
  find historical support lines like the 0.68 line in the cart above where in the past the indicator tends to bounce back; similarly find resistance lines like the -0.75 line in the chart (which servers as a resistance line both for the main indicator line   and its moving average  )
  look for convergence between the price and the indicator; for example, if the price is going up and the indicator is going down a change in the price direction may be coming soon
  look for the indicator crossing its moving average: moving up will signify an up trend and vice-versa
  since the difference between the open and previous close (which is what the blue line in the chart shows) since to go up to 0.68 (the upper horizontal line) and down to -0.75 (the lower horizontal line) most of the time, one strategy, using options, is to to buy, right before the close of a trading day, a "long iron butterfly": buy-to-open (BTO) both a call and a put at the strike price and sell-to-open (STO) a call at a strike of around $0.68 more and sell to open a put at a strike of around $0.75 less. The STO legs should be for the next expiration and the BTO legs for the next expiration after that. This way the STO will decrease their time value faster than the BTO legs if the price stays flat (which plays to your advantage) and the BTO legs may make profit if the next day it opens away from the price at which the ticker closed the previous day (when the position was opened). The most profit is when it moves right up to one of the STO legs. This position would normally be closed next day at opening. The percentage of profit it makes is low compared to other strategies but also the percentage of the total cost at risk is also low which could potentially allow a trader to increase the lot and thus, in the end, the total profit amount may be comparable to other strategies. 
 
Notes: 
 
  The indicator in the chart above comes with the standard options. For a more standard momentum indicator set both the current and previous reference point to the same OHLC value (such as "close").
  The 0.68 and -0.75 levels are for open/close (current/previous point of reference) for ticker INTC. Obviously, other tickers will likely have other levels and you will have to find those yourself. If you use INTC but use other combination of current and previous reference points, they will have different levels as well.
 
Percent Calculator (Return On Investment Target Price)First and foremost: I was inspired to publish my first script after reading some of the other member's scripts -a token of my appreciation and support, Thank You.
The percent calculator is a very simple and basic indicator to use, it''s function is to simply output the target price from either the close or ones trade-entry based on a desired percent return on investment (R.O.I.).
Say you want to profit 15% from your entry: simply plug in your entry value and the number 15 into the appropriate settings and the indicator displays what the target price should be (rounded to two decimal places).
The percent calculator also goes one step further by finding the average percent return on investment over a desired interval of time (the default is 20 candles) as well as allows one to adjust the size of the price move the average percent return on investment is being calculated for.
Say you want to find the average percent return on investment for a 3 candle swing over a 200 candle interval of time: simply plug the number 200 into the interval setting and the number 3 into the price-move setting and the indicator displays what the average 3 candle swing returns on investment.
Practical Application: comparing ones desired return on investment to the average return on investment can help determine how realistic ones goals are... it's unlikely to achieve 100% return on investment if the average is only around 10% (given the parameters one is working within) but on the other hand achieving 5% return on investment is highly likely.
SIMPLE MOVING AVG 10,20,50,100,200 with RESOLUTIONThis indicator is the best than all other sma indicators.Because in just one click you can change all the resolution /time frames for all the sma .
Multitime frame analysis can be done in just one click. just change the resolution to
15 min/30 min/1hr- if you intraday trader
1D- LONG TERM INVESTORS.
Multi-timeframe analysis (MTF) is a process in which traders can view the same ticker/indicator using a higher time frame than the chart’s, for example, displaying a daily moving average on a one-hour chart in just two clicks.
How to Use this to Buy Stocks ?
The technical indicator known as the Death cross occurs when the 50-day SMA crosses below the 200-day SMA => Bearish Signal.
An opposite indicator, known as the Golden cross, occurs when the 50-day SMA crosses above the 200-day SMA => Bullish Signal.
Crossovers are one of the main moving average strategies.
1st Strategy is the first type is a price crossover, which is when the price crosses above the sma => Buy signal
when the price crosses below the sma => Sell signal
2nd Strategy is to apply two moving averages to a chart: one longer and one shorter.
When the shorter-term MA (100) crosses above the longer-term MA (200), it's a buy signal, indicates trend is shifting up.
This is known as a "Golden cross."
Meanwhile, when the shorter-term MA (100) crosses below the longer-term MA (200), it's a sell signal, indicates trend is shifting down.
This is known as a "Dead/death cross."
The time frame or length you choose for a moving average, also called the "look back period," can play a big role in how effective it is.
An MA with a short time frame will react much quicker to price changes than an MA with a long look back period. In the figure below, the 20-day moving average more closely tracks the actual price than the 100-day moving average does.
A 20-day MA = more beneficial to a shorter-term trader, since it follows the price more closely.
A 100-day MA = more beneficial to a longer-term trader.
Moving averages work quite well in strong trending conditions but poorly in choppy or ranging conditions.
use this indicator along with Price action theory and not alone.
Moving average crossovers are a popular strategy for both entries and exits. MAs can also highlight areas of potential support or resistance
Happy Trading
Bitcoin Margin Call Envelopes [saraphig & alexgrover]Bitcoin is the most well known digital currency, and allow two parties to make a transaction without the need of a central entity, this is why cryptocurrencies are said to be decentralized, there is no central unit in the transaction network, this can be achieved thanks to cryptography. Bitcoin is also the most traded cryptocurrency and has the largest market capitalization, this make it one of the most liquid cryptocurrency.
There has been tons of academic research studying the profitability of Bitcoin as well as its role as a safe heaven asset, with all giving mixed conclusions, some says that Bitcoin is to risky to be considered as an hedging instrument while others highlight similarities between Bitcoin and gold thus showing evidence on the usefulness of Bitcoin acting as an hedging instrument. Yet Bitcoin seems to attract more short term speculative investors rather than other ones that would use Bitcoin as an hedging instrument.
Once introduced, cryptocurrencies where of course heavily analyzed by technical analyst, and technical indicators where used by retail as well as institutional investors in order to forecast the future trends of bitcoin. I never really liked the idea of designing indicators that specifically worked for only one type of market and ever less on only one symbol. Yet the user @saraphig posted in Feb 20 an indicator called " Margin Call MovingAverage " who calculate liquidation price by using a volume weighted moving average. It took my attention and we decided to work together on a relatively more complete version that would include resistances levels.
I believe the proposed indicator might result useful to some users, the code also show a way to restrict the use of an indicator to only one symbol (line 9 to 16).
 The Indicator 
The indicator only work on BTCUSD, if you use another symbol you should see the following message:
  
The indicator plot 6 extremities, with 3 upper (resistance) extremities and 3 lower (support) extremities, each one based on the isolated margin mode liquidation price formula:
 UPlp = MA/Leverage × (Leverage+1-(Leverage*0.005)) 
for upper extremities and:
 DNlp = MA × Leverage/(Leverage+1-(Leverage*0.005)) 
for lower extremities.
Length control the period of the moving averages, with higher values of length increasing the probability of the price crossing an extremity. The Leverage's settings control how far away their associated extremities are from the price, with lower values of Leverage making the extremity farther away from the price, Leverage 3 control Up3 and Dn3, Leverage 2 control Up2 and Dn2, Leverage 1 control Up1 and Dn1, @saraphig recommend values for Leverage of either : 25, 20, 15, 10 ,5.
You can select 3 different types of moving average, the default moving average is the volume weighted moving average (VWMA), you can also choose a simple moving average (SMA) and the Kaufman adaptive moving average (KAMA).
Based on my understanding (which could be wrong) the original indicator aim to highlight points where margin calls might have occurred, hence the name of the indicator. 
If you want a more "DSP" like description then i would say that each extremity represent a low-pass filter with a passband greater than 1 for upper extremities and lower than 1 for lower extremities, unlike bands indicators made by adding/subtracting a volatility indicator from another moving average this allow to conserve the original shape of the moving average, the downside of it being the inability to show properly on different scales.
  
here length = 200, on a 1h tf, each extremities are able to detect short-terms tops and bottoms. The extremity become wider when using lower time-frames.
  
You would then need to increase the Leverages settings, i recommend a time frame of 1h.
 Conclusion 
I'am not comfortable enough to make a conclusion, as i don't know the indicator that well, however i liked the original indicator posted by @saraphig and was curious about the idea behind it, studying the effect of margin calls on market liquidity as well as making indicators based on it might result a source of inspiration for other traders.
A big thanks to @saraphig who shared a lot of information about the original indicator and allowed me to post this one. I don't exclude working with him/her in the future, i invite you to follow him/her:
www.tradingview.com
Thx for reading and have a nice weekend! :3
Extended Recursive Bands - Maximum Efficiency With Extra OptionsIntroducing A New Calculation For Efficient Bands Calculation ! 
Here it is ! The Recursive Bands Indicator, an indicator specially created to be extremely efficient, i think you already know that calculation time is extra important in algorithmic trading, and this is the principal motivation for the creation of the proposed indicator. Originally described in my paper  "Pierrefeu, Alex (2019): Recursive Bands - A New Indicator For Technical Analysis" , the indicator framework has been widely used in my previous uploaded indicators, however it would have been a shame to not upload it, however user experience being a major concern for me, i decided to add extra options, which explain the term "extended".
 On The Indicator Calculation 
You can skip this part if it doesn't interest you. The calculation of the indicator is based on recursion, but i want to explain the mathematical formula described in the paper.
  
I've seen some users trying to remake it from the calculations, however there was always something weird, and i understand, mathematical notations are always a bit weird, even myself don't always write them correctly/understand them, however this one is relatively simple to understand.
First lets explain each elements of the calculation :
α = smoothing constant, or  2/(length+1) 
max/min = maximum and minimum function, max return the greatest input value while min return the lowest one, for example :
 max(4,2) = 4  while  min(4,2) = 2 
the "||" notation mean taking the absolute value, for example : |-1| = abs(-1) = 1
The calculation after the max/min function is called the correction factor, and is the core of the indicator. The last two variables are just here to provide an initial value for upper and lower, basically when we start our calculations we will assign the value of the closing price for upper and lower.
The motivation behind using a smoothing constant in range of (0,1) was to tell the reader that the indicator is easily made adaptive, this is what i did on my adaptive trailing stop indicator by using the efficiency ratio as smoothing variable, the user can use  1/length  instead of the provided calculation for alpha.
If you interested on the indicator main logic, it is actually really simple, by using  upper = max(price,upper)  and  lower = min(price,lower)  we would get the maximum/minimum price value at time  t , therefore upper can only be greater or equal than its precedent value, while lower can only be lower or equal than its precedent value, in order to fix that we subtract/sum upper/lower with a value, this allow the upper band to be lower than its precedent value and lower to be greater than its precedent value, this is the role of the correction factor.
 The Indicator 
The indicator display one upper and one lower band, every common usages applied to bands indicators such as support/resistance, breakout, trailing stop...etc, can also be applied to this one.  length  control how reactive the bands are, higher values of length will make the bands cross the price less often.
In order to provide more flexibility for the user i added the option to use various methods for the calculation of the indicator, therefore the indicator can use the average true range, standard deviation, average high-low range, and one totally exclusive method specially designed for this indicator.
 Classic Method 
This option make the indicator use its classical calculation, this is the most efficient method of all.
  
 Atr Method (atr) 
This method use the average true range as correction factor, notice that lower values of length can still produce wide band.
  
 Standard Deviation Method (stdev) 
This method use a biased estimate of the standard deviation as correction factor.
  
The method produce smoother bands that converge more slowly toward the price in comparison with the classic correction factor.
 Average High-Low Range Method (ahlr) 
This method use the average of the high-low range as correction factor, extremely similar to the average true range.
  
 Rising Falling Volatility (rfv) Method 
A new method created for this indicator, this correction factor use the absolute prices changes when price value is greater/lower than any  length  past values of the price, this allow to have more boxy shaped bands, work best with greater values of length.
  
The bands can be in contact with this method, a possible fix in the future.
 Conclusion 
The recursive band indicator is one of my greatest indicators in my opinion (i would love to have yours), as you can see the idea behind it is extremely simple and allow for a super efficient band indicator, which was the original motivation behind it, in order to provide more fun for the users i also added more option for the correction factor, this allow the user to be creative and not get stuck with the original calculation.
Like the trend step indicator family we have almost ended our series on the recursive band framework, 1 more trailing stop will be added in the future, and then we'll have more "boring" stuff until i find something cool again, it shouldn't be long ;)
Thanks for reading !
How to avoid repainting when using security() - PineCoders FAQNOTE 
The non-repainting technique in this publication that relies on bar states is now deprecated, as we have identified inconsistencies that undermine its credibility as a universal solution. The outputs that use the technique are still available for reference in this publication. However, we do not endorse its usage. See  this publication  for more information about the current best practices for requesting HTF data and why they work. 
This indicator shows how to avoid repainting when using the  security()  function to retrieve information from higher timeframes.
 What do we mean by repainting? 
Repainting is used to describe three different things, in what we’ve seen in TV members comments on indicators:
1. An indicator showing results that change during the realtime bar, whether the script is using the  security()  function or not, e.g., a Buy signal that goes on and then off, or a plot that changes values.
2. An indicator that uses future data not yet available on historical bars.
3. An indicator that uses a negative  offset=  parameter when plotting in order to plot information on past bars.
The repainting types we will be discussing here are the first two types, as the third one is intentional—sometimes even intentionally misleading when unscrupulous script writers want their strategy to look better than it is.
Let’s be clear about one thing:  repainting is not caused by a bug ; it is caused by the different context between historical bars and the realtime bar, and script coders or users not taking the necessary precautions to prevent it.
 Why should repainting be avoided? 
Repainting matters because it affects the behavior of Pine scripts in the realtime bar, where the action happens and counts, because that is when traders (or our systems) take decisions where odds  must  be in our favor.
Repainting also matters because if you test a strategy on historical bars using only OHLC values, and then run that same code on the realtime bar with  more  than OHLC information, scripts not properly written or misconfigured alerts will alter the strategy’s behavior. At that point,  you will not be running the same strategy you tested, and this invalidates your test results , which were run while not having the additional price information that is available in the realtime bar.
The realtime bar on your charts is only one bar, but it is a very important bar. Coding proper strategies and indicators on TV requires that you understand the variations in script behavior and how information available to the script varies between when the script is running on historical and realtime bars.
 How does repainting occur? 
Repainting happens because of something all traders instinctively crave: more information. Contrary to trader lure, more information is not always better. In the realtime bar, all TV indicators (a.k.a.  studies ) execute every time price changes (i.e. every  tick ). TV  strategies  will also behave the same way if they use the  calc_on_every_tick = true  parameter in their  strategy()  declaration statement (the parameter’s default value is  false ). Pine coders must decide if they want their code to use the realtime price information as it comes in, or wait for the realtime bar to close before using the same OHLC values for that bar that would be used on historical bars.
Strategy modelers often assume that using realtime price information as it comes in the realtime bar will always improve their results. This is incorrect. More information does not necessarily improve performance because it almost always entails more noise. The extra information may or may not improve results; one cannot know until the code is run in realtime for enough time to provide data that can be analyzed and from which somewhat reliable conclusions can be derived. In any case, as was stated before, it is critical to understand that if your strategy is taking decisions on realtime tick data, you are NOT running the same strategy you tested on historical bars with OHLC values only.
 How do we avoid repainting? 
It comes down to using reliable information and properly configuring alerts, if you use them. Here are the main considerations:
1. If your code is using  security()  calls, use the syntax we propose to obtain reliable data from higher timeframes.
2. If your script is a strategy, do not use the  calc_on_every_tick = true  parameter unless your strategy uses previous bar information to calculate.
3. If your script is a study and is using current timeframe information that is compared to values obtained from a higher timeframe, even if you can rely on reliable higher timeframe information because you are correctly using the  security()  function, you still need to ensure the realtime bar’s information you use (a cross of current close over a higher timeframe MA, for example) is consistent with your backtest methodology, i.e. that your script calculates on the close of the realtime bar. If your system is using alerts, the simplest solution is to configure alerts to trigger  Once Per Bar Close . If you are not using alerts, the best solution is to use information from the  preceding  bar. When using previous bar information, alerts can be configured to trigger  Once Per Bar  safely.
 What does this indicator do? 
It shows results for 9 different ways of using the  security()  function and illustrates the simplest and most effective way to avoid repainting, i.e. using  security()  as in the example above. To show the indicator’s lines the most clearly, price on the chart is shown with a black line rather than candlesticks. This indicator also shows how misusing  security()  produces repainting. All combinations of using a 0 or 1 offset to reference the series used in the  security() , as well as all combinations of values for the  gaps=  and  lookahead=  parameters are shown.
The  close  in the call labeled “BEST” means that once security has reached the upper timeframe (1 day in our case), it will fetch the previous day’s value.
The  gaps=  parameter is not specified as it is off by default and that is what we need. This ensures that the value returned by  security()  will not contain na values on any of our chart’s bars.
The  lookahead security()  to use the last available value for the higher timeframe bar we are using (the previous day, in our case). This ensures that  security()  will return the value at the end of the higher timeframe, even if it has not occurred yet. In our case, this has no negative impact since we are requesting the previous day’s value, with has already closed.
The indicator’s  Settings/Inputs  allow you to set:
- The higher timeframe  security()  calls will use
- The source  security()  calls will use
- If you want identifying labels printed on the lines that have no gaps (the lines containing gaps are plotted using very thick lines that appear as horizontal blocks of one bar in length)
For the lines to be plotted, you need to be on a smaller timeframe than the one used for the  security()  calls.
Comments in the code explain what’s going on.
 Look first. Then leap.  
Triple Kijun Trend by SpiralmanIspired from "Oscars Simple Trend Ichimoku Kijun-sen" by CapnOscar
Script displays 3 kijun lines: one for current TF, second one emulates it for TF 4 times higher, third one for x16.
For example on 1H chart there will be 3 kijuns: one for 1H, second one for 4H (emulated), third one for 16H (emulated).
Kijuns change colors based on their position relative to price. 
Kijun Sen
The base line, the slower EMA derivative, and a dynamic representation of the mean. With that said, the Kijun serves as both critical support and resistance levels for price. How does it work, and why would the Kijun be superior to commonly used moving average indicators? Fun fact: The Kijun dynamically equalizes itself to be the 50% retracement (or 0.5 Fibonacci level) of price for any given swing, and price will ALWAYS gravitate to the Kijun at some point regardless of how far above or below it is from it. By taking the median of price extremes, the Kijun accounts for volatility that other MAs or EMAs do not. A flat horizontal Kijun means that price extremes have not changed, and that the current trend losing momentum. Crypto-adjusted calculation: (highest high + lowest low) / 2 calculated over the last 60 periods.
Back to zero: Understanding seriestype: pine series basic example
time required: 10 minutes
level: medium (need to know the "array" data variable as a generic programming concept, basic Pine syntax) 
tl;dr  how variables and series work in Pine 
Pine is an array/vector language. That's something that twists how it behaves, and how we have to think about it. A lot of misunderstandings come from forgetting this fact. This example tries to clear that concept. 
First, you need to know what an array is, and how it  works in a programmig language. Also, having javascript under your belt helps too. If you don't, google "javascript array basic tutorial" is your friend :)
So, in pine arrays are called "series". Every variable is an array with values for each candle in the chart. if we do: 
 
myVar = true 
this is not a constant. It is a series of values for each candle, { true, true,....., true }
In practice, the result is the same, but we can access each of the values in the series, like myVar{0}, myVar{7}, myVar{anyNumber}....
Again, it is not a constant, since you can access/modify the each value individually
so, lets show it: 
 plot (myVar, clolor = gray) 
this plots an horizontal line of value 1 ( 1 is equal to true ) so it's all good. 
On to a more usual series: 
 tipicalSeries = close > open ? true : false 
plot(tipicalSeries, color= blue) 
This gives the expected result, a tipical up and down line with values at 1 or 0. Naturally, "tipicalSeries" is an array, the "ups" and "downs" are all stored under the same variable, indexed by the candles. 
In Pine, the ZERO position in the array is the last one, which corresponds to the last candle on the right. Say you have a chart with 12 candles. The close  would be the closing value of what we intuitively think as first candle, the one on the left. then close ... and so on.... until close , the value of the "last" candle, the one on the right. It actually helps to start thinking of the positions backwards, counting down to zero, rocket launch style  :)
And back to our series. The myVar will also be the same size, from myVar  to myVar . 
When we do some operation with them, something simple like 
 if ( myVar == tipicalSeries)  
what is really happening is that internally, Pine is checking each of the indexes, as in myVar  == tipicalSeries  , myVar  == tipicalSeries  .... myVar  == tipicalSeries 
And we can store that stuff to check it. simply:
 result = (myVar == tipicalSeries) ? true : false  //yes, this is the same as tipicalSeries, but we're not in a boolean logic tut  ;)
plot (result) 
The reason we can plot the result is that it is an array, not a single value. The example indicator i provide shows a plot where the values are obtained from different places in the array, this line here: 
 mySeries3 = mySeries2  and mySeries1   
this creates a series that is the result of the PREVIOUS values stored (the zero index is the one most at the right, or the "current" one), which here just causes a shift in the plotted line by one candle.
Go ahead, grab a copy of my code, try to change the indexes and see the results. Understanding this stuff is critical to go deeper into Pine  :) 
US/SPY- Financial Regime Index Swing Strategy Credits: concept inspired by EdgeTools Bloomberg Financial Conditions Index (Proxy)
 
Improvements: eight component basket, inverse volatility weights, winsorization option( statistical technique used to limit the influence of outliers in a dataset by replacing extreme values with less extreme ones, rather than removing them entirely), slope and price gates, exit guards, table and gradients.
 Summary in one paragraph
 A macro regime swing strategy for index ETFs, futures, FX majors, and large cap equities on daily calculation with optional lower time execution. It acts only when a composite Financial Conditions proxy plus slope and an optional price filter align. Originality comes from an eight component macro basket with inverse volatility weights and winsorized return z scores that produce a portable yardstick. 
 Scope and intent 
Markets: SPY and peers, ES futures, ACWI, liquid FX majors, BTC, large cap equities.
Timeframes: calculation daily by default, trade on any chart.
Default demo: SPY on Daily.
Purpose: convert broad financial conditions into clear swing bias and exits.
 Originality and usefulness
 
Unique fusion: return z scores for eight liquid proxies with inverse volatility weighting and optional winsorization, then slope and price gates.
Failure mode addressed: false starts in chop and early shorts during easy liquidity.
Testability: all knobs are inputs and the table shows components and weights.
Portable yardstick: z scores center at zero so thresholds transfer across symbols.
 Method overview in plain language
 Base measures
Return basis: natural log return over a configurable window, standardized to a z score. Winsorization optional to cap extremes.
 Components
 EQ US and EQ GLB measure equity tone.
CREDIT uses LQD over HYG. Higher credit quality outperformance is risk off so sign is flipped after z score.
RATES2Y uses two year yield, sign flipped.
SLOPE uses ten minus two year yield spread.
USD uses DXY, sign flipped.
VOL uses VIX, sign flipped.
LIQ uses BIL over SPY, sign flipped.
Each component is smoothed by the composite EMA.
 Fusion rule 
Weighted sum where weights are equal or inverse volatility with exponent gamma, normalized to percent so they sum to one.
 Signal rule
 Long when composite crosses up the long threshold and its slope is positive and price is above the SMA filter, or when composite is above the configured always long floor.
Short when composite crosses down the short threshold and its slope is negative and price is below the SMA filter.
Long exit on cross down of the long exit line or on a fresh short signal.
Short exit on cross up of the short exit line or on a fresh long signal, or when composite falls below the force short exit guard.
 What you will see on the chart
 
Markers on suggestion bars: L for long, S for short, LX and SX for exits.
Reference lines at zero and soft regime bands at plus one and minus one.
Optional background gradient by regime intensity.
Compact table with component z, weight percent, and composite readout.
Table fields and quick reading guide
Component: EQ US, EQ GLB, CREDIT, RATES2Y, SLOPE, USD, VOL, LIQ.
Z: current standardized value, green for positive risk tone where applicable.
Weight: contribution percent after normalization.
Composite: current index value.
Reading tip: a broadly green Z column with slope positive often precedes better long context.
 Inputs with guidance
Setup
 
Calc timeframe: default Daily. Leave blank to inherit chart.
Lookback: 50 to 1500. Larger length stabilizes regimes and delays turns.
EMA smoothing: 1 to 200. Higher smooths noise and delays signals.
Normalization
Winsorize z at ±3: caps extremes to reduce one off shocks.
Return window for equities: 5 to 260. Shorter reacts faster.
Weighting
Weight lookback: 20 to 520.
Weight mode: Equal or InvVol.
InvVol exponent gamma: 0.1 to 3. Higher compresses noisy components more.
Signals
Trade side: Long Short or Both.
Entry threshold long and short: portable z thresholds.
Exit line long and short: soft exits that give back less.
Slope lookback bars: 1 to 20.
Always long floor bfci ≥ X: macro easy mode keep long.
Force short exit when bfci < Y: macro stress guard.
 Confirm 
Use price trend filter and Price SMA length.
 View 
Glow line and Show component table.
 Symbols 
SPY ACWI HYG LQD VIX DXY US02Y US10Y BIL are defaults and can be changed.
 Realism and responsible publication
 
No performance claims. Past is not future.
Shapes can move intrabar and settle on close.
Execution is on standard candles only.
 Honest limitations and failure modes
 
Major economic releases and illiquid sessions can break assumptions.
Very quiet regimes reduce contrast. Use longer windows or higher thresholds.
Component proxies are ETFs and indexes and cannot match a proprietary FCI exactly.
 Strategy notice
 Orders are simulated on standard candles. All security calls use lookahead off. Nonstandard chart types are not supported for strategies.
 Entries and exits
 
Long rule: bfci cross above long threshold with positive slope and optional price filter OR bfci above the always long floor.
Short rule: bfci cross below short threshold with negative slope and optional price filter.
Exit rules: long exit on bfci cross below long exit or on a short signal. Short exit on bfci cross above short exit or on a long signal or on force close guard.
 Position sizing
 Percent of equity by default. Keep target risk per trade low. One percent is a sensible starting point. For this example we used 3% of the total capital
 Commisions 
We used a 0.05% comission and 5 tick slippage
 Legal 
Education and research only. Not investment advice. Test in simulation first. Use realistic costs.
Cora Combined Suite v1 [JopAlgo]Cora Combined Suite v1   (CCSV1)
This is an 2 in 1 indicator (Overlay & Oscillator) the Cora Combined Suite v1  .
CCSV1 combines a price-pane Overlay for structure/trend with a compact Oscillator for timing/pressure. It’s designed to be clear, beginner-friendly, and largely automatic: you pick a profile (Scalp / Intraday / Swing), choose whether to run as Overlay or Oscillator, and CCSV1 tunes itself in the background.
What’s inside — at a glance
1) Overlay (price pane)
CoRa Wave: a smooth trend line based on a compound-ratio WMA (CRWMA).
Green when the slope rises (bull bias), Red when it falls (bear bias).
Asymmetric ATR Cloud around the CoRa Wave
Width expands more up when buyer pressure dominates and more down when seller pressure dominates.
Fill is intentionally light, so candlesticks remain readable.
Chop Guard (Range-Lock Gate)
When the cloud stays very narrow versus ATR (classic “dead water”), pullback alerts are muted to avoid noise.
Visuals don’t change—only the alerting logic goes quiet.
Typical Overlay reads
Trend: Follow the CoRa color; green favors long setups, red favors shorts.
Value: Pullbacks into/through the cloud in trend direction are higher-quality than chasing breaks far outside it.
Dominance: A visibly asymmetric cloud hints which side is funding the move (buyers vs sellers).
2) Oscillator (subpane or inline preview)
Stretch-Z (columns): how far price is from the CoRa mean (mean-reversion context), clipped to ±clip.
Near 0 = equilibrium; > +2 / < −2 = stretched/extended.
Slope-Z (line): z-score of CoRa’s slope (momentum of the trend line).
Crossing 0 upward = potential bullish impulse; downward = potential bearish impulse.
VPO (stepline): a normalized Volume-Pressure read (positive = buyers funding, negative = sellers).
Rendered as a clean stepline to emphasize state changes.
Event Bands ±2 (subpane): thin reference lines to spot extension/exhaustion zones fast.
Floor/Ceiling lines (optional): quiet boundaries so the panel doesn’t feel “bottomless.”
Inline vs Subpane
Inline (overlay): the oscillator auto-anchors and scales beneath price, so it never crushes the price scale.
Subpane (raw): move to a new pane for the classic ±clip view (with ±2 bands). Recommended for systematic use.
Why traders like it
Two in one: Structure on the chart, timing in the panel—built to complement each other.
Retail-first automation: Choose Scalp / Intraday / Swing and let CCSV1 auto-tune lengths, clips, and pressure windows.
Robust statistics: On fast, spiky markets/timeframes, it prefers outlier-resistant math automatically for steadier signals.
Optional HTF gate: You can require higher-timeframe agreement for oscillator alerts without changing visuals.
Quick start (simple playbook)
Run As
Overlay for structure: assess trend direction, where value is (the cloud), and whether chop guard is active.
Oscillator for timing: move to a subpane to see Stretch-Z, Slope-Z, VPO, and ±2 bands clearly.
Profile
Scalp (1–5m), Intraday (15–60m), or Swing (4H–1D). CCSV1 adjusts length/clip/pressure windows accordingly.
Overlay entries
Trade with CoRa color.
Prefer pullbacks into/through the cloud (trend direction).
If chop guard is active, wait; let the market “breathe” before engaging.
Oscillator timing
Look for Funded Flips: Slope-Z crossing 0 in the direction of VPO (i.e., momentum + funded pressure).
Use ±2 bands to manage risk: stretched conditions can stall or revert—better to scale or wait for a clean reset.
Optional HTF gate
Enable to green-light only those oscillator alerts that align with your chosen higher timeframe.
What each signal means (plain language)
CoRa turns green/red (Overlay): trend bias shift on your chart.
Cloud width tilts asymmetrically: one side (buyers/sellers) is dominating; extensions on that side are more likely.
Stretch-Z near 0: fair value around CoRa; pullback timing zone.
Stretch-Z > +2 / < −2: extended; watch for slowing momentum or scale decisions.
Slope-Z cross up/down: new impulse starting; combine with VPO sign to avoid unfunded crosses.
VPO positive/negative: net buying/selling pressure funding the move.
Alerts included
Overlay
Pullback Long OK
Pullback Short OK
Oscillator
Funded Flip Up / Funded Flip Down (Slope-Z crosses 0 with VPO agreement)
Pullback Long Ready / Pullback Short Ready (near equilibrium with aligned momentum and pressure)
Exhaustion Risk (Long/Short) (Stretch-Z beyond ±2 with weakening momentum or pressure)
Tip: Keep chart alerts concise and use strategy rules (TP/SL/filters) in your trade plan.
Best practices
One glance workflow
Read Overlay for direction + value.
Use Oscillator for trigger + confirmation.
Pairing
Combine with S/R or your preferred execution framework (e.g., your JopAlgo setups).
The suite is neutral: it won’t force trades; it highlights context and quality.
Markets
Works on crypto, indices, FX, and commodities.
Where real volume is available, VPO is strongest; on synthetic volume, treat VPO as a soft filter.
Timeframes
Use the Profile preset closest to your style; feel free to fine-tune later.
For multi-TF trading, enable the HTF gate on the oscillator alerts only.
Inputs you’ll actually use (the rest can stay on Auto)
Run As: Overlay or Oscillator.
Profile: Scalp / Intraday / Swing.
Oscillator Render: “Subpane (raw)” for a classic panel; “Inline (overlay)” only for a quick preview.
HTF gate (optional): require higher-timeframe Slope-Z agreement for oscillator alerts.
Everything else ships with sensible defaults and auto-logic.
Limitations & tips
Not a strategy: CCSV1 is a decision support tool; you still need your entry/exit rules and risk management.
Non-repainting design: Signals finalize on bar close; intrabar graphics can adjust during the bar (Pine standard).
Very flat sessions: If price and volume are extremely quiet, expect fewer alerts; that restraint is intentional.
Who is this for?
Beginners who want one clean overlay for structure and one simple oscillator for timing—without wrestling settings.
Intermediates seeking a coherent trend/pressure framework with HTF confirmation.
Advanced users who appreciate robust stats and clean engineering behind the visuals.
Disclaimer: Educational purposes only. Not financial advice. Trading involves risk. Use at your own discretion.
Holt Damped Forecast [CHE]A Friendly Note on These Pine Script Scripts 
Hey there! Just wanted to share a quick, heartfelt heads-up: All these Pine Script examples come straight from my own self-study adventures as a total autodidact—think late nights tinkering and learning on my own. They're purely for educational vibes, helping me (and hopefully you!) get the hang of Pine Script basics, cool indicators, and building simple strategies.
That said, please know this isn't any kind of financial advice, investment nudge, or pro-level trading blueprint. I'd love for you to dive in with your own research, run those backtests like a champ, and maybe bounce ideas off a qualified expert before trying anything in a real trading setup. No guarantees here on performance or spot-on accuracy—trading's got its risks, and those are totally on each of us.
Let's keep it fun and educational—happy coding! 😊
  Holt Damped Forecast    — Damped trend forecasts with fan bands for uncertainty visualization and momentum integration
  Summary 
This indicator applies damped exponential smoothing to generate forward price forecasts, displaying them as probabilistic fan bands to highlight potential ranges rather than point estimates. It incorporates residual-based uncertainty to make projections more reliable in varying market conditions, reducing overconfidence in strong trends. Momentum from the trend component is shown in an optional label alongside signals, aiding quick assessment of direction and strength without relying on lagging oscillators.
  Motivation: Why this design? 
Standard exponential smoothing often extrapolates trends indefinitely, leading to unrealistic forecasts during mean reversion or weakening momentum. This design uses damping to gradually flatten long-term projections, better suiting real markets where trends fade. It addresses the need for visual uncertainty in forecasts, helping traders avoid entries based on overly optimistic point predictions.
  What’s different vs. standard approaches? 
- Reference baseline: Diverges from basic Holt's linear exponential smoothing, which assumes persistent trends without decay.
- Architecture differences:
  - Adds damping to the trend extrapolation for finite-horizon realism.
  - Builds fan bands from historical residuals for probabilistic ranges at multiple confidence levels.
  - Integrates a dynamic label combining forecast details, scaled momentum, and directional signals.
  - Applies tail background coloring to recent bars based on forecast direction for immediate visual cues.
- Practical effect: Charts show converging forecast bands over time, emphasizing shorter horizons where accuracy is higher. This visibly tempers aggressive projections in trends, making it easier to spot when uncertainty widens, which signals potential reversals or consolidation.
  How it works (technical) 
The indicator maintains two persistent components: a level tracking the current price baseline and a trend capturing directional slope. On each bar, the level updates by blending the current source price with a one-step-ahead expectation from the prior level and damped trend. The trend then adjusts by weighting the change in level against the prior damped trend. Forecasts extend this forward over a user-defined number of steps, with damping ensuring the trend influence diminishes over distance.
Uncertainty derives from the standard deviation of historical residuals—the differences between actual prices and one-step expectations—scaled by the damping structure for the forecast horizon. Bands form around the median forecast at specified confidence intervals using these scaled errors. Initialization seeds the level to the first bar's price and trend to zero, with persistence handling subsequent updates. A security call fetches the last bar index for tail logic, using lookahead to align with realtime but introducing minor repaint on unconfirmed bars.
  Parameter Guide 
The Source parameter selects the price input for level and residual calculations, defaulting to close; consider using high or low for assets sensitive to volatility, as close works well for most trend-following setups. Forecast Steps (h) defines the number of bars ahead for projections, defaulting to 4—shorter values like 1 to 5 suit intraday trading, while longer ones may widen bands excessively in choppy conditions. The Color Scheme (2025 Trends) option sets the base, up, and down colors for bands, labels, and backgrounds, starting with Ruby Dawn; opt for serene schemes on clean charts or vibrant ones to stand out in dark themes.
Level Smoothing α controls the responsiveness of the price baseline, defaulting to 0.3—values above 0.5 enhance tracking in fast markets but may amplify noise, whereas lower settings filter disturbances better. Trend Smoothing β adjusts sensitivity to slope changes, at 0.1 by default; increasing to 0.2 helps detect emerging shifts quicker, but keeping it low prevents whipsaws in sideways action. Damping φ (0..1) governs trend persistence, defaulting to 0.8—near 0.9 preserves carryover in sustained moves, while closer to 0.5 curbs overextensions more aggressively.
Show Fan Bands (50/75/95) toggles the probabilistic range display, enabled by default; disable it in oscillator panes to reduce clutter, but it's key for overlay forecasts. Residual Window (Bars) sets the length for deviation estimates, at 400 bars initially—100 to 200 works for short timeframes, and 500 or more adds stability over extended histories. Line Width determines the thickness of band and median lines, defaulting to 2; go thicker at 3 to 5 for emphasis on higher timeframes or thinner for layered indicators.
Show Median/Forecast Line reveals the central projection, on by default—hide if bands provide enough detail, or keep for pinpoint entry references. Show Integrated Label activates the combined view of forecast, momentum, and signal, defaulting to true; it's right-aligned for convenience, so turn it off on smaller screens to save space. Show Tail Background colors the last few bars by forecast direction, enabled initially; pair low transparency for subtle hints or higher for bolder emphasis.
Tail Length (Bars) specifies bars to color backward from the current one, at 3 by default—1 to 2 fits scalping, while 5 or more underscores building momentum. Tail Transparency (%) fades the background intensity, starting at 80; 50 to 70 delivers strong signals, and 90 or above allows seamless blending. Include Momentum in Label adds the scaled trend value, defaulting to true—ATR% scaling here offers relative strength context across assets.
Include Long/Short/Neutral Signal in Label displays direction from the trend sign, on by default; neutral helps in ranging markets, though it can be overlooked during strong trends. Scaling normalizes momentum output (raw, ATR-relative, or level-relative), set to ATR% initially—ATR% ensures cross-asset comparability, while %Level provides percentage perspectives. ATR Length defines the period for true range averaging in scaling, at 14; align it with your chart timeframe or shorten for quicker volatility responses.
Decimals sets precision in the momentum label, defaulting to 2—0 to 1 yields clean integers, and 3 or more suits detailed forex views. Show Zero-Cross Markers places arrows at direction changes, enabled by default; keep size small to minimize clutter, with text labels for fast scanning.
  Reading & Interpretation 
Fan bands expand outward from the current bar, with the median line as the central forecast—narrower bands indicate lower uncertainty, wider suggest caution. Colors tint up (positive forecast vs. prior level) in the scheme's up hue and down otherwise. The optional label lists the horizon, median, and range brackets at 50%, 75%, and 95% levels, followed by momentum (scaled per mode) and signal (Long if positive trend, Short if negative, Neutral if zero). Zero-cross arrows mark trend flips: upward triangle below bar for bullish cross, downward above for bearish. Tail background reinforces the forecast direction on recent bars.
  Practical Workflows & Combinations 
- Trend following: Enter long on upward zero-cross if median forecast rises above price and bands contain it; confirm with higher highs/lows. Short on downward cross with falling median.
- Exits/Stops: Trail stops below 50% lower band in longs; exit if momentum drifts negative or signal turns neutral. Use wider bands (75/95%) for conservative holds in volatile regimes.
- Multi-asset/Multi-TF: Defaults work across stocks, forex, crypto on 5m-1D; scale steps by TF (e.g., 10+ on daily). Layer with volume or structure tools—avoid over-reliance on isolated crosses.
  Behavior, Constraints & Performance 
Closed-bar logic ensures stable historical plots, but realtime updates via security lookahead may shift forecasts until bar confirmation, introducing minor repaint on the last bar. No explicit HTF calls beyond bar index fetch, minimizing gaps but watch for low-liquidity assets. Resources include a 2000-bar lookback for residuals and up to 500 labels, with no loops—efficient for most charts. Known limits: Early bars show wide bands due to sparse residuals; assumes stationary errors, so gaps or regime shifts widen inaccuracies.
  Sensible Defaults & Quick Tuning 
Start with defaults for balanced smoothing on 15m-4H charts. For choppy conditions (too many crosses), lower β to 0.05 and raise residual window to 600 for stability. In trending markets (sluggish signals), increase α/β to 0.4/0.2 and shorten steps to 2. If bands overexpand, boost φ toward 0.95 to preserve trend carry. Tune colors for theme fit without altering logic.
  What this indicator is—and isn’t 
This is a visualization and signal layer for damped forecasts and momentum, complementing price action analysis. It isn’t a standalone system—pair with risk rules and broader context. Not predictive beyond the horizon; use for confirmation, not blind entries.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino 
Reactive Curvature Smoother Moving Average IndicatorSummary in one paragraph
 RCS MA is a reactive curvature smoother for any liquid instrument on intraday through swing timeframes. It helps you act only when context strengthens by adapting its window length with a normalized path energy score and by smoothing with robust residual weights over a quadratic fit, then optionally blending a capped one step forecast. Add it to a clean chart and watch the single colored line. Shapes can shift while a bar forms and settle on close. For conservative use, judge on bar close.
 Scope and intent
 • Markets: major FX pairs, index futures, large cap equities, liquid crypto
• Timeframes: one minute to daily
• Purpose: reduce lag in trends while resisting chop and outliers
• Limits: indicator only, no orders
 
Originality and usefulness 
• Novelty: adaptive window selection by minimizing normalized path energy with directionality bias, plus Huber weighted residuals and curvature aware penalty, finished with a mintick capped forecast blend
• Failure modes addressed: whipsaws from fixed length MAs and outlier spikes that pull means
• Testable: Inputs expose all components and optional diagnostics show chosen length, directionality, and energy
• Portable yardstick: forecast cap uses mintick to stay symbol aware
 Method overview in plain language 
Base measures
• Range span of the tested window and a path energy defined as the sum of squared price increments, normalized by span
Components
Adaptive window chooser: scans L between Min and Max using an energy over trend score and picks the lowest score
Robust smoother: fits a quadratic to the last L bars, computes residuals, applies Huber weights and an exponential residual penalty scaled down when curvature is high
Forecast blend: projects one step ahead from the quadratic, caps displacement by a multiple of mintick, blends by user weight
Fusion rule
• Final line equals robust mean plus optional capped forecast blend
Signal rule
• Visual bias only: color turns lime when close is above the line, red otherwise
What you will see on the chart
• One colored line that tightens in trends and relaxes in chop
• Optional debug overlays for core value, chosen L, directionality, and energy
• Optional last bar label with L, directionality, and energy
• Reminder: drawings can move intrabar and settle on close
Inputs with guidance
Setup
• Source: price series to smooth
Logic
• Min window l_min. Typical 5 to 21. Higher increases stability, adds lag
• Max window l_max. Typical 40 to 128. Higher reduces noise, adds lag ceiling
• Length step grid_step. Typical 1 to 8. Smaller is finer and heavier
• Trend bias trend_bias. Typical 0.50 to 0.80. Higher favors trend persistence
• Residual penalty lambda_base. Typical 0.8 to 2.0. Higher downweights large residuals more
• Huber threshold huber_k. Typical 1.5 to 3.0. Higher admits more outliers
• Curvature guard curv_guard. Typical 0.3 to 1.0. Higher reduces influence when curve is tight
• Forecast blend lead_blend. 0 disables. Typical 0.10 to 0.40
• Forecast cap lead_limit. Typical 1 to 5 minticks
• Show chosen L and metrics show_debug. Diagnostics toggle
 Optional: enable diagnostics to see length, direction, and energy
 
 Realism and responsible publication 
• No performance claims. Past results never guarantee future outcomes
• Shapes can move while bars are open and settle on close
• Use on standard candles for analysis and combine with your own risk process
 Honest limitations and failure modes 
• Very quiet regimes can reduce energy contrast, length selection may hover near the bounds
• Gap heavy symbols can disrupt quadratic fit on the window edges
• Excessive forecast blend may look anticipatory; use low values and the cap
Relative Strength Index Remastered [CHE]Relative Strength Index Remastered   — Enhanced RSI with robust divergence detection using price-based pivots and line-of-sight validation to reduce false signals compared to the standard RSI indicator.
  Summary 
RSI Remastered builds on the classic Relative Strength Index by adding a more reliable divergence detection system that relies on price pivots rather than RSI pivots alone, incorporating a line-of-sight check to ensure the RSI path between points remains clear. This approach filters out many false divergences that occur in the original RSI indicator due to its volatile pivot detection on the RSI line itself. Users benefit from clearer reversal and continuation signals, especially in noisy markets, with optional hidden divergence support for trend confirmation. The core RSI calculation and smoothing options remain familiar, but the divergence logic provides materially fewer alerts while maintaining sensitivity.
  Motivation: Why this design? 
The standard RSI indicator often generates misleading divergence signals because it detects pivots directly on the RSI values, which can fluctuate erratically in volatile conditions, leading to frequent false positives that confuse traders during ranging or choppy price action. RSI Remastered addresses this by shifting pivot detection to the underlying price highs and lows, which are more stable, and adding a validation step that confirms the RSI line does not cross the direct path between pivot points. This design targets the real problem of over-signaling in the original, promoting more actionable insights without altering the RSI's core momentum measurement.
  What’s different vs. standard approaches? 
- Reference baseline: The classical TradingView RSI indicator, which uses simple RSI-based pivot detection for divergences.
- Architecture differences:
  - Pivot identification on price extremes (highs and lows) instead of RSI values, extracting RSI levels at those points for comparison.
  - Addition of a line-of-sight validation that checks the RSI path bar by bar between pivots to prevent signals where the line is interrupted.
  - Inclusion of hidden divergence types alongside regular ones, using the same robust framework.
  - Configurable drawing of connecting lines between validated pivot RSI points for visual clarity.
- Practical effect: Charts show fewer but higher-quality divergence markers and lines, reducing clutter from the original's frequent RSI pivot triggers; this matters for avoiding whipsaws in intraday trading, where the standard version might flag dozens of invalid setups per session.
  Key Comparison Aspects 
 Aspect:  Title/Shorttitle  
Original RSI: "Relative Strength Index" / "RSI"  
Robust Variant: "Relative Strength Index Remastered  " / "RSI RM"
 Aspect:  Max. Lines/Labels  
Original RSI: No specification (Standard: 50/50)  
Robust Variant: max_lines_count=200, max_labels_count=200 (for more lines/markers in divergences)
 Aspect:  RSI Calculation & Plots  
Original RSI: Identical: RSI with RMA, Plots (line, bands, gradient fills)  
Robust Variant: Identical: RSI with RMA, Plots (line, bands, gradient fills)
 Aspect:  Smoothing (MA)  
Original RSI: Identical: Inputs for MA types (SMA, EMA etc.), Bollinger Bands optional  
Robust Variant: Identical: Inputs for MA types (SMA, EMA etc.), Bollinger Bands optional
 Aspect:  Divergence Activation  
Original RSI: input.bool(false, "Calculate Divergence") (disabled by default)  
Robust Variant: input.bool(true, "Calculate Divergence") (enabled by default, with tooltip)
 Aspect:  Pivot Calculation  
Original RSI: Pivots on RSI (ta.pivotlow/high on RSI values)  
Robust Variant: Pivots on price (ta.pivotlow/high on low/high), RSI values then extracted
 Aspect:  Lookback Values  
Original RSI: Fixed: lookbackLeft=5, lookbackRight=5  
Robust Variant: Input: L=5 (Pivot Left), R=5 (Pivot Right), adjustable (min=1, max=50)
 Aspect:  Range Between Pivots  
Original RSI: Fixed: rangeUpper=60, rangeLower=5 (via _inRange function)  
Robust Variant: Input: rangeUpper=60 (Max Bars), rangeLower=5 (Min Bars), adjustable (min=1–6, max=100–300)
 Aspect:  Divergence Types  
Original RSI: Only Regular Bullish/Bearish: - Bull: Price LL + RSI HL - Bear: Price HH + RSI LH  
Robust Variant: Regular + Hidden (optional via showHidden=true): - Regular Bull: Price LL + RSI HL - Regular Bear: Price HH + RSI LH - Hidden Bull: Price HL + RSI LL - Hidden Bear: Price LH + RSI HH
 Aspect:  Validation  
Original RSI: No additional check (only pivot + range check)  
Robust Variant: Line-of-Sight Check: RSI line must not cross the connecting line between pivots (line_clear function with slope calculation and loop for each bar in between)
 Aspect:  Signals (Plots/Shapes)  
Original RSI: - Plot of pivot points (if divergence) - Shapes: "Bull"/"Bear" at RSI value, offset=-5  
Robust Variant: - No pivot plots, instead shapes at RSI , offset=-R (adjustable) - Shapes: "Bull"/"Bear" (Regular), "HBull"/"HBear" (Hidden) - Colors: Lime/Red (Regular), Teal/Orange (Hidden)
 Aspect:  Line Drawing  
Original RSI: No lines  
Robust Variant: Optional (showLines=true): Lines between RSI pivots (thick for regular, dashed/thin for hidden), extend=none
 Aspect:  Alerts  
Original RSI: Only Regular Bullish/Bearish (with pivot lookback reference)  
Robust Variant: Regular Bullish/Bearish + Hidden Bullish/Bearish (specific "at latest pivot low/high")
 Aspect:  Robustness  
Original RSI: Simple, prone to false signals (RSI pivots can be volatile)  
Robust Variant: Higher: Price pivots are more stable, line-of-sight filters "broken" divergences, hidden support for trend continuations
 Aspect:  Code Length/Structure  
Original RSI: ~100 lines, simple if-blocks for bull/bear  
Robust Variant: ~150 lines, extended helper functions (e.g., inRange, line_clear), var group for inputs
  How it works (technical) 
The indicator first computes the core RSI value based on recent price changes, separating upward and downward movements over the specified length and smoothing them to derive a momentum reading scaled between zero and one hundred. This value is then plotted in a separate pane with fixed upper and lower reference lines at seventy and thirty, along with optional gradient fills to highlight overbought and oversold zones.
For smoothing, a moving average type is applied to the RSI if enabled, with an option to add bands around it based on the variability of recent RSI values scaled by a multiplier. Divergence detection activates on confirmed price pivots: lows for bullish checks and highs for bearish. At each new pivot, the system retrieves the bar index and values (price and RSI) for the current and prior pivot, ensuring they fall within a configurable bar range to avoid unrelated points.
Comparisons then assess whether the price has made a lower low (or higher high) while the RSI at those points moves in the opposite direction—higher for bullish regular, lower for bearish regular. For hidden types, the directions reverse to capture trend strength. The line-of-sight check calculates the straight path between the two RSI points and verifies that the actual RSI values in between stay entirely above (for bullish) or below (for bearish) that path, breaking the signal if any bar violates it. Valid signals trigger shapes at the RSI level of the new pivot and optional lines connecting the points. Initialization uses built-in functions to track prior occurrences, with states persisting across bars for accurate historical comparisons. No higher timeframe data is used, so confirmation occurs after the right pivot bars close, minimizing live-bar repaints.
  Parameter Guide 
Length — Controls the period for measuring price momentum changes — Default: 14 — Trade-offs/Tips: Shorter values increase responsiveness but add noise and more false signals; longer smooths trends but delays entries in fast markets.  
Source — Selects the price input for RSI calculation — Default: Close — Trade-offs/Tips: Use high or low for volatility focus, but close works best for most assets; mismatches can skew overbought/oversold reads.  
Calculate Divergence — Enables the enhanced divergence logic — Default: True — Trade-offs/Tips: Disable for pure RSI view to save computation; essential for signal reliability over the standard method.  
Type (Smoothing) — Chooses the moving average applied to RSI — Default: SMA — Trade-offs/Tips: None for raw RSI; EMA for quicker adaptation, but SMA reduces whipsaws; Bollinger Bands option adds volatility context at cost of added lines.  
Length (Smoothing) — Period for the smoothing average — Default: 14 — Trade-offs/Tips: Match RSI length for consistency; shorter boosts signal speed but amplifies noise in the smoothed line.  
BB StdDev — Multiplier for band width around smoothed RSI — Default: 2.0 — Trade-offs/Tips: Lower narrows bands for tighter signals, risking more touches; higher widens for fewer but stronger breakouts.  
Pivot Left — Bars to the left for confirming price pivots — Default: 5 — Trade-offs/Tips: Increase for stricter pivots in noisy data, reducing signals; too high delays confirmation excessively.  
Pivot Right — Bars to the right for confirming price pivots — Default: 5 — Trade-offs/Tips: Balances with left for symmetry; longer right ensures maturity but shifts signals backward.  
Max Bars Between Pivots — Upper limit on distance for valid pivot pairs — Default: 60 — Trade-offs/Tips: Tighten for short-term trades to focus recent action; widen for swing setups but risks unrelated comparisons.  
Min Bars Between Pivots — Lower limit to avoid clustered pivots — Default: 5 — Trade-offs/Tips: Raise to filter micro-moves; too low invites overlapping signals like the original RSI.  
Detect Hidden — Includes trend-continuation hidden types — Default: True — Trade-offs/Tips: Enable for full trend analysis; disable simplifies to reversals only, akin to basic RSI.  
Draw Lines — Shows connecting lines between valid pivots — Default: True — Trade-offs/Tips: Turn off for cleaner charts; helps visually confirm line-of-sight in backtests.
  Reading & Interpretation 
The main RSI line oscillates between zero and one hundred, crossing above fifty suggesting building momentum and below indicating weakness; touches near seventy or thirty flag potential extremes. The optional smoothed line and bands provide a filtered view—price above the upper band on the RSI pane hints at overextension. Divergence shapes appear as upward labels for bullish (lime for regular, teal for hidden) and downward for bearish (red regular, orange hidden) at the pivot's RSI level, signaling a mismatch only after validation. Connecting lines, if drawn, slope between points without RSI interference, their color matching the shape type; a dashed style denotes hidden. Fewer shapes overall compared to the standard RSI mean higher conviction, but always confirm with price structure.
  Practical Workflows & Combinations 
- Trend following: Enter longs on regular bullish shapes near support with higher highs in price; filter hidden bullish for pullback buys in uptrends, pairing with a rising smoothed RSI above fifty.
- Exits/Stops: Use bearish regular as reversal warnings to tighten stops; hidden bearish in downtrends confirms continuation—exit if lines show RSI crossing the path.
- Multi-asset/Multi-TF: Defaults suit forex and stocks on one-hour charts; for crypto volatility, widen pivot ranges to ten; scale min/max bars proportionally on daily for swings, avoiding the original's intraday spam.
  Behavior, Constraints & Performance 
Signals confirm only after the right pivot bars close, so live bars may show tentative pivots that vanish on close, unlike the standard RSI's immediate RSI-pivot triggers—plan for this delay in automation. No higher timeframe calls, so no security-related repaints. Resources include up to two hundred lines and labels for dense charts, with a loop in validation scanning up to three hundred bars between pivots, which is efficient but could slow on very long histories. Known limits: Slight lag at pivot confirmation in trending markets; volatile RSI might rarely miss fine path violations; not ideal for gap-heavy assets where pivots skip.
  Sensible Defaults & Quick Tuning 
Start with defaults for balanced momentum and divergence on most timeframes. For too many signals (like the original), raise pivot left/right to eight and min bars to ten to filter noise. If sluggish in trends, shorten RSI length to nine and enable EMA smoothing for faster adaptation. In high-volatility assets, widen max bars to one hundred but disable hidden to focus essentials. For clean reversal hunts, set smoothing to none and lines on.
  What this indicator is—and isn’t 
RSI Remastered serves as a refined momentum and divergence visualization tool, enhancing the standard RSI for better signal quality in technical analysis setups. It is not a standalone trading system, nor does it predict price moves—pair it with volume, structure breaks, and risk rules for decisions. Use alongside position sizing and broader context, not in isolation.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino






















