RenkoNow you can plot a "Renko" chart on any timeframe for free! As with my previous algorithm, you can plot the "Linear Break" chart on any timeframe for free!
I again decided to help TradingView programmers and wrote code that converts a standard candles / bars to a "Renko" chart. The built-in renko() and security() functions for constructing a "Renko" chart are working wrong. Do not try to write strategies based on the built-in renko() function! The developers write in the manual: "Please note that you cannot plot Renko bricks from Pine script exactly as they look. You can only get a series of numbers similar to OHLC values for Renko bars and use them in your algorithms". However, it is possible to build a "Renko" chart exactly like the "Renko" chart built into TradingView. Personally, I had enough Pine Script functionality.
For a complete understanding of how such a chart is built, you can read to Steve Nison's book "BEYOND JAPANESE CANDLES" and see the instructions for creating a "Renko" chart:
Rule 1: one white brick (or series) is built when the price rises above the base price by a fixed threshold value or more.
Rule 2: one black brick (or series) is built when the price falls below the base price by a fixed threshold or more.
Rule 3: if the rise or fall of the price is less than the minimum fixed value, then new bricks are not drawn.
Rule 4: if today's closing price is higher than the maximum of the last brick (white or black) by a threshold or more, move to the column to the right and build one or more white bricks of equal height. A new brick begins with the maximum of the previous brick.
Rule 5: if today's closing price is below the minimum of the last brick (white or black) by a threshold or more, move to the column to the right and build one or more black bricks of equal height. A new brick begins with the minimum of the previous brick.
Rule 6: if the price is below the maximum or above the minimum, then new bricks are not drawn on the chart.
So my algorithm can to plot Traditional Renko with a fixed box size. I want to note that such a "Renko" chart is slightly different from the "Renko" chart built into TradingView, because as a base price I use (by default) close of first candle. How the developers of TradingView calculate the base price I don’t know. Personally, I do as written in the book of Steve Neeson.
The algorithm is very complicated and I do not want to explain it in detail. I will explain very briefly. The first part of the get_renko () function — // creating lists — creates two lists that record how many green bricks should be and how many red bricks. The second part of the get_renko () function — // creating open and close series — creates open and close series to plot bricks. So, this is a white box - study it!
As you understand, one green candle can create a condition under which it will be necessary to plot, for example, 10 green bricks. So the smaller the box size you make, the smaller the portion of the chart you will see.
I stuffed all the logic into a wrapper in the form of the get_renko() function, which returns a tuple of OHLC values. And these series with the help of the plotcandle() annotation can be converted to the "Renko" chart. I also want to note that with a large number of candles on the chart, outrages about the buffer size uncertainty are heard from the TradingView blackbox. Because of it, in the annotation study() set the value of the max_bars_back parameter.
In general, use this script (for example, to write strategies)!
Cari dalam skrip untuk "one一季度财报"
Time Range StatisticsA good amount of users requested a text box showing various price statistics, the following script returns various of these stats in a user-selected range, and include classical ones such as a central tendency measurement (mean), dispersion (normalized range) and percent change, but also include less common statistics such as average traded volume and number of gaps. The script also calculates the correlation between the closing price and another user-selected instrument.
The script is currently the longest one I ever made and took some efforts, as I wasn't satisfied with the statistics to be originally included. Big thx to Gael for the enormous feedback and the idea of the normalized range, to user @Cookiecrush for the feedback ( without ya I would have posted something bad you know umu ? ), and Lulidolce for the support, friendship is magic!
 Selected Range 
The setting  Start  determine the bar at which the range starts, while  End  determine at which bar the range end. To help you select these values, the current bar number (bar index) is displayed at the right of the indicator title in blue.
The setting  evaluate to last bar  will use a range starting at  Start  and ending at the last bar, as such you can use a full range by using  Start = 0  and select  evaluate to last bar 
  
The range is highlighted by an area on the chart. By default Start = 9000 and End = 10000, you might not have this amount of data in your chart, as such use the displayed bar index to select Start and End, then set the settings as default.
 Displayed Statistics 
The statistics panel is displayed on the right side of the last bar, the panel has 3 sections, a title section who shows the symbol ticker, timeframe, and overall trends represented by a chart emoji, the overall trends are determined by comparing the number of higher highs with the number of lower low.
Below are displayed the date ranges with time format: year/month/day/hour:minute.
The second section shows the general statistics. The first one is the mean, also represented by the orange line in the chart, the blue line displayed represent the highest price value in the range, while the red one represents the lowest price value. 
The second stat is the normalized range, and determine how spread is the price in the user-selected range, why not the standard deviation? Because the standard deviation might return results varying widely depending on the scale of the closing price, you could get measures such as 0.0156 or 16 or even 56 depending on the instrument, as such using a normalized range can be more appropriate as it lays in a range of (0,1). Lower values indicate a low degree of price variation. Note that I still want to find another measure in the future.
The percentage change (or relative change) indicates at which percentage the price has increased or decreased, and is calculated by subtracting the closing at bar  Start  with the price at bar  End , divided by the price at bar  End , the result is then multiplied by 100. 
The average traded volume calculate the mean of the volume in the selected range, I used the same format used by the original volume indicator for clarity.
Finally, the last stats of the section is the number of gaps, this stat is by default hidden. An up gap is detected when the open price is superior to the previous high, while a down gap is detected when the open price is inferior to the previous low, this allow to only retain significant gaps.
The last section of the indicator panel shows the correlation between the closing price and another instrument, by default GOOG, this correlation is also calculated within the user-selected range. Positive values indicate a positive relationship, that is the two instruments tend to move in the same direction. Negative values indicate a negative relationship, both instruments tend to move in a direction opposite to each other. Values closer to 1 or -1 indicate a stronger relationship, while values closer to 0 indicate no relationship.
 In Summary 
The script shows various stats, each calculated within a user-selected range, in general one would be more interested in how these stats might evolve with time, but checking them in a custom range can be quite interesting.
Thx for reading.  umu 
Histogram - Price Action - Dy CalculatorThis script aims to help users of Price Action robot, for Smarttbot (brazilian site that automates Brazilian market (B3)).
You can use on any symbol.
The script will follow price action principles. It will calculate the absolute value of last candle and compare with actual candle. Colors are:
- Red - If the actual candle absolute value is higher than previous one, and the price is lower than last candle. It would be a short entry.
- Blue - If the actual candle absolute value is higher than previous one, and the price is higher than last candle. It would be a long entry.
- Black - The actual candle absolute value is lower than previous one, so there is no entry.
If there is a candle that is higher than previous one, and both high and low values are outside boundaries of previous one, it will calculate which boundary is bigger and will apply the collor accordingly.
eha Moving Averages StrategyMoving Average  based strategies are very popular ones among both long-term investors and short-term traders as they can be tailored to any time frame. One of the main moving average strategies are crossovers. The very simple type is a price  crossover , which is when the  price crosses  above or below a moving average to signal a potential change in trend.
Another strategy is to apply  two moving averages  to a chart: one longer (or slow) and one shorter (or fast). When the shorter-term MA crosses above the longer-term MA, it's a buy signal, as it indicates that the trend is shifting up (also known as “ Golden Cross ”). Meanwhile, when the shorter-term MA crosses below the longer-term MA, it's a sell signal, as it indicates that the trend is shifting down (which is also known as “ Dead/Death Cross ”).
This is a study to find a suitable trading strategy for 4-6 hour time frames. As you can see the performance is currently very poor. It has just generated almost 90 trades in a very long period from January 2017 to the time of publishing the study for the first time.
Moving averages work quite well in strong trending conditions but poorly in choppy or ranging conditions. Adjusting the time frame can correct this problem temporarily, although, at some point, these issues are likely to occur regardless of the time frame chosen for the moving average(s).
I am working on this basic strategy to make its performance better and I will update the post in the future. So keep in touch by following the post.
 Why have I republished my study?
 
It sounds like  TradingView  stores and indexes scripts based on the title of the post rather than the actual title of the scripts and if one chose general terms as the title of the post, the  TradingView  script search engine may be unable to find it. So I decided to repost the strategy with a more searchable and unique prefix of " eha ".
Please provide me with your precious feedback.
Dual Purpose Pine Based CorrelationThis is my "Pine-based" correlation() function written in raw Pine Script. Other names applied to it are "Pearson Correlation", "Pearson's r", and one I can never remember being "Pearson Product-Moment Correlation Coefficient(PPMCC)". There is two basic ways to utilize this script. One is checking correlation with another asset such as the S&P 500 (provided as a default). The second is using it as a handy independent indicator correlated to time using Pine's bar_index variable. Also, this is in fact two separate correlation indicators with independent period adjustments, so I guess you could say this indicator has a dual purpose split personality. My intention was to take standard old correlation and apply a novel approach to it, and see what happens. Either way you use it, I hope you may find it most helpful enough to add to your daily TV tool belt.
You will notice I used the Pine built-in correlation() in combination with my custom function, so it shows they are precisely equal, even when the first two correlation() parameters are reversed on purpose or by accident. Additionally, there's an interesting technique to provide a visually appealing line with two overlapping plot()s combined together. I'm sure many members may find that plotting tactic useful when a bird's nest of plotting is occurring on the overlay pane in some scenarios. One more thing about correlation is it's always confined to +/-1.0 irregardless of time intervals or the asset(s) it is applied to, making it a unique oscillator.
As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette". For those of you who are newcomers to Pine Script, this code release may also help you comprehend the "Power of Pine" by employing advanced programming techniques in Pine exhibiting code utilization in a most effective manner. One of the many tricks I applied here was providing floating point number safeties for _correlation(). While it cannot effectively use a floating point number, it won't error out in the event this should occur especially when applying "dominant cycle periods" to it, IF you might attempt this.
 NOTICE:  You may have observed there is a sqrt() custom function and you may be thinking... "Did he just sick and twistedly overwrite the Pine built-in sqrt() function?" The answer is... YES, I am and yes I did! One thing I noticed, is that it does provide slightly higher accuracy precision decimal places compared to the Pine built-in sqrt(). Be forewarned, "MY" sqrt() is technically speaking slower than snail snot compared to the native Pine sqrt(), so I wouldn't advise actually using it religiously in other scripts as a daily habit. It is seemingly doing quite well in combination with these simple calculations without being "sluggish". Lastly, of course you may always just delete the custom sqrt() function,   via Pine Editor, and then the script will still operate flawlessly, yet more efficiently.
 Features List Includes: 
