Time Offset Calculation Framework - PineCoders FAQ█ OVERVIEW
Calculating time-based offsets is necessary when coders need to draw lines or labels into the future because using `xloc = xloc.bar_time` in `label.new()` or `line.new()` is then mandatory.
This script provides a function to help with those calculations:
f_timeFrom(_from, _qty, _units)
The function calculates a negative (into the past) or positive (into the future) offset from the current bar's starting or closing time, or from the current time of day.
The offset can be expressed in units of chart resolution, or in seconds, minutes, hours, days, months or years.
█ HOW TO USE THE FRAMEWORK
1. You will need to include the supplied `f_resInMinutes()` function in your script in order to use `f_timeFrom()`.
It is used to calculate offsets using chart units when `f_timeFrom(_, _, "chart")` is used.
2. Whether you use `f_timeFrom()` for labels or lines, remember to use `xloc = xloc.bar_time`, as the default is `xloc = xloc.bar_index`.
3. Use `f_timeFrom()` for the `x` argument in `label.new()`, or for `x1` or `x2` in `line.new()`.
It can of course also be used in the relevant `label.set_*()` or `line.set_*()` functions.
Examples
// Label 3 days into the future from current bar's time.
label.new(f_timeFrom("bar", 3, "days"), high, "time + 3 days", xloc.bar_time)
// Label 2 hours into the future from current time
label.new(f_timeFrom("now", 2, "hours"), high, "timenow + 3 hours", xloc.bar_time)
// Label at bar's time plus 4 units of the chart's resolution.
label.new(f_timeFrom("bar", 4, "chart"), high, "time + 3 chart units", xloc.bar_time)
The parameters are:
f_timeFrom(_from, _qty, _units) =>
// _from : starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
// _qty : the +/- qty of _units of offset required. A "series float" can be used but it will be cast to a "series int".
// _units : string containing one of the seven allowed time units: "chart" (chart's resolution), "seconds", "minutes", "hours", "days", "months", "years".
█ LIMITATIONS
While this function makes it easier for coders to calculate time offsets using a variety of methods, it does not solve the inherent problematic that offsets do not calculate accurately when bars are missing between the start and end times of the offset. There is currently no way to circumvent this challenge in Pine.
Missing bars will occur on holidays, during no-trade periods (including normal periods where markets are closed) and when there are irregularities in data feeds. Charts at seconds resolutions, for example, will often miss bars when there are no trades to update the feed. On hourly charts of non 24x7 markets, periods when the markets are closed will also cause irregularities, as will holidays on day charts.
Other irregularities can occur because of how the offsets are calculated. A calculation of a one second offset from the bar's time will end one bar further on daily charts, for example. `f_timeFrom()` is no panacea; it simply makes offsets easier to calculate, however imprecise they are.
█ HOW TO USE THIS SCRIPT
The script's Inputs allow you to specify an offset, its units and starting time, and control the frequency of bars where lines are drawn.
Use the Inputs to play around with the parameters; you will quickly notice the irregularities mentioned above and be able to judge the usefulness of time-based offsets on the type of chart you use.
Look first. Then leap.
Faq
Alert Creation Framework - PineCoders FAQThis script provides a framework to add alerts to a script.
It uses a method and provides code that:
— Allows the indicator's users to select the plotting of markers representing the different conditions used to trigger alerts.
— Allows filtering of the markers on direction: both, longs only, shorts only.
— Uses a single alert for the indicator. It will trigger on any number of marker conditions selected by the user when the alert is configured. The user can thus create the combination that suits his needs.
— Includes the marker's number in the alert's message.
NOTES
— Alerts should usually be configured to trigger Once Per Bar Close to prevent false signals.
— See the Pine User Manual page on alerts .
— This code uses the Pine Script Coding Conventions .
Look first. Then leap.
MTF Selection Framework - PineCoders FAQOur MTF Selection Framework allows Pine coders to add multi-timeframe capabilities to their script with the following features:
► Timeframe selection
The higher timeframe can be selected using 3 different ways:
• By steps (60 min., 1D, 3D, 1W, 1M, 1Y).
• As a multiple of the current chart's resolution, which can be fractional, so 3.5 will work.
• Fixed.
► Non-repainting or Repainting mode can be selected.
► Smoothing of the HTF line
Can be turned on/off and a smoothing factor allows the user to select the degree of smoothing he requires.
The framework is used here to create a higher timeframe version of a simple RSI line, but it can be used to access HTF information for almost any signal.
Functions used
f_resInMinutes()
Converts the current timeframe.multiplier plus the TF into minutes of type float.
• In Pine, the timeframe.multiplier is an integer representing the resolution, but a value of 1 can mean one day or one minute. This function converts that information in a standard fractional float minutes format that can then be used by the other functions in the framework.
• If the chart's current resolution is 15 seconds, the function will return 0.25 . If the chart's resolution is one day, it will return 1440 .
f_tfResInMinutes(_resolution)
Returns resolution of _resolution period in minutes.
• This function does the same as f_resInMinutes() , but on the target resolution supplied as a parameter in the timeframe.period string format.
f_resNextStep(_res)
Given a current resolution in fractional float minutes, returns its corresponding stepped HTF in the timeframe.period string format.
• This allows the implementation of the step HTF selection mode.
f_multipleOfRes(_res, _mult)
Given a current resolution in fractional float minutes and a fractional multiplier, returns a multiple of the resolution as a string in "timeframe.period" format usable with "security()".
• A multiple like 3.5 is allowed.
• Note that with seconds resolutions, the result returned is constrained by the discrete seconds resolutions available on TV.
f_htfLabel(_txt, _y, _color)
Used to display a label showing either:
• A warning when the chart's resolution is not lower than the HTF.
• The HTF resolution currently used.
The y position used to position the label will require adaptation to the signal you are using. For use in "overlay = true" mode, a technique that works well is commented out in the code.
Look first. Then leap.
Functions Allowing Series As Length - PineCoders FAQ█ WARNING
Improvements to the following Pine built-ins have deprecated the vast majority of this publication's functions, as the built-ins now accept "series int" `length` arguments:
ta.wma()
ta.linreg()
ta.variance()
ta.stdev()
ta.correlation()
NOTE
For an EMA function that allows a "series int" argument for `length`, please see `ema2()` in the ta library by TradingView .
█ ORIGINAL DESCRIPTION
Pinescript requires many of its built-in functions to use a simple int as their period length, which entails the period length cannot vary during the script's execution. These functions allow using a series int or series float for their period length, which means it can vary on each bar.
The functions shared in this script include:
Rolling sum: Sum(src,p)
Simple moving average: Sma(src,p)
Rolling variance: Variance(src,p)
Rolling standard deviation: Stdev(src,p)
Rolling covariance: Covariance(x,y,p)
Rolling correlation: Correlation(x,y,p)
If p is a float then it is rounded to the nearest int .
How to Use the Script
Most of the functions in the script are dependent on the Sma function. The Correlation function uses the Covariance and Stdev functions. Be sure you include all the required functions in your script.
Make sure the series you use as the length argument is greater than 0, else the functions will return na . When using a series as length argument, the following error might appear:
Pine cannot determine the referencing length of a series. Try using max_bars_back in the study or strategy function.
This can be frequent if you use barssince(condition) where condition is a relatively rare event. You can fix it by including max_bars_back=5000 in your study declaration statement as follows:
study("Title",overlay=true,max_bars_back=5000)
Example
The chart shows the Sma , Stdev , Covariance and Correlation functions. The Sma uses the closing price as input and bars as period length where:
bars = barssince(change(security(syminfo.tickerid,"D",close ,lookahead=true)))
The Stdev uses the closing price as input and bars + 9 as period length. The Covariance and Correlation use the closing price as x and bar_index as y , with bars + 9 as period length.
Look first. Then leap.
Script Stopwatch - PineCoders FAQ█ WARNING
The publication of our LibraryStopwatch has deprecated this publication.
█ ORIGINAL DESCRIPTION
This script calculates the run time of a Pine script. While its numbers are not very precise and it doesn’t work on all scripts, it will help developers calculate run times more precisely than by hand, and so provides Pine coders with an additional profiling tool to help them optimize their code.
How to use the code
• Place the code included between the up/down arrows after your script’s input() calls.
• Comment out the display modes you don’t want to use.
• Save your script, wait and look at the results.
• Results show in different colors, depending on the average time per bar:
- green for < 5 ms
- dark red for < 50 ms
- bright red for > 50 ms (the maximum allowed is 200).
How the code works
The code in this script starts by saving the value of the timenow variable on the first bar. While the time variable returns the time at the beginning of the bar, timenow returns the current time. The code then follows the progression of timenow during the script’s execution. The variable only updates every second, so in between updates the script makes an estimate of the total time elapsed by adding the last average time per bar calculated to each bar that passes until timenow increases by another 1000 because one more second has elapsed since its last update. At that point a new, current average time per bar is calculated and the cycle repeats.
The code only calculates elapsed time for the initial run. Once the realtime bar is hit, timing stops so that time spent in the realtime bar does not affect the numbers once they have been calculated on the script’s initial pass over the dataset.
Notes
• If results show zero elapsed time, it’s most probably because your script executes in less than one second, which is very good. In that case timenow hasn’t changed, so no timing can be calculated.
• The code is quirky and doesn’t work on all scripts.
• It doesn’t properly time execution of security() calls.
• The average time per bar will sometimes vary quite a bit with changes in chart resolution.
Look first. Then leap.
Backtesting on Non-Standard Charts: Caution! - PineCoders FAQMuch confusion exists in the TradingView community about backtesting on non-standard charts. This script tries to shed some light on the subject in the hope that traders make better use of those chart types.
Non-standard charts are:
Heikin Ashi (HA)
Renko
Kagi
Point & Figure
Range
These chart types are called non-standard because they all transform market prices into synthetic views of price action. Some focus on price movement and disregard time. Others like HA use the same division of bars into fixed time intervals but calculate artificial open, high, low and close (OHLC) values.
Non-standard chart types can provide traders with alternative ways of interpreting price action, but they are not designed to test strategies or run automated traded systems where results depend on the ability to enter and exit trades at precise price levels at specific times, whether orders are issued manually or algorithmically. Ironically, the same characteristics that make non-standard chart types interesting from an analytical point of view also make them ill-suited to trade execution. Why? Because of the dislocation that a synthetic view of price action creates between its non-standard chart prices and real market prices at any given point in time. Switching from a non-standard chart price point into the market always entails a translation of time/price dimensions that results in uncertainty—and uncertainty concerning the level or the time at which orders are executed is detrimental to all strategies.
The delta between the chart’s price when an order is issued (which is assumed to be the expected price) and the price at which that order is filled is called slippage . When working from normal chart types, slippage can be caused by one or more of the following conditions:
• Time delay between order submission and execution. During this delay the market may move normally or be subject to large orders from other traders that will cause large moves of the bid/ask levels.
• Lack of bids for a market sell or lack of asks for a market buy at the current price level.
• Spread taken by middlemen in the order execution process.
• Any other event that changes the expected fill price.
When a market order is submitted, matching engines attempt to fill at the best possible price at the exchange. TradingView strategies usually fill market orders at the opening price of the next candle. A non-standard chart type can produce misleading results because the open of the next candle may or may not correspond to the real market price at that time. This creates artificial and often beneficial slippage that would not exist on standard charts.
Consider an HA chart. The open for each candle is the average of the previous HA bar’s open and close prices. The open of the HA candle is a synthetic value, but the real market open at the time the new HA candle begins on the chart is the unrelated, regular open at the chart interval. The HA open will often be lower on long entries and higher on short entries, resulting in unrealistically advantageous fills.
Another example is a Renko chart. A Renko chart is a type of chart that only measures price movement. The purpose of a Renko chart is to cluster price action into regular intervals, which consequently removes the time element. Because Trading View does not provide tick data as a price source, it relies on chart interval close values to construct Renko bricks. As a consequence, a new brick is constructed only when the interval close penetrates one or more brick thresholds. When a new brick starts on the chart, it is because the previous interval’s close was above or below the next brick threshold. The open price of the next brick will likely not represent the current price at the time this new brick begins, so correctly simulating an order is impossible.
Some traders have argued with us that backtesting and trading off HA charts and other non-standard charts is useful, and so we have written this script to show traders what happens when order fills from backtesting on non-standard charts are compared to real-world fills at market prices.
Let’s review how TV backtesting works. TV backtesting uses a broker emulator to execute orders. When an order is executed by the broker emulator on historical bars, the price used for the fill is either the close of the order’s submission bar or, more often, the open of the next. The broker emulator only has access to the chart’s prices, and so it uses those prices to fill orders. When backtesting is run on a non-standard chart type, orders are filled at non-standard prices, and so backtesting results are non-standard—i.e., as unrealistic as the prices appearing on non-standard charts. This is not a bug; where else is the broker emulator going to fetch prices than from the chart?
This script is a strategy that you can run on either standard or non-standard chart types. It is meant to help traders understand the differences between backtests run on both types of charts. For every backtest, a label at the end of the chart shows two global net profit results for the strategy:
• The net profits (in currency) calculated by TV backtesting with orders filled at the chart’s prices.
• The net profits (in currency) calculated from the same orders, but filled at market prices (fetched through security() calls from the underlying real market prices) instead of the chart’s prices.
If you run the script on a non-standard chart, the top result in the label will be the result you would normally get from the TV backtesting results window. The bottom result will show you a more realistic result because it is calculated from real market fills.
If you run the script on a normal chart type (bars, candles, hollow candles, line, area or baseline) you will see the same result for both net profit numbers since both are run on the same real market prices. You will sometimes see slight discrepancies due to occasional differences between chart prices and the corresponding information fetched through security() calls.
Features
• Results shown in the Data Window (third icon from the top right of your chart) are:
— Cumulative results
— For each order execution bar on the chart, the chart and market previous and current fills, and the trade results calculated from both chart and market fills.
• You can choose between 2 different strategies, both elementary.
• You can use HA prices for the calculations determining entry/exit conditions. You can use this to see how a strategy calculated from HA values can run on a normal chart. You will notice that such strategies will not produce the same results as the real market results generated from HA charts. This is due to the different environment backtesting is running on where for example, position sizes for entries on the same bar will be calculated differently because HA and standard chart close prices differ.
• You can choose repainting/non-repainting signals.
• You can show MAs, entry/exit markers and market fill levels.
• You can show candles built from the underlying market prices.
• You can color the background for occurrences where an order is filled at a different real market price than the chart’s price.
Notes
• On some non-standard chart types you will not obtain any results. This is sometimes due to how certain types of non-standard types work, and sometimes because the script will not emit orders if no underlying market information is detected.
• The script illustrates how those who want to use HA values to calculate conditions can do so from a standard chart. They will then be getting orders emitted on HA conditions but filled at more realistic prices because their strategy can run on a standard chart.
• On some non-standard chart types you will see market results surpass chart results. While this may seem interesting, our way of looking at it is that it points to how unreliable non-standard chart backtesting is, and why it should be avoided.
• In order not to extend an already long description, we do not discuss the particulars of executing orders on the realtime bar when using non-standard charts. Unless you understand the minute details of what’s going on in the realtime bar on a particular non-standard chart type, we recommend staying away from this.
• Some traders ask us: Why does TradingView allow backtesting on non-standard chart types if it produces unrealistic results? That’s somewhat like asking a hammer manufacturer why it makes hammers if hammers can hurt you. We believe it’s a trader’s responsibility to understand the tools he is using.
Takeaways
• Non-standard charts are not bad per se, but they can be badly used.
• TV backtesting on non-standard charts is not broken and doesn’t require fixing. Traders asking for a fix are in dire need of learning more about trading. We recommend they stop trading until they understand why.
• Stay away from—even better, report—any vendor presenting you with strategies running on non-standard charts and implying they are showing reliable results.
• If you don’t understand everything we discussed, don’t use non-standard charts at all.
• Study carefully how non-standard charts are built and the inevitable compromises used in calculating them so you can understand their limitations.
Thanks to @allanster and @mortdiggiddy for their help in editing this description.
Look first. Then leap.
How to avoid repainting when NOT using security()Even when your code does not use security() calls, repainting dynamics still come into play in the realtime bar. Script coders and users must understand them and, if they choose to avoid repainting, need to know how to do so. This script demonstrates three methods to avoid repainting when NOT using the security() function.
Note that repainting dynamics when not using security() usually only come into play in the realtime bar, as historical data is fixed and thus cannot cause repainting, except in situations related to stock splits or dividend adjustments.
For those who don’t want to read
Configure your alerts to trigger “Once Per Bar Close” and you’re done.
For those who want to understand
Put this indicator on a 1 minute or seconds chart with a live symbol. As price changes you will see four of this script’s MAs (all except the two orange ones) move in the realtime bar. You are seeing repainting in action. When the current realtime bar closes and becomes a historical bar, the lines on the historical bars will no longer move, as the bar’s OHLC values are fixed. Note that you may need to refresh your chart to see the correct historical OHLC values, as exchange feeds sometimes produce very slight variations between the end values of the realtime bar and those of the same bar once it becomes a historical bar.
Some traders do not use signals generated by a script but simply want to avoid seeing the lines plotted by their scripts move during the realtime bar. They are concerned with repainting of the lines .
Other traders use their scripts to evaluate conditions, which they use to either plot markers on the chart, trigger alerts, or both. They may not care about the script’s plotted lines repainting, but do not want their markers to appear/disappear on the chart, nor their alerts to trigger for a condition that becomes true during the realtime bar but is no longer true once it closes. Those traders are more concerned with repainting of signals .
For each of the three methods shown in this script’s code, comments explain if its lines, markers and alerts will repaint or not. Through the Settings/Inputs you will be able to control plotting of lines and markers corresponding to each method, as well as experiment with the option, for method 2, of disabling only the lines plotting in the realtime bar while still allowing the markers and alerts to be generated.
An unavoidable fact is that non-repainting lines, markers or alerts are always late compared to repainting ones. The good news is that how late they are will in many cases be insignificant, so that the added reliability of the information they provide will largely offset the disadvantages of waiting.
Method 1 illustrates the usual way of going about things in a script. Its gray lines and markers will always repaint but repainting of the alerts the marker conditions generate can be avoided by configuring alerts to trigger “Once Per Bar Close”. Because this gray marker repaints, you will occasionally see it appear/disappear during the realtime bar when the gray MAs cross/un-cross.
Method 2 plots the same MAs as method 1, but in green. The difference is that it delays its marker condition by one bar to ensure it does not repaint. Its lines will normally repaint but its markers will not, as they pop up after the condition has been confirmed on the bar preceding the realtime bar. Its markers appear at the beginning of the realtime bar and will never disappear. When using this method alerts can be configured to trigger “Once Per Bar” so they fire the moment the marker appears on the chart at the beginning of the realtime bar. Note that the delay incurred between methods 1 and 2 is merely the instant between the close of a realtime bar and the beginning of the next one—a delay measured in milliseconds. Method 2 also allows its lines to be hidden in the realtime bar with the corresponding option in the script’s Settings/Inputs . This will be useful to those wishing to eliminate unreliable lines from the realtime bar. Commented lines in method 2 provide for a 2b option, which is to delay the calculation of the MAs rather than the cross condition. It has the obvious inconvenient of plotting delayed MAs, but may come in handy in some situations.
Method 3 is not the best solution when using MAs because it uses the open of bars rather than their close to calculate the MAs. While this provides a way of avoiding repainting, it is not ideal in the case of MA calcs but may come in handy in other cases. The orange lines and markers of method 3 will not repaint because the value of open cannot change in the realtime bar. Because its markers do not repaint, alerts may be configured using “Once Per Bar”.
Spend some time playing with the different options and looking at how this indicator’s lines plot and behave when you refresh you chart. We hope everything you need to understand and prevent repainting when not using security() is there.
Look first. Then leap.
How to avoid repainting when using security() - PineCoders FAQNOTE
The non-repainting technique in this publication that relies on bar states is now deprecated, as we have identified inconsistencies that undermine its credibility as a universal solution. The outputs that use the technique are still available for reference in this publication. However, we do not endorse its usage. See this publication for more information about the current best practices for requesting HTF data and why they work.
This indicator shows how to avoid repainting when using the security() function to retrieve information from higher timeframes.
What do we mean by repainting?
Repainting is used to describe three different things, in what we’ve seen in TV members comments on indicators:
1. An indicator showing results that change during the realtime bar, whether the script is using the security() function or not, e.g., a Buy signal that goes on and then off, or a plot that changes values.
2. An indicator that uses future data not yet available on historical bars.
3. An indicator that uses a negative offset= parameter when plotting in order to plot information on past bars.
The repainting types we will be discussing here are the first two types, as the third one is intentional—sometimes even intentionally misleading when unscrupulous script writers want their strategy to look better than it is.
Let’s be clear about one thing: repainting is not caused by a bug ; it is caused by the different context between historical bars and the realtime bar, and script coders or users not taking the necessary precautions to prevent it.
Why should repainting be avoided?
Repainting matters because it affects the behavior of Pine scripts in the realtime bar, where the action happens and counts, because that is when traders (or our systems) take decisions where odds must be in our favor.
Repainting also matters because if you test a strategy on historical bars using only OHLC values, and then run that same code on the realtime bar with more than OHLC information, scripts not properly written or misconfigured alerts will alter the strategy’s behavior. At that point, you will not be running the same strategy you tested, and this invalidates your test results , which were run while not having the additional price information that is available in the realtime bar.
The realtime bar on your charts is only one bar, but it is a very important bar. Coding proper strategies and indicators on TV requires that you understand the variations in script behavior and how information available to the script varies between when the script is running on historical and realtime bars.
How does repainting occur?
Repainting happens because of something all traders instinctively crave: more information. Contrary to trader lure, more information is not always better. In the realtime bar, all TV indicators (a.k.a. studies ) execute every time price changes (i.e. every tick ). TV strategies will also behave the same way if they use the calc_on_every_tick = true parameter in their strategy() declaration statement (the parameter’s default value is false ). Pine coders must decide if they want their code to use the realtime price information as it comes in, or wait for the realtime bar to close before using the same OHLC values for that bar that would be used on historical bars.
Strategy modelers often assume that using realtime price information as it comes in the realtime bar will always improve their results. This is incorrect. More information does not necessarily improve performance because it almost always entails more noise. The extra information may or may not improve results; one cannot know until the code is run in realtime for enough time to provide data that can be analyzed and from which somewhat reliable conclusions can be derived. In any case, as was stated before, it is critical to understand that if your strategy is taking decisions on realtime tick data, you are NOT running the same strategy you tested on historical bars with OHLC values only.
How do we avoid repainting?
It comes down to using reliable information and properly configuring alerts, if you use them. Here are the main considerations:
1. If your code is using security() calls, use the syntax we propose to obtain reliable data from higher timeframes.
2. If your script is a strategy, do not use the calc_on_every_tick = true parameter unless your strategy uses previous bar information to calculate.
3. If your script is a study and is using current timeframe information that is compared to values obtained from a higher timeframe, even if you can rely on reliable higher timeframe information because you are correctly using the security() function, you still need to ensure the realtime bar’s information you use (a cross of current close over a higher timeframe MA, for example) is consistent with your backtest methodology, i.e. that your script calculates on the close of the realtime bar. If your system is using alerts, the simplest solution is to configure alerts to trigger Once Per Bar Close . If you are not using alerts, the best solution is to use information from the preceding bar. When using previous bar information, alerts can be configured to trigger Once Per Bar safely.
What does this indicator do?
It shows results for 9 different ways of using the security() function and illustrates the simplest and most effective way to avoid repainting, i.e. using security() as in the example above. To show the indicator’s lines the most clearly, price on the chart is shown with a black line rather than candlesticks. This indicator also shows how misusing security() produces repainting. All combinations of using a 0 or 1 offset to reference the series used in the security() , as well as all combinations of values for the gaps= and lookahead= parameters are shown.
The close in the call labeled “BEST” means that once security has reached the upper timeframe (1 day in our case), it will fetch the previous day’s value.
The gaps= parameter is not specified as it is off by default and that is what we need. This ensures that the value returned by security() will not contain na values on any of our chart’s bars.
The lookahead security() to use the last available value for the higher timeframe bar we are using (the previous day, in our case). This ensures that security() will return the value at the end of the higher timeframe, even if it has not occurred yet. In our case, this has no negative impact since we are requesting the previous day’s value, with has already closed.
The indicator’s Settings/Inputs allow you to set:
- The higher timeframe security() calls will use
- The source security() calls will use
- If you want identifying labels printed on the lines that have no gaps (the lines containing gaps are plotted using very thick lines that appear as horizontal blocks of one bar in length)
For the lines to be plotted, you need to be on a smaller timeframe than the one used for the security() calls.
Comments in the code explain what’s going on.
Look first. Then leap.
Print Trade Number - PineCoders FAQThis script prints a trade number <1000 on the chart. It requires at least 3 bars between successive entries.
Look first. Then leap.
Averages - PineCoders FAQ█ WARNING
The publication of our ConditionalAverages library has deprecated this publication.
█ ORIGINAL DESCRIPTION
The need to calculate averages (arithmetic mean) comes up here and there in scripts. When you want the average of a value only when a given condition has occurred, you will often not be able to use the standard sma function in Pine because it will average all values in the series. Even if you take care to use your condition to set non-conforming values to zero, this ends up skewing your results with zero values.
This script calculates:
1. The running average of all up volumes,
2. The average of last x occurrences of up volume ,
3. The average up volume occurrences in last y bars.
Look first. Then leap.