Dark Background - Easily disabled in indicator Settings->Style for "Light" charts or with Pine commenting
AND much, much more... You have the source! 
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
Pivots MTF [LucF]Pivots detected at higher timeframes are more significant because more market activity—or work—is required to produce them. This indicator displays pivots calculated on the higher timeframe of your choice.
 Features 
► Timeframe selection
— The higher timeframe (HTF) can be selected in 3 different ways:
 • By steps (15 min., 60 min., 4H, 1D, 3D, 1W, 1M, 1Y). This setting is the default.
 • As a multiple of the current chart's resolution, which can be fractional, so 3.5 will work.
 • Fixed.
— The HTF used can be displayed near the last bar (default).
— Note that using the HTF is not mandatory. If it is disabled, the indicator will calculate on the chart's resolution.
— Non-repainting or repainting mode can be selected. This has no impact on the display of historical bars, but when no repainting is selected, pivot detection in the realtime bar will be delayed by one chart bar (not one bar at the HTF).
► Pivots
— Three color schemes are provided: green/red, aqua/pink and coral/violet (the default).
— Both the thickness and brightness of lines can be controlled separately for the hi and lo pivots.
— The visibility of the last hi/lo pivots can be enhanced.
— Prices can be displayed on pivot lines and the text's size and color can be adjusted.
— The number of bars required for the left/right pivot legs can be controlled (the default is 4).
— The source can be selected individually for hi and lo pivots (the default is  hlc3  and  low .
— The mean of the hi/lo pivot values of the last few thousand chart bars can be displayed. Pivots having lasted longer during the mean's period will weigh more in the calculation. The mean can be displayed in running mode and/or only showing its last level as a long horizontal line. I don't find it very useful; maybe others will.
► Markers and Alerts
— Markers can be configured on breaches of either the last hi/lo pivot levels, or the hi/lo mean. Crossovers and crossunders are controlled separately.
— Alerts can be configured using any of the marker combinations. As is usual for my indicators, only one alert is used. It will trigger on the markers that are active when you create your alert. Once your markers are set up the way you want, create your alert from the chart/timeframe you want the alert to run on, and be sure to use the “Once Per Bar Close” triggering condition. Use an alert message that will remind you of the combination of markers used when creating the alert. If you use multiple markers to trigger one alert, then having the indicator show those markers will be important to help you figure out which marker triggered the alert when it fired.
A quick look at the pattern of these markers will hopefully convince you that using them as entry/exit signals would be perilous, as they are prone to whipsaw. I have included them because some traders may use the markers as reminders.
 Using Pivots 
These pivots can be used in a few different ways:
— When using the  high / low  sources they will show extreme levels, breaches of which should be more significant.
— Another way to use them is with  hlc3  (the average of the  high ,  low  and  close ) for hi pivots and  low  for the lo pivots. This accounts for my personal mythology to the effect that drops typically reach previous lows more easily than rallies make newer highs.
— Using  low  for hi pivots and  high  for lo pivots (so backward) can be a useful way to set stops or to detect weakness in movements.
You will usually be better served by pivots if you consider them as denoting regions rather than precise levels. The flexibility in the display options of this indicator will help you adapt it to the way you use your pivots. To indicate areas rather than levels, for example, try using a brightness of 1 with a line thickness of 30. The cloud effect generated this way will show areas better than fine lines.
Realize that these pivot lines are positioned in the past, and so they are drawn after the fact because a given number of bars need to elapse before calculations determine a pivot has occurred. You will thus never see a pivot top, for example, identified on the realtime bar. To detect a pivot, it takes a number of bars corresponding to the dilation of the higher timeframe in the current one, multiplied by the number of bars you use for your pivots' right leg. Also note that the Pine native function used to detect pivots in this indicator considers a summit to be a top when the number of bars in each leg are lower or equal to that top. Bars in legs do not need to be progressively lower on each side of the pivot for a pivot to be detected. 
 If you program in Pine 
— See the  Pinecoders MTF Selection Framework  for an explanation of the functions used in this script to provide the selection mechanism for the higher timeframe.
— This code uses the  Pine Script Coding Conventions .
 Thanks 
— To the Pine coders asking questions in the  Pine Script chat on TV ; your questions got me to write this indicator.
Center Of Linearity - A More Efficient Alternative To Elhers CGIntroduction 
The center of gravity oscillator  (CG)  is one of the oscillators presented in Elhers book "cybernetic analysis for stocks and futures". This oscillator can be described as a bandpass filter centered around 0, its simplicity is ridiculous yet this indicator managed to get a pretty great popularity, this might be due to Elhers saying that he has substantial advantages over conventional oscillators used in technical analysis.
Today i propose a more efficient estimation of the center of gravity oscillator, this estimation will only use one convolution, while the original and other estimations use 2. I will also explain everything about the center of gravity oscillator, because even if its name can be imposing its actually super easy to understand.
 The Center Of Gravity Oscillator 
The CG oscillator is a bandpass filter, in short it filter high frequencies components as well as low frequency ones, this is why the oscillator is both smooth (no high frequencies) as well as detrended (no low frequencies), and therefore the oscillator focus exclusively on the cycles.
Its calculation is simple, its just a linearly weighted moving average minus a simple moving average  wma - sma , this is not what is showcased in its book, but the result is just the same, the only thing that change is the scale, this is why some estimates have a weird scale that is not centered around 0, the output is technically the same but the scale isn't, however the scale of an oscillator isn't a big deal as long as the oscillator is centered around 0 and we don't plan to use it as input for overlay indicators.
If you are familiar with moving averages you'll know that the wma is more reactive than the sma, this is because more recent values have higher weights, and since subtracting a low-pass filter with another one conserve the smoothness while removing low-frequency components, we end up with a bandpass filter, yay!
 Why "Center" Of Gravity ? 
Elhers explain the idea behind this title with a pretty blurry analogy, so i'll try to give a visual explanation, we said earlier that the center of gravity was simply : wma - sma, ok lets look at their respective impulse responses,
  
Those are basically the weights of each filters, also called filter coefficients, lets denote the coefficients of the wma as  a  and the coefficients of the moving average as  b . So whats the meaning behind center of gravity ? We basically want to "center" the weights of the wma, this can be done with  a  -  b 
  
The coefficients of the wma are therefore centered around 0, but actually there is more to that than a simple title explanation, basically  a - b = c , where  c  are the coefficients of the  center of gravity  bandpass filter, therefore if we where to apply convolution to the price with  c , we would get the center of gravity oscillator. Thats the thing with FIR filters, we can use convolution for describing a lot of FIR systems, and the difference between two impulse responses of two low-pass filters (here wma, sma) give us the coefficients of a bandpass filter.
 The Center Of Linearity 
At this point we could simply get the oscillator by using  length/2 - i  as coefficient, however in order to propose a more interesting variation i decided to go with a less efficient but more original approach, the center of linearity. Imagine two convolutions :
 a = i*src  and  b = i*src 
 a  only has a reversed index  length-i , and is therefore describe a simple wma. Both convolutions give the following impulse responses :
  
Both are symmetrical to each others, and cross at a point, denoted center of linearity. The difference of each responses is :
  
Using it as coefficients would give us a bandpass filter who would look exactly like the Cg oscillator, this would be calculated as follows in our convolution :
 i*src -i*src ) = i*(src -src ) 
Lets compare our estimate with the CG oscillator,
  
 Conclusion 
I this post i explained the calculation of the CG oscillator and proposed an efficient estimation of it by using an original approach. The CG oscillator isn't something complicated to use nor calculate, and is in fact closely related to the rolling covariance between the price and a linear function, so if you want to use the crosses between the center of gravity and 0 you can just use :  correlation(close,bar_index,length)  instead, thats basically the same.
The proposed indicator can also use other weightings instead of a linear one, each impulses responses would remain symmetrical.
Smart Envelope - Running Away From The TrendIntroduction 
Envelopes indicators consist in displaying one upper and one lower extremity on the price chart. They are most of the time built by adding/subtracting a volatility estimator  (rolling stdev, atr, range...etc)  to a central tendency estimator  (SMA, EMA, LSMA...etc) . Their interpretation is often subject to debate amongst technical analyst, some will use a support and resistance methodology, where price will start a downtrend once it cross the upper extremity, and a down trend once it cross the lower one. Others will prefer a breakout methodology, where price will reach higher highs once it cross the upper extremity, and lower lows when it cross the lower one. Because of price non stationarity its hard to select the best methodology, the support and resistance one will mostly work on ranging markets, while the breakout methodology mostly work on trending ones.
Therefore new methods where proposed, instead of using moving averages with a high lag, faster filters where used, such as the least squares moving average or zero lag exponential moving average, other band indicators where also created using adaptive filters, but improvements remain relatively low. The most difficult task would be to make extremities with the ability to return accurate support and resistances levels, and today i want to provide a new way to construct such extremities by using the recursive bands framework that allow extremely creative and efficient indicators.
 The Main Idea 
With classical bands indicators, the upper and lower extremity will still be correlated with the main trend, the problem behind such method is that we can't use a support and resistance methodology with trending markets, the fact that reversals exist tells us that our extremities will always be crossed by the main trend, here is an example :
  
Here the support is correlated with the main trend, in order for it to be accurate we must assume the trend will go on for ever, and will only detect higher lows, this is what we expect with the orange line, but we can see that a severe down trend totally destroy our plan.
In short we need to give some  headroom  to our extremities, and thus one extremity can't be correlated with the main trend.
 The proposed Indicator 
  
We want to minimize the correlation between the extremities, so if the upper extremity rise, the lower one must fall. This allow to give some headroom and allow the user to anticipate larger movements, this is how bands seeking to give support and resistances points should work.
The indicator has a length setting that control the wideness of the extremities, unlike other indicators low values such as 14 can still create really wide bands, take that into account.
  
length = 5. Lower length values allow for more motion from the extremities, but does not necessarily involve detecting shorter terms support and resistances levels. The factor setting is not that important, but it allow to return extremities with more motion when high, and really wide bands when below 1 and greater than 0.
 Central Tendency Estimator 
Something fun with the recursive band framework is that the bands are no longer based on the central tendency estimator but its the central tendency estimator who is based on the bands. The central tendency estimator can also provide support and resistances points with the price, like classical moving averages, altho its lack of motion is this time a downside.
  
 Conclusion 
Altho the extremities are more accurate than other band indicators, the problem remain the same, larger trend will always break the extremities and continue creating higher/lower highs/lows, at this point our stop loss would certainly be triggered. This is a huge downsides of contrarian strategy, we sure might anticipate reversals earlier, but we are exposed to larger price movements, therefore the risk is extreme. 
But the proposed methodology might still prove useful to develop more robust support and resistances levels based on envelopes indicators. 
Thanks for reading !
Visual RSI [LucF]Visual RSI offers a different way of looking at RSI by providing a composite representation of 9 different RSI-generated components. Instead of focusing on one line only, this approach blends multiple sources to provide the viewer with a larger context RSI-based picture.
 For those who don’t want to read 
• Green in bullish (>50) zone is the most bullish.
• Red in bullish zone doesn’t necessarily mean bearish—it just means bullish strength is weakening. It may be just a pause before a reprise or exhaustion signalling a reversal—impossible to tell.
• The same in inverse applies to the bearish zone (<50).
 For those who want to understand 
The nine components making up Visual RSI are:
• a current timeframe RSI
• a higher timeframe RSI
• the delta between these two RSI lines
• for each of these three basic components, two independent Bollinger band: one calculated for the bullish section of the scale (>50) and a separate one calculated for the lower bearish region.
 Dual BBs 
In my view, RSI’s position with regards to the centerline is much more important than its position in extreme areas. Why? Because the building block of RSI is the  ratio  of the averages of up/down moves during the RSI period. When the average of ups is greater, RSI is > 50. So while a rising signal starting from 20 let’s say, indicates that the rate of change is increasing, only when it crosses 50 can we say that sentiment balance has truly become bullish, and this information is more reliable than the signal being at a level corresponding to whatever estimate we make of what constitutes an extreme value. In my landscape, the general balance of a ratio provides more valuable information than the ratio’s exact value.
The idea behind the dual BBs is to provide independent tracking information for both halves of the indicator’s space, which I find more useful than the normal method of simply adding a multiple of the standard deviation on both sides of the mean. With dual BBs, the upper BB will never go lower than the indicator’s centerline, and the lower BB will never go higher. The upper BB focuses on upper-bound volatility when the signal is bearish, and the lower BB focuses on downside volatility when the signal is bearish.
The functions used to calculate the independent BBs are reusable on other signals if a centerline can be defined for them. A clamping percentage is implemented, so that when a BB line is hugging the centerline it clamps to it. This helps in providing earlier signals when they use the BB line states.
 Providing context to RSI 
What RSI measures indirectly is the balance in the rate of change—or the speed of price movement, but not its instant value, otherwise RSI would be even noisier. More precisely, RSI represents the relative strength of the up/down movement in the last n bars of RSI’s length, with 14 often used because that’s what Wilder proposed (Visual RSI’s defaults are 20 for the current timeframe and 40 for the higher timeframe). At every bar, a new value is added to the equation and an old value carrying equal weight is dropped, so a large dropped off value will have more impact on RSI’s value if the new bar’s move is small. This accounts for some of RSI’s speed in identifying exhaustion after important moves, but almost for some of its noise.
 
Visual RSI is the result of trying to drown RSI’s noise in the context of other informational streams, while simultaneously providing even faster information than RSI alone, by giving more visual weight to the delta between the current and higher timeframe RSI’s.
 How to read Visual RSI 
The default settings show all 9 basic components as green/red areas of intensities varying with their importance. The most intense colors are reserved for the delta RSI and the BBs have the lightest intensities. The individual lines of components are intentionally difficult to distinguish so that focus is first on the general picture, including the all-important six-state background, and then on the delta RSI.
One entry setup could be reversals in a larger trend context, so low pivots of the delta in a fully bullish context (a green background in the upper section of the indicator), and inversely, high pivots in a fully bearish context (a red background in the lower section of the indicator).
Please resist the common misconception, when interpreting RSI, that a reversal in the signal will necessarily lead to a reversal in price. Each trend has its rhythm. Only machine-generated price action can progress regularly. It’s normal for trends to take a breather for some time before they continue or reverse, as traders driving the trend experience emotional fatigue and gradual fear. RSI reversals merely signify that such a breather has occurred—nothing more. Only the larger context can provide information that can situate that pause and put more meaningful odds on it having more probability of continuing in one direction or the other. This is the reasoning behind the setup just described.
 Features 
• All components can be hidden, displayed as a simple line, a uniformly colored fill, or a green/red fill (the default).
• The background can be colored using 9 different methods, including 3 six-state methods using the rising/falling BB lines of the 3 basic components. These six states allow for bullish/bearish/neutral sentiment in both the upper and lower regions of the indicator. A bearish (dark red) background in the bullish (>50) section of the indicator represents decreasing bullishness. A bearish (slightly brighter red) in the bearish (<50) section of the indicator means incresingly bearish sentiment. The six-state backgrounds allow for neutral (no color) sentiment when no compelling signs can be found to conclude anything with meaningful odds. The default background uses the six-state method on the higher timeframe RSI’s BBs because I find it the most useful, as it represents the largest—and slowest—context sentiment among all the indicator’s components.
• A thin status bar in the top part of the indicator also allows selection of the same 9 methods to color it. The default is a triple-state system using the rising/falling characteristics of the current timeframe RSI’s BBs to provide a short-term counterbalance to the long-term background.
• Three different markers can be configured using approximately 70 permutations each, each filtered by 20 different filter permutations. When modification of the relevant parameters in the script’s  Settings/Settings/Parameters  section is added, possibilities are almost endless. If the generated signals are then fed into the PineCoders Engine and combined with the Engine’s own options, the permutations go up another order of magnitude, and changes to any setting can be instantly evaluated using the Engine’s backtesting results.
• Five simple filters can be combined. They are additive. They include volume-related conditions and a chandelier, which I find useful because both volume and volatility (the chandelier using highs/lows and ATR) are sensible complementary sources to RSI’s momentum information. The filter’s state can be shown as a thin line at the bottom of the indicator.
• Alerts can be configured using any of the marker/filter combinations mentioned. As usual, once your markers/filters are set up the way you want, create your alert from the chart/timeframe you want the alert to run on and be sure to use the “Once Per Bar Close” triggering condition. Use an alert message that will remind you of which combination of markers were used when creating the alert.
• A plot providing entry signals for the PineCoders Backtesting & Trading Engine is supplied. It will use whichever marker/filter configuration is active to generate signals.
• All higher timeframe information is non-repainting. Higher timeframe lines can be smoothed (the default). The selection of the higher timeframe can be made using 3 different methods:
1. By steps (if current timeframe <= 1 minute: 60 min, <= 60 min: 1D, <= 6H: 3D, <= 1D: 1W, <=1W: 1M, >1W: 12M)
2. By a user-defined multiple of the current timeframe
3. Using a fixed timeframe
 Thanks to: 
• Alex Orekhov aka @everget for the chandelier code.
• @RicardoSantos who through a small remark early on, unknowingly put me on the track of eliminating noise through visual crowding.
• The brilliant guys in the PineCoders Pro room for your knowledge, limitless creativity and constant companionship.
Forecasting - Drift MethodIntroduction 
Nothing fancy in terms of code, take this post as an educational post where i provide information rather than an useful tool. 
 Time-Series Forecasting And The Drift Method 
In time-series analysis one can use many many forecasting methods, some share similarities but they can all by classified in groups and sub-groups, the drift method is a forecasting method that unlike averages/naive methods does not have a constant (flat) forecast, instead the drift method can increase or decrease over time, this is why its a great method when it comes to forecasting linear trends.  
Basically a drift forecast is like a linear extrapolation, first you take the first and last point of your data and draw a line between those points, extend this line into the future and you have a forecast, thats pretty much it.
One of the advantage of this method is first its simplicity, everyone could do it by hand without any mathematical calculations, then its ability to be non-conservative, conservative methods involve methods that fit the data very well such as linear/non-linear regression that best fit a curve to the data using the method of least-squares, those methods take into consideration all the data points, however the drift method only care about the first and last point.
 Understanding Bias And Variance 
In order to follow with the ability of methods to be non-conservative i want to introduce the concept of bias and variance, which are essentials in time-series analysis and machine learning. 
First lets talk about training a model, when forecasting a time-series we can divide our data set in two, the first part being the training set and the second one the testing set. In the training set we fit a model to the training data, for example :
  
We use 200 data points, we split this set in two sets, the first one is for training which is in blue, and the other one for testing which is in green. 
Basically the  Bias  is related to how well a forecasting model fit the training set, while the  variance  is related to how well the model fit the testing set. In our case we can see that the drift line does not fit the training set very well, it is then said to have high bias. If we check the testing set :
  
We can see that it does not fit the testing set very well, so the model is said to have high variance. It can be better to talk of bias and variance when using regression, but i think you get it. This is an important concept in machine learning, you'll often see the term "overfitting" which relate to a model fitting the training set really well, those models have a low to no bias, however when it comes to testing they don't fit well at all, they have high variance. 
 Conclusion On The Drift Method 
The drift method is good at forecasting linear trends, and thats all...you see, when forecasting financial data you need models that are able to capture the complexity of the price structure as well as being robust to noise and outliers, the drift method isn't able to capture such complexity, its not a super smart method, same goes for linear regression. This is why more peoples are switching to more advanced models such a neural networks that can sometimes capture such complexity and return decent results.
So this method might not be the best but if you like lines then here you go.
 
Dollar Cost Average (Data Window Edition)Hi everyone
Hope you had a nice weekend and you're all excited for the week to come. At least I am (thanks to a few coffee but that still counts !!!)
This indicator is inspired from  Dollar-Cost-Average-Cost-Basis 
 EDUCATIONAL POST 
The educational post is coming a  bit later this afternoon  explaining how to use the indicator so I would advise to follow me so that you'll get updated in real-time :) (shameless self-advertising)
 1 - What is Dollar-Cost Averaging (DCA)? 
Dollar-Cost Averaging is a strategy that allows an investor to buy the same dollar amount of an investment on regular intervals. The purchases occur regardless of the asset's price.
I hope you're hungry because that one is a biggie and gave me a few headaches. Happy that it's getting out of my way finally and I can offer it
This indicator will analyse for the defined date range, how a dollar cost average (DCA) method would have performed vs investing all the hard earnt money at the beginning
 2- What's on the menu today ? 
Please check this screenshot to understand what you're supposed to see :  CLICK ME I'M A SCREENSHOT   (I'll repeat this URL one more time below as I noticed some don't read the information on my description and then will come pinging me saying "sir me no understand your indicator, itz buggy sir"
(yes I finally thought about a way to share screenshots on TradingView, took me 4 weeks, I'm slow to understand things apparently)
 My indicator works with all asset classes and with the daily/weekly/monthly timeframes 
As always, let's review quickly the different fields so that you'll understand how to use it (and I won't get spammed with questions in DM ^^)
-  Use current resolution  : if checked will use the resolution of the chart
-  Timeframe used for DCA  : different timeframe to be used if  Use current resolution  is unchecked
-  Amount invested in your local currency  : The amount in Fiat money that will be invested at each period selected above
-  Starting Date 
-  Ending Date 
-  Select a candle level for the desired timeframe   : If you want to use the open or close of the selected period above. Might make a diffence when the timeframe is weekly or monthly
 3 - Specifications used 
I got the idea from this website  dcabtc.com  and the result shown by this website and my indicator are very interesting in general and for your own trading
The formula used for the DCA calculation is that one :  Investopedia Dollar Cost Average 
 4 - How to interpret the results 
"But sir which results ??"...... those ones :   CLICK ME I'M A SCREENSHOT   :) (strike #2 with the screenshot)
It will draw all the plots and will give you some nice data to analyze in the Data Window section of TradingView
I'm not completely satisfied with the tool yet but the results are very closed to the  dcabtc  website mentioned above
If you're trading a very bullish asset class (who said crypto ?), it's very interesting to see what a DCA strategy could bring in term of performance. But DCA is not magic, there is a time component which is the day/week/month you'll start to invest (those who invested in crypto beginning of 2018 in altcoins know what I'm talking about and ..............will hate me for this joke)
 5 - What's next ? 
As said, the educational post is coming next but not only. 
Will probably post a strategy tomorrow using this indicator so that you can compare what's performing best between your trading and a dollar cost average method
I'll publish as a protected source this time a more advanced version of that one including DCA forecasts
 6 - Suggested alternative (but I'll you doing it) 
If you don't want to have this panel in the bottom with the plots and analyze the results in the data window, you can always create an infopanel like shown here  Risk-Reward-InfoPanel/  and display all the data there
Hope you'll like it, like me, love it, love me, tip me :)
____________________________________________________________ 
Feel free to hit the thumbs up as it shows me that I'm not doing this for nothing and will motivate to deliver more quality content in the future. (Meaning... a few likes only = no indicators = Dave enjoying the beach) 
- I'm an offically approved PineEditor/LUA/MT4 approved mentor on codementor. You can request a coaching with me if you want and I'll teach you how to build kick-ass indicators and strategies 
 Jump on a 1 to 1 coaching with me  
- You can also hire for a custom dev of your indicator/strategy/bot/chrome extension/python
sma-pivotsThis model is based on this script 
I change it to sma model . the model run on pivots high or low that are base on SMA 
I make two SMA one for high pivots and one for low pivots ( I put for now at same distance but you need to change it according to needs)
because asset can be in bull period or bear period when we have two separate distance of SMA we can find the correct combination if to buy more or less by changing either the sma pivot of the low end or the sma pivots of the high end using the length . also global we can use the lookbar of bar numbers 
one sma to both pivots is bad as it not consider the market situation but separation to two one for sell and one for buy can give you a better flexible model for enter or exit 
so its your job to find what length is best suited for exit and what for enter . 
  example when we have two different length how it work on 4 hour
TTM SQUEEZE with ALERT by NM// ######################################################################################
// This script was created because the original TTM Squeeze script
// did trigger when only one of the Bollinger Bands was 
// in the Keltner channel. It now gives the option to use it as was
// or to force it to only give a signal when both BB are in the Keltner channels
// 
// Furthermore an alert was added to fire when we are squeezing
// no matter which option your choose (original or strict)
//
// To create an alert, click on the alerts in the right column on your screen
// then click on the +button to add an alert. 
// Select from the conditions "CTTV Squeeze" and "Once per bar close"
// Keep in mind that you set this alert for one instrument and one particular time frame
//
// If you would have any questions, contact me : 
// TradingView : @Nico.Muselle
// ######################################################################################
How to start using this script ? 
1. Add this script to your favorites
2. Click on the Indicator-button on the top bar of your chart
3. Click on Favorites and find CTTV TTM
Do also check out my other indicators : 
 
 Percentage change - 
 Power Moving Average Pro - (use Moving Averages of higher time frames on lower time frame charts) - 
 Power Moving Average - (use 1 moving average of a higher time frame on the current time frame) - 
 BitFinex Longs vs. Shorts - 
 Relative Strength Index Direction - 
 Reversal Candles - 
 EMADiff - 
 Improved Linear Regression Bull and Bear Power v02 - 
 Improved Linear Regression Bull and Bear Power v01 - 
 
PS : Sorry about the messy chart - Bottom indicators show the TTM Squeeze, top one being the original posted here, bottom one being the more strict option.
Guerrilla AdvancedThis indicator was designed with people without Pro License in mind (Including many of my close friends).
Basically, you will get a combo of few different tools in one box, with ability to turn them on and off with a single check mark, also, you have total control over the input numbers that was used in calculations if you so want to, for example, sometimes when i see a massive bullish up trend, i reduce the short rally from 12 to 8 even 6 to get faster signal for selling the trend.
So, what will you get in this pack?
1- Ichimoko. Yes, you heard it right, although we have it in the default tools but hey, it will use one indicator slot and if you don't have a pro license, you will use that slot
2- Rally. This is an old yet very powerful system for getting buy or sell signals, basically, you get two lines and for making the life easier i draw a cloud between them. when the trend passes above the cloud and it was bellow it in past, right after the very first candle that gets above the cloud you can put the buy order, and vice versa, the moment a candle body enters the cloud, if you want an aggressive signal, you can sell, if not, you may want to wait to see if the candles drop bellow the cloud or not then decide.
3- Resistance Support Cloud. Most of us always heard about resistance and support "lines" but many of us don't know that, in each trend, the trend line itself is a resistance or support line, and when you are going in a bullish or bearish tunnel, the floor and roof of tunnels are again resistance and supports, using this part of the tool, just like rally, you get a cloud that shows you the resistance / support "zone"
4- William Fractals. To be honest, I got this part of the code from another source available around. Why? looking at those fractal indicators, you can easily eyeball the trend line or existence of a tunnel.
5- Different EMA lines. If you are one of those people that use EMA lines for their trading, have fun with them, there are few different standard ones and even a custom one that you can put your desired number for it.
Trench Cross ScalperThe original script was posted on ProRealCode by user Nicolas.
This indicator is an attempt of scalping strategy by crossing the mean high or low weigthed price over a short "n" period. This 2 lines represent the black "trench" on screenshots attached.
When signal line (blue one) crossing the buy trigger one (dotted green one) a buy signal should occur and vice-versa for a sell signal (when crossing the dotted red one). I add an option to draw the white signal line as the close price value of the high/low ones if they are respectively above or below the trench' buy or sell lines trigger.
The yellow green and red brick lines serve as stoploss.
The indicator can be use alone with no price chart as its values are derivated from it, of course if you dont mind about candlesticks informations.
I think enter/exit trades should occur very quickly, as it were designed for scalping trading purpose. I didn't have much time to test it for a long period, so here it is as a concept indicator, despite that, it does have sense.
Fibonacci WavesFirst of all, ignore all other lines in the example chart except the four FAT lines. The four fat lines are the ones that define the fibonacci price leves. The lines have different extension offset to the right. The shortest one is the end of the second wave ( or leg B ), the next one is the end of C, the one following that is the end of D and the final one is the end of the final leg E.
The two input parameters is the start of A and the end of A. 
If the start of A is larger than then end of A, the calculated series is a downward trend, else it is an upward trend.
Calculation based on old EWT simple wave expansion by fibonacci sequence.
0.618, 1.618, 0.382
Based on this source: 
www.ino.com
Best Regards,
/Hull, 2015.05.20.15:50 ( placera.se )
VWMA Series (Dynamic) mtf - Dual Gradient Colored"VWMA Series (Dynamic) mtf - Dual Gradient Colored" is a multi-timeframe (MTF) Volume-Weighted Moving Average (VWMA) ribbon indicator that plots up to 60 sequential VWMAs with arithmetic progression periods (e.g., 1, 4, 7, 10…).  Each VWMA line is dual-gradient colored:  Base hue = Greenish (#2dd204) if close > VWMA (bullish), Magenta (#ff00c8) if close < VWMA (bearish)  
Brightness gradient = fades from base → white as period increases (short → long-term)
Uses daily resolution by default (timeframe="D"), making it ideal for higher-timeframe trend filtering on lower charts.Key FeaturesFeature
Description
Dynamic Periods
Start + i × Increment → e.g., 1, 4, 7, 10… up to 60 terms
Dual Coloring
Bull/Bear + Gradient (short = vivid, long = pale)
MTF Ready
Plots daily VWMAs on any lower timeframe (1H, 15M, etc.)
No Lag on Long Sets
Predefined "best setups" eliminate repainting/lag
Transparency Control
Adjustable line opacity for clean visuals
Scalable
Up to 60 VWMAs (max iterations)
Recommended Setups (No Lag)Type
Example Sequence (Start, Inc, Iter)
Long-Term Trend
1, 3, 30 → 1, 4, 7 … 88
93, 3, 30 → 93, 96 … 180
372, 6, 30 → 372, 378 … 546
Short-Term Momentum
1, 1, 30 → 1, 2, 3 … 30
94, 2, 30 → 94, 96 … 152
1272, 5, 30 → 1272, 1277 … 1417
Key Use CasesUse Case
How to Use
1. Multi-Timeframe Trend Alignment
On 1H chart, use 1, 3, 30 daily VWMAs → price above all green lines = strong uptrend
2. Dynamic Support/Resistance
Cluster of long-term pale VWMAs = major S/R zone
3. Early Trend Change Detection
Short-term vivid lines flip from red → green before longer ones = early bullish signal
4. Ribbon Compression/Expansion
Tight bundle → consolidation; fanning out → trend acceleration
5. Mean Reversion Entries
Price far from long-term VWMA cluster + short-term reversal = pullback trade
6. Volume-Weighted Fair Value
Long-period VWMAs reflect true average price paid over weeks/months
Visual Summary
Price ↑
  ████  ← Short VWMA (vivid green = close > VWMA)
   ███
    ██
     █
    . . . fading to white
     █
    ██
   ███
  ████  ← Long VWMA (pale = institutional average)
Green lines = price above VWMA (bullish bias)  
Magenta lines = price below VWMA (bearish bias)  
Gradient = shorter (left) → brighter; longer (right) → whiter  
Ribbon thickness = trend strength (wide = strong, narrow = weak)
Best For  Swing traders using daily trend on intraday charts  
Volume-based strategies (VWMA > SMA)  
Clean, colorful trend visualization without clutter  
Institutional fair value anchoring via long-period VWMAs
Pro Tip:
Use Start=1, Increment=3, Iterations=30 on a 4H chart with timeframe="D" → perfect daily trend filter with zero lag and beautiful gradient flow.
Scissors&Knifes V3.1✂️ The Scissors (PAG Chop V4 Engine)
🧠 Core idea
Scissors measure market compression and breakout readiness.
They use a modified Choppiness Index that looks at the relationship between:
True Range volatility (ATR × period length)
The total high–low range over the same window.
The smaller the ratio (sum of TR vs range), the more directional and impulsive the market is.
The higher the ratio, the more “sideways” the market trades.
This version smooths the result over PAG_SMOOTHLEN bars and applies several color bands that correspond to volatility states.
🎨 Color code meaning
Range	State	Color	Interpretation
≤ 30	Strong Red	#8B0000	Momentum exhaustion on downside, sellers dominating — about to reverse or already strong down-trend.
30 – 38	Brick Red	#A52A2A	Fading downside pressure; often the “bleeding edge” of a bearish climax.
38 – 55	Transparent	black (α≈100)	Neutral chop zone — indecision, range-building.
55 – 61.8	Yellow (optional)	#DAA520	Early compression pocket where volatility starts contracting; the calm before a trend.
61.8 – 70	Bright Green	#556B2F	Energy release phase: volatility breaking out upward.
≥ 70	Strong Green	#355E3B	Sustained bullish drive, often continuation leg of a trend.
🪶 Secret nuance:
The transition bands (38–45 and 45–55) are treated as fully transparent to mark “dead zones.”
When PAG Chop sits here, all label activity pauses — the system resets its cluster memory so the next colored print begins a new “cluster”, letting you clearly see where fresh directional momentum starts.
🧩 Cluster logic
Every time a colored (non-transparent) reading appears, it belongs to a “color cluster.”
Grey labels (= count 1) mark the genesis of a new cluster, and following counts 2, 3, 4 … represent the internal continuity of that trend state.
You can optionally hide the first N grey or count 2 labels to reduce clutter on the initial stabilization bars.
✂️ Label meaning
Each label shows:
Emoji ✂️
Current count (e.g. ✂️ = 3 means 3 timeframes are simultaneously firing)
Optional list of the timeframes that contribute.
So a high count (e.g. 8–10) means many lower TFs are synchronizing volatility breakout — a multiframe alignment, often just before an acceleration burst.
🔪 The Knife (Mr Blonde V4 Engine)
🧠 Core idea
Mr Blonde converts the slope of a long EMA into an angle-of-attack metric — literally the “tilt” of market momentum.
It computes the EMA gradient relative to price span and rescales it into degrees (-5 ° to +5 °).
The steeper the angle, the stronger the directional push.
🎨 Color code meaning
Angle range	Color	Interpretation
≥ +5 °	Transparent (Black 1)	Fully over-extended up move — wait for reset.
+3.57 – +5 °	Dark Red	Strong upward slope, momentum apex.
+2.14 – +3.57 °	Orange	Medium upward slope, trend acceleration zone.
+0.71 – +2.14 °	Light Orange	Mild upward bias, pre-momentum phase.
0 to -0.71 °	Yellow	Neutral transition.
-0.71 – -2.14 °	Olive Green	Soft bearish slope.
-2.14 – -3.57 °	Olive Drab	Building bearish momentum.
-3.57 – -5 °	Hunter Green	Strong downward angle, aggressive push.
≤ -5 °	Transparent (Black 2)	Oversold/over-tilted — likely exhaustion.
🪶 Secret nuance:
Mr Blonde uses a “span normalization” factor that divides EMA slope by the dynamic range of highs and lows.
This lets it compare angles fairly across assets with different volatility profiles (e.g. BTC vs ES) — it’s one of the rare EMA-angle implementations that self-scales properly.
🗡 Label meaning
Emoji 🔪
Count = how many TFs share the same momentum angle bias.
When many TFs show the same slope polarity (e.g. knife = 8), you’re in a deep momentum cascade — a “knife trend.”
💫 Yellow knife
The yellow state marks neutrality or slope flattening.
If you enable yellow visibility (mb_show_yellow), you can see where momentum cools off — often the earliest reversal hint.
⚙️ Shared mechanics between ✂️ and 🔪
Multi-timeframe sweep
The script cycles through 1 m → 10 m by default, running both engines once per TF.
Each returning true adds +1 to the count.
So:
sc_hits = count of timeframes where PAG fires + 1
knife_hits = count of timeframes where MB fires + 1
That “+1 shift” means there’s always at least 1, letting count = 1 represent the local TF itself.
Cluster limiter
If Limit max labels per cluster is on, you cap how many total symbols (both ✂️ & 🔪, including trails) can appear within one color phase — avoiding chart spam during extended trends.
Trails
Each printed label seeds a short-lived “trail” sequence — faded copies extending N bars forward.
Trails visualize the linger effect of the last signal, useful for visually connecting bursts in momentum.
Grey or count = 1 labels can have shorter or longer trails depending on your overrides (*_trail_bars_grey).
They’re purely visual and do not affect alerting.
Alerts
Alerts fire independently of whether you hide labels — unless you enable “respect filters”.
This guarantees you never miss a structural signal even if you suppress visuals for clarity.
🌈 Interpreting Both Together
Scenario	Interpretation
✂️ = low (1–2) + 🔪 rising (red/orange)	Market just leaving chop, early thrust stage.
✂️ = high (≥ 5) + 🔪 green	Fully aligned breakout continuation — trend in progress.
✂️ = yellow cluster + 🔪 yellow	Volatility squeeze, energy buildup — next expansion near.
✂️ = green cluster → 🔪 turns red	Cross-state conflict; likely transition or correction.
✂️ = grey + 🔪 grey	Reset condition — both engines cooling; stand aside.
💡 Hidden edge:
Scissors signal potential, Knife measures kinetic force.
The perfect storm is when ✂️ goes from yellow→green one bar before 🔪 shifts from orange→green — it catches the birth of directional flow while volatility is still tight.
🧭 Reading the labels intuitively
Grey ✂️/🔪 = 1 → embryonic state, may fizzle or bloom.
✂️/🔪 = 2 or 3 → expansion taking hold.
✂️/🔪 ≥ 4 (mid black) → strong synchronized drive across TFs.
Transparent gap → cluster reset; prepare for new phase.
Trail lines → echo of previous cluster strength.
Final secret tip 🗝
Because both engines are mathematically uncorrelated (volatility vs EMA angle), when they agree in color polarity on multiple TFs, you have one of the cleanest probabilistic trend windows possible.
If you ever see ✂️ = 6 + 🔪 = 6 both pointing the same way — that’s a “knife-through-the-scissors” moment: volatility expansion and directional slope synchronized — those are the bars where institutional algorithms tend to add size.
Opening Range Break LRSThis script is designed for a trend-following, opening range breakout strategy. The main idea is to only trade breakouts that happen in the same direction as the short-term trend, which the script identifies using a linear regression slope.
1. Identify the Short-Term Trend
This is the first and most important step. The script does this for you using the Linear Regression and the bar coloring.
•	If the bars are colored BLUE: The linear regression slope is positive. This means the script considers the short-term trend to be UP. A trader using this script would only look for long (buy) trades.
•	If the bars are colored YELLOW: The linear regression slope is negative. This means the script considers the short-term trend to be DOWN. A trader using this script would only look for short (sell) trades.
This filter is designed to prevent you from trading a "false breakout" against the immediate momentum.
2. Watch the Opening Ranges Form
At the start of the trading session (8:30 AM by default), the script will begin drawing boxes for the 5, 15, 30, and 60-minute opening ranges you've enabled.
•	The 5-minute box (e.g., gray) will be set after the 8:30 - 8:35 period.
•	The 15-minute box (e.g., blue) will be set after the 8:30 - 8:45 period.
•	...and so on.
These boxes, which extend for the rest of the day, represent the key high and low levels established at the open. The "Live Box Extension" input simply keeps the right edge of the box a few bars away from the current price so you can see it clearly.
3. Look for a Filtered Breakout Signal
This is where the trend filter (Step 1) and the range boxes (Step 2) come together.
Bullish Trade Example (Long):
1.	A trader sees the bars are colored BLUE (uptrend). They are now only looking for a break above one of the ORB highs.
2.	They will ignore any break below the ORB lows, as that would be trading against the trend filter.
3.	The price moves up and finally closes above the 15-minute ORB high.
4.	The script will plot a green "Break 15" label. This is the trader's signal to enter a long trade.
Bearish Trade Example (Short):
1.	A trader sees the bars are colored YELLOW (downtrend). They are now only looking for a break below one of the ORB lows.
2.	They will ignore any break above the ORB highs.
3.	The price moves down and closes below the 5-minute ORB low.
4.	The script will plot a red "Break 5" label. This is the trader's signal to enter a short trade.
4. Use Multiple Timeframes for Context
The real power of this script is seeing all the ranges at once. A trader wouldn't just trade them in isolation.
•	Confirmation: A "Break 5" signal is a quick, early signal. But if the price also breaks the "15" and "30" minute highs, it signals much stronger bullish consensus, which might encourage the trader to hold the trade longer.
•	Support & Resistance: The other ORB levels act as a map for the day.
o	As Targets: If a trader takes a "Break 15" long signal, the 30-minute ORB high and 60-minute ORB high become logical profit targets.
o	As Warning Signs: If the price gives a "Break 5" long signal but is struggling right under the 15-minute high, a trader might wait for that 15-minute level to break before entering, seeing it as a key resistance level.
Summary: A Trader's Workflow
1.	Morning (8:30 AM): Watch the script. What color are the bars? (Blue = longs only, Yellow = shorts only).
2.	Wait: Let the 5, 15, 30, and 60-minute ranges form. The boxes will be drawn on the chart.
3.	Execute: Wait for a "Break" signal (a label) that matches your trend direction.
4.	Manage: Use the other ORB levels as potential profit targets or as confirmation of the move's strength.
5.	Single Signal: The "Single Signal Only" input, if checked, ensures they only get one signal per timeframe (e.g., one "Break 15" long, and that's it for the day), which helps prevent over-trading in choppy conditions.
Session Streaks [LuxAlgo]The  Session Streaks  tool allows traders to identify whether a session is bullish or bearish on the chart. It also shows the current session streak, or the number of consecutive bullish or bearish sessions.
The tool features a dashboard with information about the session streaks of the underlying product on the chart.
🔶  USAGE 
  
Analyzing session streaks is commonly used for market timing by studying the number of consecutive sessions over time and how long they last before the market changes direction.
We identify a bullish session as one in which the closing price is equal to or greater than the opening price, and a bearish session as one in which the closing price is below the opening price.
Each session is labeled according to its bias (bullish or bearish) and the number of consecutive sessions of the same type that conform the current streak.
🔹  Dashboard 
  
The dashboard at the top shows information about the current session.
Under the "Streaks" header, historical information about session streaks is displayed, divided into bullish and bearish categories.
 
 Number: Total number of streaks.
 Median: The average duration of those streaks. We chose the median over the mean to avoid misrepresentation due to outliers.
 Mode: The most common streak duration.
 
As the image shows, for this particular market, there are more bullish streaks than bearish ones. Bullish streaks have an average duration that is longer than that of bearish streaks, and both have the same most common streak duration.
If the current session is bullish and the median streak duration for bullish sessions is three, then we could consider scenarios in which the next two sessions are bullish.
🔶  DETAILS 
🔹  Streaks On Larger Timeframes 
  
On timeframes lower than or equal to Daily, the tool identifies each consecutive session, but this behavior changes on larger timeframes.
On timeframes larger than daily, the tool identifies the last session of each bar. Let's use the chart in the image as a reference.
At the top of the image, there is a daily chart where each session corresponds to each candle. One candle equals one day.
In the middle, we have a weekly chart where each session is the last session of each week, which is usually Friday for the Nasdaq 100 futures contract. The levels and labels displayed correspond to the last session within each candle, which is the last day of each week.
The levels and labels on the monthly chart correspond to the last session of each month, which is the last day of each month.
🔹  Gradient Style 
  
Traders can choose between two different color gradients for the session background. Each gradient provides different information about price behavior within each session.
 
  Horizontal: Green indicates prices at the top of the session range and red indicates prices at the bottom.
  Vertical: Green indicates prices that are equal to or greater than the open price and red indicates prices that are below the open price of the session.
 
🔶  SETTINGS 
🔹  Dashboard 
 
  Dashboard: Enable or disable the dashboard.
  Position: Select the location of the dashboard.
  Size: Select the dashboard size.
 
🔹  Style 
 
  Bullish: Select a color for bullish sessions.
  Bearish: Select a color for bearish sessions.
  Transparency: Select a transparency level from 100 to 0.
  Gradient: Select a horizontal or vertical gradient.
pine script tradingbot - many ema oscillator## 🧭 **Many EMA Oscillator (TradingView Pine Script Indicator)**  
*A multi-layer EMA differential oscillator for trend strength and momentum analysis*
---
### 🧩 **Overview**
The **Many EMA Oscillator** is a **TradingView Pine Script indicator** designed to help traders visualize **trend direction**, **momentum strength**, and **multi-timeframe EMA alignment** in one clean oscillator panel.  
It’s a **custom EMA-based trend indicator** that shows how fast or slow different **Exponential Moving Averages (EMAs)** are expanding or contracting — helping you identify **bullish and bearish momentum shifts** early.
This **Pine Script EMA indicator** is especially useful for traders looking to combine multiple **EMA signals** into one **momentum oscillator** for better clarity and precision.
---
### ⚙️ **How It Works**
1. **Multiple EMA Layers:**  
   The indicator calculates seven **EMAs** (default: 20, 50, 100, 150, 200, 300) and applies a **smoothing filter** using another EMA (default smoothing = 20).  
   This removes short-term noise and gives a smoother, professional-grade momentum reading.
2. **EMA Gap Analysis:**  
   The oscillator measures the **difference between consecutive EMAs**, revealing how trend layers are separating or converging.  
   ```
   diff1 = EMA(20) - EMA(50)
   diff2 = EMA(50) - EMA(100)
   diff3 = EMA(100) - EMA(150)
   diff4 = EMA(150) - EMA(200)
   diff5 = EMA(200) - EMA(300)
   ```
   These gaps (or “differentials”) show **trend acceleration or compression**, acting like a **multi-EMA MACD system**.
3. **Color-Coded Visualization:**  
   Each differential (`diff1`–`diff5`) is plotted as a **histogram**:  
   - 🟢 **Green bars** → EMAs expanding → bullish momentum growing  
   - 🔴 **Red bars** → EMAs contracting → bearish momentum or correction  
   This gives a clean, compact view of **trend strength** without cluttering your chart.
4. **Automatic Momentum Signals:**  
   - **🟡 Up Triangle** → All EMA gaps increasing → strong bullish trend alignment  
   - **⚪ Down Triangle** → All EMA gaps decreasing → trend weakening or bearish transition  
---
### 📊 **Inputs**
| Input | Default | Description |
|-------|----------|-------------|
| `smmoth_emas` | 20 | Smoothing factor for all EMAs |
| `Length2`–`Length7` | 20–300 | Adjustable EMA periods |
| `Length21`, `Length31`, `Length41`, `Length51` | Optional | For secondary EMA analysis |
---
### 🧠 **Interpretation Guide**
| Observation | Meaning |
|--------------|----------|
| Increasing green bars | Trend acceleration and bullish continuation |
| Decreasing red bars | Trend exhaustion or sideways consolidation |
| Yellow triangles | All EMA layers aligned bullishly |
| White triangles | All EMA layers aligned bearishly |
This **EMA oscillator for TradingView** simplifies **multi-EMA trading strategies** by showing alignment strength in one place.  
It works great for **swing traders**, **scalpers**, and **trend-following systems**.
---
### 🧪 **Best Practices for Use**
- Works on **all TradingView timeframes** (1m, 5m, 1h, 1D, etc.)  
- Suitable for **stocks, forex, crypto, and indices**  
- Combine with **RSI**, **MACD**, or **price action** confirmation  
- Excellent for detecting **EMA compression zones**, **trend continuation**, or **momentum shifts**  
- Can be used as part of a **multi-EMA trading strategy** or **trend strength indicator setup**
---
### 💡 **Why It Stands Out**
- 100% built in **Pine Script v6**  
- Optimized for **smooth EMA transitions**  
- Simple color-coded momentum visualization  
- Professional-grade **multi-timeframe trend oscillator**  
This is one of the most **lightweight and powerful EMA oscillators** available for TradingView users who prefer clarity over clutter.
---
### ⚠️ **Disclaimer**
This indicator is published for **educational and analytical purposes only**.  
It does **not provide financial advice**, buy/sell signals, or investment recommendations.  
Always backtest before live use and trade responsibly.
---
### 👨💻 **Author**
Developed by **@algo_coders**  
Built in **Pine Script v6** on **TradingView**  
Licensed under the  (mozilla.org)
Power RSI Segment Runner [CHE]  Power RSI Segment Runner   — Tracks RSI momentum across higher timeframe segments to detect directional switches for trend confirmation.
  Summary 
This indicator calculates a running Relative Strength Index adapted to segments defined by changes in a higher timeframe, such as daily closes, providing a smoothed view of momentum within each period. It distinguishes between completed segments, which fix the final RSI value, and ongoing ones, which update in real time with an exponential moving average filter. Directional switches between bullish and bearish momentum trigger visual alerts, including overlay lines and emojis, while a compact table displays current trend strength as a progress bar. This segmented approach reduces noise from intra-period fluctuations, offering clearer signals for trend persistence compared to standard RSI on lower timeframes.
  Motivation: Why this design? 
Standard RSI often generates erratic signals in choppy markets due to constant recalculation over fixed lookback periods, leading to false reversals that mislead traders during range-bound or volatile phases. By resetting the RSI accumulation at higher timeframe boundaries, this indicator aligns momentum assessment with broader market cycles, capturing sustained directional bias more reliably. It addresses the gap between short-term noise and long-term trends, helping users filter entries without over-relying on absolute overbought or oversold thresholds.
  What’s different vs. standard approaches? 
- Baseline Reference: Diverges from the classic Wilder RSI, which uses a fixed-length exponential moving average of gains and losses across all bars.
- Architecture Differences:
  - Segments momentum resets at higher timeframe changes, isolating calculations per period instead of continuous history.
  - Employs persistent sums for ups and downs within segments, with on-the-fly RSI derivation and EMA smoothing.
  - Integrates switch detection logic that clears prior visuals on reversal, preventing clutter from outdated alerts.
  - Adds overlay projections like horizontal price lines and dynamic percent change trackers for immediate trade context.
- Practical Effect: Charts show discrete RSI endpoints for past segments alongside a curved running trace, making momentum evolution visually intuitive. Switches appear as clean, extendable overlays, reducing alert fatigue and highlighting only confirmed directional shifts, which aids in avoiding whipsaws during minor pullbacks.
  How it works (technical) 
The indicator begins by detecting changes in the specified higher timeframe, such as a new daily bar, to define segment boundaries. At each boundary, it finalizes the prior segment's RSI by summing positive and negative price changes over that period and derives the value from the ratio of those sums, then applies an exponential moving average for smoothing. Within the active segment, it accumulates ongoing ups and downs from price changes relative to the source, recalculating the running RSI similarly and smoothing it with the same EMA length.
Points for the running RSI are collected into an array starting from the segment's onset, forming a curved polyline once sufficient bars accumulate. Comparisons between the running RSI and the last completed segment's value determine the current direction as long, short, or neutral, with switches triggering deletions of old visuals and creation of new ones: a label at the RSI pane, a vertical dashed line across the RSI range, an emoji positioned via ATR offset on the price chart, a solid horizontal line at the switch price, a dashed line tracking current close, and a midpoint label for percent change from the switch.
Initialization occurs on the first bar by resetting accumulators, and visualization gates behind a minimum bar count since the segment start to avoid early instability. The trend strength table builds vertically with filled cells proportional to the rounded RSI value, colored by direction. All drawing objects update or extend on subsequent bars to reflect live progress.
  Parameter Guide 
EMA Length — Controls the smoothing applied to the running RSI; higher values increase lag but reduce noise. Default: 10. Trade-offs: Shorter settings heighten sensitivity for fast markets but risk more false switches; longer ones suit trending conditions for stability.
Source — Selects the price data for change calculations, typically close for standard momentum. Default: close. Trade-offs: Open or high/low may emphasize gaps, altering segment intensity.
Segment Timeframe — Defines the higher timeframe for segment resets, like daily for intraday charts. Default: D. Trade-offs: Shorter frames create more frequent but shorter segments; longer ones align with major cycles but delay resets.
Overbought Level — Sets the upper threshold for potential overbought conditions (currently unused in visuals). Default: 70. Trade-offs: Adjust for asset volatility; higher values delay bearish warnings.
Oversold Level — Sets the lower threshold for potential oversold conditions (currently unused in visuals). Default: 30. Trade-offs: Lower values permit deeper dips before signaling bullish potential.
Show Completed Label — Toggles labels at segment ends displaying final RSI. Default: true. Trade-offs: Enables historical review but can crowd charts on dense timeframes.
Plot Running Segment — Enables the curved polyline for live RSI trace. Default: true. Trade-offs: Visualizes intra-segment flow; disable for cleaner panes.
Running RSI as Label — Displays current running RSI as a forward-projected label on the last bar. Default: false. Trade-offs: Useful for quick reads; may overlap in tight scales.
Show Switch Label — Activates RSI pane labels on directional switches. Default: true. Trade-offs: Provides context; omit to minimize pane clutter.
Show Switch Line (RSI) — Draws vertical dashed lines across the RSI range at switches. Default: true. Trade-offs: Marks reversal bars clearly; extends both ways for reference.
Show Solid Overlay Line — Projects a horizontal line from switch price forward. Default: true. Trade-offs: Acts as dynamic support/resistance; wider lines enhance visibility.
Show Dashed Overlay Line — Tracks a dashed line from switch to current close. Default: true. Trade-offs: Shows price deviation; thinner for subtlety.
Show Percent Change Label — Midpoint label tracking percent move from switch. Default: true. Trade-offs: Quantifies progress; centers dynamically.
Show Trend Strength Table — Displays right-side table with direction header and RSI bar. Default: true. Trade-offs: Instant strength gauge; fixed position avoids overlap.
Activate Visualization After N Bars — Delays signals until this many bars into a segment. Default: 3. Trade-offs: Filters immature readings; higher values miss early momentum.
Segment End Label — Color for completed RSI labels. Default: 7E57C2. Trade-offs: Purple tones for finality.
Running RSI — Color for polyline and running elements. Default: yellow. Trade-offs: Bright for live tracking.
Long — Color for bullish switch visuals. Default: green. Trade-offs: Standard for uptrends.
Short — Color for bearish switch visuals. Default: red. Trade-offs: Standard for downtrends.
Solid Line Width — Thickness of horizontal overlay line. Default: 2. Trade-offs: Bolder for emphasis on key levels.
Dashed Line Width — Thickness of tracking and vertical lines. Default: 1. Trade-offs: Finer to avoid dominance.
  Reading & Interpretation 
Completed segment RSIs appear as static points or labels in purple, indicating the fixed momentum at period close—values drifting toward the upper half suggest building strength, while lower half implies weakness. The yellow curved polyline traces the live smoothed RSI within the current segment, rising for accumulating gains and falling for losses. Directional labels and lines in green or red flag switches: green for running momentum exceeding the prior segment's, signaling potential uptrend continuation; red for the opposite.
The right table's header colors green for long, red for short, or gray for neutral/wait, with filled purple bars scaling from bottom (low RSI) to top (high), topped by the numeric value. Overlay elements project from switch bars: the solid green/red line as a price anchor, dashed tracker showing pullback extent, and percent label quantifying deviation—positive for alignment with direction, negative for counter-moves. Emojis (up arrow for long, down for short) float above/below price via ATR spacing for quick chart scans.
  Practical Workflows & Combinations 
- Trend Following: Enter long on green switch confirmation after a higher high in structure; filter with table strength above midpoint for conviction. Pair with volume surge for added weight.
- Exits/Stops: Trail stops to the solid overlay line on pullbacks; exit if percent change reverses beyond 2 percent against direction. Use wait bars to confirm without chasing.
- Multi-Asset/Multi-TF: Defaults suit forex/stocks on 1H-4H with daily segments; for crypto, shorten EMA to 5 for volatility. Scale segment TF to weekly for daily charts across indices.
- Combinations: Overlay on EMA clouds for confluence—switch aligning with cloud break strengthens signal. Add volatility filters like ATR bands to debounce in low-volume regimes.
  Behavior, Constraints & Performance 
Signals confirm on bar close within segments, with running polyline updating live but gated by minimum bars to prevent flicker. Higher timeframe changes may introduce minor repaints on timeframe switches, mitigated by relying on confirmed HTF closes rather than intrabar peeks. Resource limits cap at 500 labels/lines and 50 polylines, pruning old objects on switches to stay efficient; no explicit loops, but array growth ties to segment length—suitable for up to 500-bar histories without lag.
Known limits include delayed visualization in short segments and insensitivity to overbought/oversold levels, as thresholds are inputted but not actively visualized. Gaps in source data reset accumulators prematurely, potentially skewing early RSI.
  Sensible Defaults & Quick Tuning 
Start with EMA length 10, daily segments, and 3-bar wait for balanced responsiveness on hourly charts. For excessive switches in ranging markets, increase wait bars to 5 or EMA to 14 to dampen noise. If signals lag in trends, drop EMA to 5 and use 1H segments. For stable assets like indices, widen to weekly segments; tune colors for dark/light themes without altering logic.
  What this indicator is—and isn’t 
This tool serves as a momentum visualization and switch detector layered over price action, aiding trend identification and confirmation in segmented contexts. It is not a standalone trading system, predictive model, or risk calculator—always integrate with broader analysis, position sizing, and stop-loss discipline. View it as an enhancement for discretionary setups, not automated alerts without validation.
  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
PM Range Breaker [CHE]  PM Range Breaker   — Premarket bias with first-five range breaks, optional SWDEMA regime latch, and simple two-times-range targets
  Summary 
This indicator sets a once-per-day directional bias during New York premarket and then tracks a strict first-five-minutes range from the session open. After the first five complete, it marks clean breakouts and can project targets at two times the measured range. A second mode latches an EMA-based regime to inform the bias and optional background tinting. A compact panel reports live state, first-five levels, and rolling hit rates of both bias modes using a user-defined midday close for statistics.
  Motivation: Why this design? 
Intraday traders often get whipsawed by early noise or by fast flips in trend filters. This script commits to a bias at a single premarket minute and then waits for the market to present an objective structure: the first-five range. Breaks after that window are clearer and easier to manage. The alternative SWDEMA regime gives a slower, latched context for users who prefer a trend scaffold rather than a midpoint reference.
  What’s different vs. standard approaches? 
 Baseline: Typical open-range-breakout lines or a single moving-average filter without daily commitment.
 Architecture differences:
   Bias decision at a fixed New York time using either a midpoint lookback (“Classic”) or a two-EMA regime latch (“SWDEMA”).
   Strict five-minute window from session open; breakout shapes print only after that window.
   Single-shot breakout direction per session (debounce) and optional two-times-range targets.
   On-chart panel with hit rates using a configurable midday close for statistics.
 Practical effect: Cleaner visuals, fewer repeated signals, and a traceable daily decision that can be evaluated over time.
  How it works (technical) 
 Time handling uses New York session times for premarket decision, open, first-five end, and a midday statistics checkpoint.
 Classic bias: A midpoint is computed from the highest and lowest over a user period; at the premarket minute, the bias is set long when the close is above the midpoint, short otherwise.
 SWDEMA bias: Two EMAs define a regime score that requires price and trend agreement; when both agree on a confirmed bar, the regime latches. At the premarket minute, the daily bias is set from the current regime.
 The first-five range captures high and low from open until the end minute, then freezes. Breakouts are detected after that window using close-based cross logic.
 The script draws range lines and optional targets at two times the frozen range. A session break direction latch prevents duplicate break markers.
 Statistics compare daily open and a configurable midday close to record if the chosen bias aligned with the move.
 Optional elements include EMA lines, midpoint line, latched-regime background, and regime switch markers.
 Data aggregation for day logic and the first-five window is sampled on one-minute data with explicit lookahead off. On charts above one minute, values update intra-bar until the underlying minute closes.
  Parameter Guide 
Premarket Start (NY) — Minute when the bias is decided — Default: 08:30 — Move earlier for more stability; later for recency.
Market Open (NY) — Session start used for the first-five window — Default: 09:30 — Align to instrument’s RTH if different.
First-5 End (NY) — End of the first-five window — Default: 09:35 — Extend slightly to capture wider opening ranges.
Day End (NY) for Stats — Midday checkpoint for hit rate — Default: 12:00 — Use a later time for a longer evaluation window.
Show First-5 Lines — Draw the frozen range lines — Default: On — Turn off if your chart is crowded.
Show Bias Background (Session) — Tint by daily bias during session — Default: On — Useful for directional context.
Show Break Shapes — Print breakout triangles — Default: On — Disable if you only want lines and alerts.
Show 2R Targets (Optional) — Plot targets at two times the range — Default: On — Switch off if you manage exits differently.
Line Length Right — Extension length of drawn lines — Default: 20 (bars) — Increase for slower timeframes.
High/Low Line Colors — Visual colors for range levels — Defaults: Green/Red — Adjust to your theme.
Long/Short Bias Colors — Background tints — Defaults: Green/Red with high transparency — Lower transparency for stronger emphasis.
Show Corner Panel — Enable the info panel — Default: On — Centralizes status and numbers.
Show Hit Rates in Panel — Include success rates — Default: On — Turn off to reduce panel rows.
Panel Position — Anchor on chart — Default: Top right — Move to avoid overlap.
Panel Size — Text size in panel — Default: Small — Increase on high-resolution displays.
Dark Panel — Dark theme for the panel — Default: On — Match your chart background.
Show EMA Lines — Plot blue and red EMAs — Default: Off — Enable for SWDEMA context.
Show Midpoint Line — Plot the midpoint — Default: Off — Useful for Classic mode visualization.
Midpoint Lookback Period — Bars for high-low midpoint — Default: 300 — Larger values stabilize; smaller values respond faster.
Midpoint Line Color — Color for midpoint — Default: Gray — A neutral line works best.
SWDEMA Lengths (Blue/Red) — Periods for the two EMAs — Defaults: 144 and 312 — Longer values reduce flips.
Sources (Blue/Red) — Price sources — Defaults: Close and HLC3 — Adjust if you prefer consistency.
Offsets (Blue/Red) — Pixel offsets for EMA plots — Defaults: zero — Use only for visual shift.
Show Latched Regime Background — Background by SWDEMA regime — Default: Off — Separate from session bias.
Latched Background Transparency — Opacity of regime background — Default: eighty-eight — Lower value for stronger tint.
Show Latch Switch Markers — Plot regime change markers — Default: Off — For auditing regime changes.
Bias Mode — Classic midpoint or SWDEMA latch — Default: Classic — Choose per your style.
Background Mode — Session bias or SWDEMA regime — Default: Session — Decide which background narrative you want.
  Reading & Interpretation 
 Panel: Shows the active bias, first-five high and low, and a state that reads Building during the window, Ready once frozen, and Break arrows when a breakout occurs. Hit rates show the percentage of days where each bias mode aligned with the midday move.
 Colors and shapes: Green background implies long bias; red implies short bias. Triangle markers denote the first valid breakout after the first-five window. Optional regime markers flag regime changes.
 Lines: First-five high and low form the core structure. Optional targets mark a level at two times the frozen range from the breakout side.
  Practical Workflows & Combinations 
 Trend following: Choose a bias mode. Wait for the first clean breakout after the first-five window in the direction of the bias. Confirm with structure such as higher highs and higher lows or lower highs and lower lows.
 Exits and risk: Conservative users can trail behind the opposite side of the first-five range. Aggressive users can scale near the two-times-range target.
 Multi-asset and multi-TF: Works well on intraday timeframes from one minute upward. For non-US sessions, adjust the time inputs to the instrument’s regular trading hours.
  Behavior, Constraints & Performance 
 Repaint and confirmation: Bias and regime decisions use confirmed bars. Breakout signals evaluate on bar close at the chart timeframe. On higher timeframes, minute-based sources update within the live bar until the minute closes.
 security and HTF: The script samples one-minute data. Lookahead is off. Values stabilize once the source minute closes.
 Resources: `max_bars_back` is five thousand. Drawing objects and the panel update efficiently, with position extensions handled on the last bar.
 Known limits: Midday statistics use the configured time, not the official daily close. Session logic assumes New York session timing. Targets are simple multiples of the first-five range and do not adapt to volatility beyond that structure.
  Sensible Defaults & Quick Tuning 
Start with Classic bias, midpoint lookback at three hundred, and all visuals on.
 Too many flips in context → switch to SWDEMA mode or increase EMA lengths.
 Breakouts feel noisy → extend the first-five end by a minute or two, or wait for a retest by your own rules.
 Too sluggish → reduce midpoint lookback or shorten EMA lengths.
 Chart cluttered → hide EMA or midpoint lines and keep only range levels and breakout shapes.
  What this indicator is—and isn’t 
This is a visualization and signal layer for session bias and first-five structure. It does not manage orders, position sizing, or risk. It is not predictive. Use it alongside market structure, execution rules, and independent risk controls.
 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 
Many thanks to LonesomeTheBlue
 for the original work. I adapted the midpoint calculation for this script. www.tradingview.com 






















