Ticker Tape█ OVERVIEW
This indicator creates a dynamic, scrolling display of multiple securities' latest prices and daily changes, similar to the ticker tapes on financial news channels and the Ticker Tape Widget . It shows realtime market information for a user-specified list of symbols along the bottom of the main chart pane.
█ CONCEPTS
Ticker tape
Traditionally, a ticker tape was a continuous, narrow strip of paper that displayed stock prices, trade volumes, and other financial and security information. Invented by Edward A. Calahan in 1867, ticker tapes were the earliest method for electronically transmitting live stock market data.
A machine known as a "stock ticker" received stock information via telegraph, printing abbreviated company names, transaction prices, and other information in a linear sequence on the paper as new data came in. The term "ticker" in the name comes from the "tick" sound the machine made as it printed stock information. The printed tape provided a running record of trading activity, allowing market participants to stay informed on recent market conditions without needing to be on the exchange floor.
In modern times, electronic displays have replaced physical ticker tapes. However, the term "ticker" remains persistent in today's financial lexicon. Nowadays, ticker symbols and digital tickers appear on financial news networks, trading platforms, and brokerage/exchange websites, offering live updates on market information. Modern electronic displays, thankfully, do not rely on telegraph updates to operate.
█ FEATURES
Requesting a list of securities
The "Symbol list" text box in the indicator's "Settings/Inputs" tab allows users to list up to 40 symbols or ticker Identifiers. The indicator dynamically requests and displays information for each one. To add symbols to the list, enter their names separated by commas . For example: "BITSTAMP:BTCUSD, TSLA, MSFT".
Each item in the comma-separated list must represent a valid symbol or ticker ID. If the list includes an invalid symbol, the script will raise a runtime error.
To specify a broker/exchange for a symbol, include its name as a prefix with a colon in the "EXCHANGE:SYMBOL" format. If a symbol in the list does not specify an exchange prefix, the indicator selects the most commonly used exchange when requesting the data.
Realtime updates
This indicator requests symbol descriptions, current market prices, daily price changes, and daily change percentages for each ticker from the user-specified list of symbols or ticker identifiers. It receives updated information for each security after new realtime ticks on the current chart.
After a new realtime price update, the indicator updates the values shown in the tape display and their colors.
The color of the percentages in the tape depends on the change in price from the previous day . The text is green when the daily change is positive, red when the value is negative, and gray when the value is 0.
The color of each displayed price depends on the change in value from the last recorded update, not the change over a daily period. For example, if a security's price increases in the latest update, the ticker tape shows that price with green text, even if the current price is below the previous day's closing price. This behavior allows users to monitor realtime directional changes in the requested securities.
NOTE: Pine scripts execute on realtime bars when new ticks are available in the chart's data feed. If no new updates are available from the chart's realtime feed, it may cause a delay in the data the indicator receives.
Ticker motion
This indicator's tape display shows a list of security information that incrementally scrolls horizontally from right to left after new chart updates, providing a dynamic visual stream of current market data. The scrolling effect works by using a counter that increments across successive intervals after realtime ticks to control the offset of each listed security. Users can set the initial scroll offset with the "Offset" input in the "Settings/Inputs" tab.
The scrolling rate of the ticker tape display depends on the realtime ticks available from the chart's data feed. Using the indicator on a chart with frequent realtime updates results in smoother scrolling. If no new realtime ticks are available in the chart's feed, the ticker tape does not move. Users can also deactivate the scrolling feature by toggling the "Running" input in the indicator's settings.
█ FOR Pine Script™ CODERS
• This script utilizes dynamic requests to iteratively fetch information from multiple contexts using a single request.security() instance in the code. Previously, `request.*()` functions were not allowed within the local scopes of loops or conditional structures, and most `request.*()` function parameters, excluding `expression`, required arguments of a simple or weaker qualified type. The new `dynamic_requests` parameter in script declaration statements enables more flexibility in how scripts can use `request.*()` calls. When its value is `true`, all `request.*()` functions can accept series arguments for the parameters that define their requested contexts, and `request.*()` functions can execute within local scopes. See the Dynamic requests section of the Pine Script™ User Manual to learn more.
• Scripts can execute up to 40 unique `request.*()` function calls. A `request.*()` call is unique only if the script does not already call the same function with the same arguments. See this section of the User Manual's Limitations page for more information.
• This script converts a comma-separated "string" list of symbols or ticker IDs into an array . It then loops through this array, dynamically requesting data from each symbol's context and storing the results within a collection of custom `Tape` objects . Each `Tape` instance holds information about a symbol, which the script uses to populate the table that displays the ticker tape.
• This script uses the varip keyword to declare variables and `Tape` fields that update across ticks on unconfirmed bars without rolling back. This behavior allows the script to color the tape's text based on the latest price movements and change the locations of the table cells after realtime updates without reverting. See the `varip` section of the User Manual to learn more about using this keyword.
• Typically, when requesting higher-timeframe data with request.security() using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should use the history-referencing operator to offset the series, preventing lookahead bias on historical bars. However, the request.security() call in this script uses barmerge.lookahead_on without offsetting the `expression` because the script only displays results for the latest historical bar and all realtime bars, where there is no future information to leak into the past. Instead, using this call on those bars ensures each request fetches the most recent data available from each context.
• The request.security() instance in this script includes a `calc_bars_count` argument to specify that each request retrieves only a minimal number of bars from the end of each symbol's historical data feed. The script does not need to request all the historical data for each symbol because it only shows results on the last chart bar that do not depend on the entire time series. In this case, reducing the retrieved bars in each request helps minimize resource usage without impacting the calculated results.
Look first. Then leap.
Security
TimeframeComparisonLibrary "TimeframeComparison"
Timeframe comparison for higher and lower timeframe
█ OVERVIEW
This library is used to compare higher / lower timeframe by using timeframe.multiplier.
minMult()
timeframe multiplier in minutes
Returns: float value
Hikkake Hunter 2.0This script serves as a successor to a previous script I wrote for identifying Hikkakes nearly two years ago.
The old version has been preserved here:
█ OVERVIEW
This script is a rework of an old script that identified the Hikkake candlestick pattern. While this pattern is not usually considered a part of the standard candlestick patterns set, I found a lot of value when finding a solution to identifying it. A Hikkake pattern is a 3-candle pattern where a middle candle is nested in between the range of the prior candle, and a candle that follows has a higher high and a higher low (bearish setup) or a lower high and a lower low (bullish setup). What makes this pattern unique is the "confirmation" status of the pattern; within 3 candles of this pattern's appearance, there must be a candle that closes above the high (bullish setup) or below the low (bearish setup) of the second candle. Additional flexibility has been added which allows the user to specify the number of candles (up to 5) that the pattern may have to confirm after its appearance.
█ CONCEPTS
This script will cover concepts mainly focusing on candlestick analysis, price analysis (with higher timeframes), and statistical analysis. I believe there is also educational value presented with the use of user-defined-types (UDTs) in accomplishing these concepts that I hope others will find useful.
Candlestick Analysis - Identification and confirmation of the patterns in the deprecated script were clunky and inefficient. While the previous script required the use of 6 candles to perform the confirmations of patterns (restricted solely to identifying patterns that confirmed in 3 candles or less), this script only requires 3 candles to identify and process patterns by utilizing a UDT representing a 'pattern object'. An object representing a pattern will be created when it has been identified, and fields within that object will be set for processing by the functions it is passed to. Pattern objects are held by a var array (values within the array persist between bars) and will be removed from this array once they have been confirmed or non-confirmed.
This is a significant deviation from the previous script's methods, as it prevents unnecessary re-evaluations of the confirmation status of patterns (i.e. Hikkakes confirmed on the first candle will no longer need to be checked for confirmations on the second or third; a pitfall of the deprecated version which required multiple booleans tracking prior confirmation statuses). This deviation is also what provides the flexibility in changing the number of candles that can pass before a pattern is deemed non-confirmed.
As multiple patterns can be confirmed simultaneously, this script uses another UDT representing a linked-list reduction of the pattern object used to process it. This liked-list object will then be used for Price Analysis.
Price Analysis - This script employs the use of a UDT which contains all the returns of confirmed patterns. The user specifies how many candles ahead of the confirmed pattern to calculate its return, as well as where this calculation begins. There are two settings: FROM APPEARANCE and FROM CONFIRMATION (default). Price differences are calculated from the open of the candle immediately following the candle which had confirmed the pattern to the close of the candle X candles ahead (default 10). ( SEE FEATURES )
Because of how Pine functions, this calculation necessitates a lookback on prior candles to identify when a pattern had been confirmed. This is accomplished with the following pseudo-code:
if not na(confirmed linked-list )
for all confirmed in list
GET MATRIX PLACEMENT
offset = FROM CONFIRMATION ? 0 : # of candles to confirm
openAtFind = open
percent return = ((close - openAtFind) / openAtFind) * 100
ADD percent return TO UDT IN MATRIX
All return UDTs are held in a matrix which breaks up these patterns into specific groups covered in the next section.
Higher Timeframes - This script makes a request.security call to a higher timeframe in order to identify a price range which breaks up these patterns into groups based on the 'partition' they had appeared in. The default values for this partitioning will break up the chart into three sections: upper, middle, and lower. The upper section represents the highest 20% of the yearly trading range that an asset has experienced. The lower section represents the trading range within a third (33%) of the yearly low. And the middle section represents the yearly high-low range between these two partitions.
The matrix containing all return UDTs will have these returns split up based on the number of candles required to confirm the pattern as well as the partition the pattern had appeared in. The underlying rationale is that patterns may perform better or worse at different parts of an asset's trading range.
Statistical Analysis - Once a pattern has been confirmed, the matrix containing all return UDTs will be queried to check if a 'returnArray' object has been created for that specific pattern. If not, one will be initialized and a confirmed linked-list object will be created that contains information pertinent to the matrix position of this object.
This matrix contains the returns of both the Bullish and Bearish Hikkake patterns, separated by the number of candles needed to confirm them, and by the partitions they had appeared in. For the standard 3 candles to confirm, this means the matrix will contain 18 elements (dependent on the number of candles allowed for confirmations; its size will range from 12 to 30).
When the required number of candles for Price Analysis passes, a percent return is calculated and added to the returnArray contained in the matrix at the location derived from the confirmed linked-list object's values. The return is added, and all values in the returnArray are updated using Pine's built in array.___ functions. This returnArray object contains the array of all returns, its size, its average, the median, the standard deviation of returns, and a separate 3-integer array which holds values that correspond to the types of returns experienced by this pattern (negative, neutral, and positive)*.
After a pattern has been confirmed, this script will place the partition and all of the aforementioned stats values (plus a 95% confidence interval of expected returns) related to that pattern onto the tooltip of the label that identifies it. This allows users to scroll over the label of a confirmed pattern to gauge its prior performance under specific conditions. The percent return of the specific pattern identified will later be placed onto the label tooltip as well. ( SEE LIMITATIONS )
The stats portion of this script also plays a significant role in how patterns are presented when using the Adaptive Coloring mode described in FEATURES .
*These values are incremented based on user-input related to what constitutes a 'negative' or 'positive' return. Default values would place any return by a pattern between -3% and 3% in the 'neutral' category, and values exceeding either end will be placed in the 'negative' or 'positive' categories.
█ FEATURES
This script contains numerous inputs for modifying its behavior and how patterns are presented/processed, separated into 5 groups.
Confirmation Setting - The most important input for this script's functioning. This input is a 'confirm=true' input and must be set by the user before the script is applied to the chart. It sets the number of candles that a pattern has to confirm once it has been identified.
Alert Settings - This group of booleans sets which types of alerts will fire during the scripts execution on the chart. If enabled, the four alerts will trigger when: a pattern has been identified, a pattern has been confirmed, a pattern has been non-confirmed, and show the return for that confirmed pattern in an alert. Because this script uses the 'alert' function and not 'alertcondition', these must be enabled before 'any alert() function call' is set in TradingView's 'alerts' settings.
Partition Settings - This group of inputs are responsible for creating (and viewing) the partitions that breaks the returns of the patterns identified up into their respective groups. The user may set the resolution to grab the range from, the length back of this resolution the partitions get their values from, the thresholds which breaks the partitions up into their groups, and modify the visibility (if they're shown, the colors, opacity) of these partitions.
Stats Settings - These inputs will drastically alter how patterns are presented and the resulting information derived from them after their appearance. Because of this section's importance, some of these inputs will be described in more detail.
P/L Sample Length - Defines the number of candles after the starting point to grab values from in the % return calculation for that pattern.
P/L Starting Point - Defines the starting point where the P/L calculation will take place. 'FROM APPEARANCE' will set the starting point at the candle immediately following the pattern's appearance. 'FROM CONFIRMATION' will place the starting point immediately following the candle which had confirmed the pattern. ( SEE LIMITATIONS )
Min Returns Needed - Sets how many times a specific pattern must appear (both by number of candles needed to confirm and by partition) before the statistics for that pattern are displayed onto the tooltip (and for gradient coloration in Adaptive Coloring mode).
Enable Adaptive Coloring - Changes the coloration of the patterns based on the bullish/bearishness of the specified Gradient Reference value of that pattern compared to the Return Tolerance values OR the minimum and maximum values of that specified Gradient Reference value contained in the matrix of all returns. This creates a color from a gradient using the user-specified colors and alters how many of the patterns may appear if prior performance is taken into account.
Gradient Reference - Defines which stats measure of returns will be used in the gradient color generation. The two settings are 'AVG' and 'MEDIAN'.
Hard Limit - This boolean sets whether the Return Tolerance values will not be replaced by values that exceed them from the matrix of returns in color gradient generation. This changes the scale of the gradient where any Gradient Reference values of patterns that exceed these tolerances will be colored the full bullish or bearish gradient colors, and anything in between them will be given a color from the gradient.
Visibility Settings - This last section includes all settings associated with the overall visibility of patterns found with this script. This includes the position of the labels and their colors (+ pattern colors without Adaptive Coloring being enabled), and showing patterns that were non-confirmed.
Most of these inputs in the script have these kinds of descriptions to what they do provided by their tooltips.
█ HOW TO USE
I attempted to make this script much easier to use in terms of analyzing the patterns and displaying the information to the user. The previous script would have the user go to the 'data window' side bar on TradingView to view the returns of a pattern after they had specified which pattern to analyze through the settings, needlessly convoluted. This aim at simplicity was achieved through the use of UDTs and specific code-design.
To use, simply apply the indicator to a chart, set the number of candles (between 2 and 5) for confirming this specific pattern and adjust the many settings described above at your leisure.
█ LIMITATIONS
Disclaimer - This is a tool created with the hopes of helping identify a specific pattern and provide an informative view about the performance of that pattern. Previous performance is not indicative of future results. None of this constitutes any form of financial advice, *use at your own risk*.
Statistical Analysis - This script assumes that all patterns will yield a NORMAL DISTRIBUTION regarding their returns which may not be reflective of reality. I personally have limited experience within the field of statistics apart from a few high school/college courses and make no guarantees that the calculation of the 95% confidence interval is correct. Please review the source code to verify for yourself that this interval calculation is correct (Function Name: f_DisplayStatsOnLabel).
P/L Starting Point - Because of when the object related to the confirmation status of a pattern is created (specifically the linked-list object) setting the 'P/L Starting Point' to 'FROM APPEARANCE' will yield the results of that P/L calculation at the same time as 'FROM CONFIRMATION'.
█ EXAMPLES
Default Settings:
Partition Background (default):
Partition Background (Resolution D : Length 30):
Adaptive Coloration:
Show Non-Confirmed:
OWRS VolatilililityBit of a fun indicator taking into the asset names and natural processes and also the fact that the crypto markets are (definitely) not run by weird occultists and naturalists. Looks for disturbances in price of these four key assets. Read into it what you will. Sometimes the clues are just in the names.
Things you will learn from this script:
1. Using security function to compare multiple assets in one indicator.
2. Using indexing to reference historic data.
3. Setting chart outputs such as color based on interrogation of a boolean.
4. To only go back 3-4 iterations of any repeatable sequence as chaos kicks in after 3.55 (Feigenbaum)
1. By extension only the last 3 or 4 candles are of any use in indicator creation.
2. I am almost definitely a pagan.
3. You were expecting this numbered list to go 1,2,3,4,5,6,7. na mate. Chaos.
Kagi Implementation (+ATR)My Own Kagi Indicator Implementation!
I couldn't find anywhere on the internet a simple implementation of the Kagi indicator (apart from a seemingly complicated JavaScript implementation).
So I decided to implement it myself and test it against the built-in Kagi indicator calculated by the built-in security function - They ended up exactly the same! (You can see my orange plot completely covers the security's purple plot)
My calculations are based on this article from a site called "euroland", the article is called "Kagi Chart" (I can't post the link because of TradingView restrictions)
Bonus: The built-in kagi indicator uses only Fixed Amount Reversal Size. One that is interested in an ATR Reversal Size can modify the calculation a bit (see script's comments) to easily create and use it.
Some interesting info about the security function I discovered while doing this script:
After I implemented it I noticed that my calculations are the same except the fact that all my values are delayed by 1 bar (relative to the security's indicator). After some research I discovered that the security function uses future data in it's calculation and therefore it cannot be trusted for testing live-trading strategies, unless it is given the appropriate parameters (see script for example).
Have fun trading and don't lose money!
Example - HTF Values Without 'Security()'This is an example of how to reference higher timeframe data without the
need for a 'security()' call.
I have attempted to create the function example:
f_insecurity()
with the purpose of wrapping up and pumping out all common relevent HTF
price data that's needed for your everyday indicators in a reliable fashion.
`security()` revisited [PineCoders]NOTE
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.
█ OVERVIEW
This script presents a new function to help coders use security() in both repainting and non-repainting modes. We revisit this often misunderstood and misused function, and explain its behavior in different contexts, in the hope of dispelling some of the coder lure surrounding it. The function is incredibly powerful, yet misused, it can become a dangerous WMD and an instrument of deception, for both coders and traders.
We will discuss:
• How to use our new `f_security()` function.
• The behavior of Pine code and security() on the three very different types of bars that make up any chart.
• Why what you see on a chart is a simulation, and should be taken with a grain of salt.
• Why we are presenting a new version of a function handling security() calls.
• Other topics of interest to coders using higher timeframe (HTF) data.
█ WARNING
We have tried to deliver a function that is simple to use and will, in non-repainting mode, produce reliable results for both experienced and novice coders. If you are a novice coder, stick to our recommendations to avoid getting into trouble, and DO NOT change our `f_security()` function when using it. Use `false` as the function's last argument and refrain from using your script at smaller timeframes than the chart's. To call our function to fetch a non-repainting value of close from the 1D timeframe, use:
f_security(_sym, _res, _src, _rep) => security(_sym, _res, _src )
previousDayClose = f_security(syminfo.tickerid, "D", close, false)
If that's all you're interested in, you are done.
If you choose to ignore our recommendation and use the function in repainting mode by changing the `false` in there for `true`, we sincerely hope you read the rest of our ramblings before you do so, to understand the consequences of your choice.
Let's now have a look at what security() is showing you. There is a lot to cover, so buckle up! But before we dig in, one last thing.
What is a chart?
A chart is a graphic representation of events that occur in markets. As any representation, it is not reality, but rather a model of reality. As Scott Page eloquently states in The Model Thinker : "All models are wrong; many are useful". Having in mind that both chart bars and plots on our charts are imperfect and incomplete renderings of what actually occurred in realtime markets puts us coders in a place from where we can better understand the nature of, and the causes underlying the inevitable compromises necessary to build the data series our code uses, and print chart bars.
Traders or coders complaining that charts do not reflect reality act like someone who would complain that the word "dog" is not a real dog. Let's recognize that we are dealing with models here, and try to understand them the best we can. Sure, models can be improved; TradingView is constantly improving the quality of the information displayed on charts, but charts nevertheless remain mere translations. Plots of data fetched through security() being modelized renderings of what occurs at higher timeframes, coders will build more useful and reliable tools for both themselves and traders if they endeavor to perfect their understanding of the abstractions they are working with. We hope this publication helps you in this pursuit.
█ FEATURES
This script's "Inputs" tab has four settings:
• Repaint : Determines whether the functions will use their repainting or non-repainting mode.
Note that the setting will not affect the behavior of the yellow plot, as it always repaints.
• Source : The source fetched by the security() calls.
• Timeframe : The timeframe used for the security() calls. If it is lower than the chart's timeframe, a warning appears.
• Show timeframe reminder : Displays a reminder of the timeframe after the last bar.
█ THE CHART
The chart shows two different pieces of information and we want to discuss other topics in this section, so we will be covering:
A — The type of chart bars we are looking at, indicated by the colored band at the top.
B — The plots resulting of calling security() with the close price in different ways.
C — Points of interest on the chart.
A — Chart bars
The colored band at the top shows the three types of bars that any chart on a live market will print. It is critical for coders to understand the important distinctions between each type of bar:
1 — Gray : Historical bars, which are bars that were already closed when the script was run on them.
2 — Red : Elapsed realtime bars, i.e., realtime bars that have run their course and closed.
The state of script calculations showing on those bars is that of the last time they were made, when the realtime bar closed.
3 — Green : The realtime bar. Only the rightmost bar on the chart can be the realtime bar at any given time, and only when the chart's market is active.
Refer to the Pine User Manual's Execution model page for a more detailed explanation of these types of bars.
B — Plots
The chart shows the result of letting our 5sec chart run for a few minutes with the following settings: "Repaint" = "On" (the default is "Off"), "Source" = `close` and "Timeframe" = 1min. The five lines plotted are the following. They have progressively thinner widths:
1 — Yellow : A normal, repainting security() call.
2 — Silver : Our recommended security() function.
3 — Fuchsia : Our recommended way of achieving the same result as our security() function, for cases when the source used is a function returning a tuple.
4 — White : The method we previously recommended in our MTF Selection Framework , which uses two distinct security() calls.
5 — Black : A lame attempt at fooling traders that MUST be avoided.
All lines except the first one in yellow will vary depending on the "Repaint" setting in the script's inputs. The first plot does not change because, contrary to all other plots, it contains no conditional code to adapt to repainting/no-repainting modes; it is a simple security() call showing its default behavior.
C — Points of interest on the chart
Historical bars do not show actual repainting behavior
To appreciate what a repainting security() call will plot in realtime, one must look at the realtime bar and at elapsed realtime bars, the bars where the top line is green or red on the chart at the top of this page. There you can see how the plots go up and down, following the close value of each successive chart bar making up a single bar of the higher timeframe. You would see the same behavior in "Replay" mode. In the realtime bar, the movement of repainting plots will vary with the source you are fetching: open will not move after a new timeframe opens, low and high will change when a new low or high are found, close will follow the last feed update. If you are fetching a value calculated by a function, it may also change on each update.
Now notice how different the plots are on historical bars. There, the plot shows the close of the previously completed timeframe for the whole duration of the current timeframe, until on its last bar the price updates to the current timeframe's close when it is confirmed (if the timeframe's last bar is missing, the plot will only update on the next timeframe's first bar). That last bar is the only one showing where the plot would end if that timeframe's bars had elapsed in realtime. If one doesn't understand this, one cannot properly visualize how his script will calculate in realtime when using repainting. Additionally, as published scripts typically show charts where the script has only run on historical bars, they are, in fact, misleading traders who will naturally assume the script will behave the same way on realtime bars.
Non-repainting plots are more accurate on historical bars
Now consider this chart, where we are using the same settings as on the chart used to publish this script, except that we have turned "Repainting" off this time:
The yellow line here is our reference, repainting line, so although repainting is turned off, it is still repainting, as expected. Because repainting is now off, however, plots on historical bars show the previous timeframe's close until the first bar of a new timeframe, at which point the plot updates. This correctly reflects the behavior of the script in the realtime bar, where because we are offsetting the series by one, we are always showing the previously calculated—and thus confirmed—higher timeframe value. This means that in realtime, we will only get the previous timeframe's values one bar after the timeframe's last bar has elapsed, at the open of the first bar of a new timeframe. Historical and elapsed realtime bars will not actually show this nuance because they reflect the state of calculations made on their close , but we can see the plot update on that bar nonetheless.
► This more accurate representation on historical bars of what will happen in the realtime bar is one of the two key reasons why using non-repainting data is preferable.
The other is that in realtime, your script will be using more reliable data and behave more consistently.
Misleading plots
Valiant attempts by coders to show non-repainting, higher timeframe data updating earlier than on our chart are futile. If updates occur one bar earlier because coders use the repainting version of the function, then so be it, but they must then also accept that their historical bars are not displaying information that is as accurate. Not informing script users of this is to mislead them. Coders should also be aware that if they choose to use repainting data in realtime, they are sacrificing reliability to speed and may be running a strategy that behaves very differently from the one they backtested, thus invalidating their tests.
When, however, coders make what are supposed to be non-repainting plots plot artificially early on historical bars, as in examples "c4" and "c5" of our script, they would want us to believe they have achieved the miracle of time travel. Our understanding of the current state of science dictates that for now, this is impossible. Using such techniques in scripts is plainly misleading, and public scripts using them will be moderated. We are coding trading tools here—not video games. Elementary ethics prescribe that we should not mislead traders, even if it means not being able to show sexy plots. As the great Feynman said: You should not fool the layman when you're talking as a scientist.
You can readily appreciate the fantasy plot of "c4", the thinnest line in black, by comparing its supposedly non-repainting behavior between historical bars and realtime bars. After updating—by miracle—as early as the wide yellow line that is repainting, it suddenly moves in a more realistic place when the script is running in realtime, in synch with our non-repainting lines. The "c5" version does not plot on the chart, but it displays in the Data Window. It is even worse than "c4" in that it also updates magically early on historical bars, but goes on to evaluate like the repainting yellow line in realtime, except one bar late.
Data Window
The Data Window shows the values of the chart's plots, then the values of both the inside and outside offsets used in our calculations, so you can see them change bar by bar. Notice their differences between historical and elapsed realtime bars, and the realtime bar itself. If you do not know about the Data Window, have a look at this essential tool for Pine coders in the Pine User Manual's page on Debugging . The conditional expressions used to calculate the offsets may seem tortuous but their objective is quite simple. When repainting is on, we use this form, so with no offset on all bars:
security(ticker, i_timeframe, i_source )
// which is equivalent to:
security(ticker, i_timeframe, i_source)
When repainting is off, we use two different and inverted offsets on historical bars and the realtime bar:
// Historical bars:
security(ticker, i_timeframe, i_source )
// Realtime bar (and thus, elapsed realtime bars):
security(ticker, i_timeframe, i_source )
The offsets in the first line show how we prevent repainting on historical bars without the need for the `lookahead` parameter. We use the value of the function call on the chart's previous bar. Since values between the repainting and non-repainting versions only differ on the timeframe's last bar, we can use the previous value so that the update only occurs on the timeframe's first bar, as it will in realtime when not repainting.
In the realtime bar, we use the second call, where the offsets are inverted. This is because if we used the first call in realtime, we would be fetching the value of the repainting function on the previous bar, so the close of the last bar. What we want, instead, is the data from the previous, higher timeframe bar , which has elapsed and is confirmed, and thus will not change throughout realtime bars, except on the first constituent chart bar belonging to a new higher timeframe.
After the offsets, the Data Window shows values for the `barstate.*` variables we use in our calculations.
█ NOTES
Why are we revisiting security() ?
For four reasons:
1 — We were seeing coders misuse our `f_secureSecurity()` function presented in How to avoid repainting when using security() .
Some novice coders were modifying the offset used with the history-referencing operator in the function, making it zero instead of one,
which to our horror, caused look-ahead bias when used with `lookahead = barmerge.lookahead_on`.
We wanted to present a safer function which avoids introducing the dreaded "lookahead" in the scripts of unsuspecting coders.
2 — The popularity of security() in screener-type scripts where coders need to use the full 40 calls allowed per script made us want to propose
a solid method of allowing coders to offer a repainting/no-repainting choice to their script users with only one security() call.
3 — We wanted to explain why some alternatives we see circulating are inadequate and produce misleading behavior.
4 — Our previous publication on security() focused on how to avoid repainting, yet many other considerations worthy of attention are not related to repainting.
Handling tuples
When sending function calls that return tuples with security() , our `f_security()` function will not work because Pine does not allow us to use the history-referencing operator with tuple return values. The solution is to integrate the inside offset to your function's arguments, use it to offset the results the function is returning, and then add the outside offset in a reassignment of the tuple variables, after security() returns its values to the script, as we do in our "c2" example.
Does it repaint?
We're pretty sure Wilder was not asked very often if RSI repainted. Why? Because it wasn't in fashion—and largely unnecessary—to ask that sort of question in the 80's. Many traders back then used daily charts only, and indicator values were calculated at the day's close, so everybody knew what they were getting. Additionally, indicator values were calculated by generally reputable outfits or traders themselves, so data was pretty reliable. Today, almost anybody can write a simple indicator, and the programming languages used to write them are complex enough for some coders lacking the caution, know-how or ethics of the best professional coders, to get in over their heads and produce code that does not work the way they think it does.
As we hope to have clearly demonstrated, traders do have legitimate cause to ask if MTF scripts repaint or not when authors do not specify it in their script's description.
► We recommend that authors always use our `f_security()` with `false` as the last argument to avoid repainting when fetching data dependent on OHLCV information. This is the only way to obtain reliable HTF data. If you want to offer users a choice, make non-repainting mode the default, so that if users choose repainting, it will be their responsibility. Non-repainting security() calls are also the only way for scripts to show historical behavior that matches the script's realtime behavior, so you are not misleading traders. Additionally, non-repainting HTF data is the only way that non-repainting alerts can be configured on MTF scripts, as users of MTF scripts cannot prevent their alerts from repainting by simply configuring them to trigger on the bar's close.
Data feeds
A chart at one timeframe is made up of multiple feeds that mesh seamlessly to form one chart. Historical bars can use one feed, and the realtime bar another, which brokers/exchanges can sometimes update retroactively so that elapsed realtime bars will reappear with very slight modifications when the browser's tab is refreshed. Intraday and daily chart prices also very often originate from different feeds supplied by brokers/exchanges. That is why security() calls at higher timeframes may be using a completely different feed than the chart, and explains why the daily high value, for example, can vary between timeframes. Volume information can also vary considerably between intraday and daily feeds in markets like stocks, because more volume information becomes available at the end of day. It is thus expected behavior—and not a bug—to see data variations between timeframes.
Another point to keep in mind concerning feeds it that when you are using a repainting security() plot in realtime, you will sometimes see discrepancies between its plot and the realtime bars. An artefact revealing these inconsistencies can be seen when security() plots sometimes skip a realtime chart bar during periods of high market activity. This occurs because of races between the chart and the security() feeds, which are being monitored by independent, concurrent processes. A blue arrow on the chart indicates such an occurrence. This is another cause of repainting, where realtime bar-building logic can produce different outcomes on one closing price. It is also another argument supporting our recommendation to use non-repainting data.
Alternatives
There is an alternative to using security() in some conditions. If all you need are OHLC prices of a higher timeframe, you can use a technique like the one Duyck demonstrates in his security free MTF example - JD script. It has the great advantage of displaying actual repainting values on historical bars, which mimic the code's behavior in the realtime bar—or at least on elapsed realtime bars, contrary to a repainting security() plot. It has the disadvantage of using the current chart's TF data feed prices, whereas higher timeframe data feeds may contain different and more reliable prices when they are compiled at the end of the day. In its current state, it also does not allow for a repainting/no-repainting choice.
When `lookahead` is useful
When retrieving non-price data, or in special cases, for experiments, it can be useful to use `lookahead`. One example is our Backtesting on Non-Standard Charts: Caution! script where we are fetching prices of standard chart bars from non-standard charts.
Warning users
Normal use of security() dictates that it only be used at timeframes equal to or higher than the chart's. To prevent users from inadvertently using your script in contexts where it will not produce expected behavior, it is good practice to warn them when their chart is on a higher timeframe than the one in the script's "Timeframe" field. Our `f_tfReminderAndErrorCheck()` function in this script does that. It can also print a reminder of the higher timeframe. It uses one security() call.
Intrabar timeframes
security() is not supported by TradingView when used with timeframes lower than the chart's. While it is still possible to use security() at intrabar timeframes, it then behaves differently. If no care is taken to send a function specifically written to handle the successive intrabars, security() will return the value of the last intrabar in the chart's timeframe, so the last 1H bar in the current 1D bar, if called at "60" from a "D" chart timeframe. If you are an advanced coder, see our FAQ entry on the techniques involved in processing intrabar timeframes. Using intrabar timeframes comes with important limitations, which you must understand and explain to traders if you choose to make scripts using the technique available to others. Special care should also be taken to thoroughly test this type of script. Novice coders should refrain from getting involved in this.
█ TERMINOLOGY
Timeframe
Timeframe , interval and resolution are all being used to name the concept of timeframe. We have, in the past, used "timeframe" and "resolution" more or less interchangeably. Recently, members from the Pine and PineCoders team have decided to settle on "timeframe", so from hereon we will be sticking to that term.
Multi-timeframe (MTF)
Some coders use "multi-timeframe" or "MTF" to name what are in fact "multi-period" calculations, as when they use MAs of progressively longer periods. We consider that a misleading use of "multi-timeframe", which should be reserved for code using calculations actually made from another timeframe's context and using security() , safe for scripts like Duyck's one mentioned earlier, or TradingView's Relative Volume at Time , which use a user-selected timeframe as an anchor to reset calculations. Calculations made at the chart's timeframe by varying the period of MAs or other rolling window calculations should be called "multi-period", and "MTF-anchored" could be used for scripts that reset calculations on timeframe boundaries.
Colophon
Our script was written using the PineCoders Coding Conventions for Pine .
The description was formatted using the techniques explained in the How We Write and Format Script Descriptions PineCoders publication.
Snippets were lifted from our MTF Selection Framework , then massaged to create the `f_tfReminderAndErrorCheck()` function.
█ THANKS
Thanks to apozdnyakov for his help with the innards of security() .
Thanks to bmistiaen for proofreading our description.
Look first. Then leap.
New Alerts Allow for Dynamic Messageswww.tradingview.com
Following the last example from the link above, I added a function return to plot the calculated RSI value for each ticker.
For this, I added the expression of the rsi bult-in function in the security call, to send as a return to the plot function.
Ps. I purposely inverted the crossunder/crossover calls for testing here.
Supertrend Screener PanelScript to display Supertrend trend state of 8 different securities in a panel. Timeframe & Tickers which are to be displayed can be configured from settings.
Part of code is from the ADX DI Monitoring Panel script by u/wugamlo with his permission. Thanks to him for that and do please check out his work also.
A Deeper Look Into Security Function & Possible ImprovementsThere is a link below that further explain the purpose of this publication.
A fresh new look into the limitations of the security() function and perhaps expand our horizons on having access to more accurate data no matter from what timeframe you are on.
docs.google.com
As always, it is my desire to help the community to continue reaching new highs.
security free MTF example - JDThis script is not intended for trading purposes but gives some examples how you can get values
from previous candles in other timeframes, without using security calls.
NOTE: the "open", "high" and "low" values are calculated "on the fly", as the bar progresses,
the "close" is determined at the end of the timeframe, so it's only know at the first bar of the next time period
JD.
#NotTradingAdvice #DYOR
Disclaimer.
I AM NOT A FINANCIAL ADVISOR.
THESE IDEAS ARE NOT ADVICE AND ARE FOR EDUCATION PURPOSES ONLY.
ALWAYS DO YOUR OWN RESEARCH!
Any Security vs. Any Security Change Comparison [BigBitsIO]This script allows you to compare the percentage-based change in the price of any two securities on any given (and supported) timeframe on the chart. This can give you a very simple way to compare any two securities against one another.
Ex: If your base security gained 5%, and the other security gained 3% in a single day, the change comparison would show a green bar of 2% because your base security outgained your other security by 2%.
Features:
- 2 securities to compare. A base and other.
- Shortlist of default securities to choose from.
- Ability to override the default securities list and use any security supported by TradingView. You must use the correct security string to do so.
- Resolution is tied to whatever the current chart is using. This way the view of the indicator always reflects the correct resolution of the chart.
- If either market has a 0% change, it is considered likely closed during that period and will result in a change of 0%, as they shouldn't be compared at that time.
BEST USA Bank Holidays HelperHello traders
This is a quick helper displaying the US bank holidays labels 1 day before the actual bank holiday date
Useful to be reminded when it's better to not trade as the big "whales" aren't trading either - and are probably drinking cocktails on their yachts in the Caribbeans island
This is my way of saying that, the days where the USA are off, the derivatives like indices aren't likely to give big opportunities
Of course, big move might happen but statistically, we're better off going to the Caribbeans islands as well (or preparing for the next trading day)
Bonus
The indicator displays in fuschia (never knew how to write that word properly without checking google first...) the 2019 US bank holidays
Best regards and enjoy your cocktails today :)
Dave
Fixed TimeFrame SMMAA script for SMMA calculated on fixed timeframe, different from the main chart's timeframe.
As it's known, we can't use mutable variables with security. At the same time, SMMA references to the previous values. So it's impossible to create SMMA on different timeframe, just passing a variable with SMMA to security.
To overcome this restriction, we should use a function, which calculates SMMA and we are passing the function to the security, so the function will be calculated on required timeframe.
[RD] Easy dynamic resolution dashboard=== Easy dynamic resolution dashboard (initial) ===
Easy dashboard to show different running reolution bars most of the scale is adjustable.
Current state is initial and could have some bugs, or been in a cleaner way of coding. Let me know if you find something so we could fix it
Best way to start is in a seperate pane to adjust the you like best or most. Afterwards can copied to chart if needed
The round circle in the middle is the avg low|high price of that specifick candle in the resolution
Loading and input adjustments could take a while (reload)
You should get a warning if the current timeframe is higher then the input resolutions choosen. Adjust the reolutions according and you should be fine
Special thanks go to and borrowed some code from
- @PineCoders
- @RicardoSantos
Notes / Updates
- Let me know where it need (bug) fixes or adjustments
BTC DominanceThis Script plots the BTC Dominance chart in an indicator window, so you don't have to bother with tabs as much when doing your analysis.
tips are always welcome at: (38uGQJDDZDL6wX48x4gYTccPeQ3ZHVYmY4)
I hope you enjoy the script :)
Security() Correction - Realtime vs. Historical BarsProblem
Pine's implementation of the security() function behaves differently in realtime vs. historical bars. Specifically, for historical bars, calling security() for a time frame (TF) larger/slower than the current chart's TF will return information about the last completed bar of the higher TF. However, for realtime bars (i.e. if you allow the chart to continue to plot in realtime), security() returns information about the presently in-progress bar of the higher TF. Clearly, this leads to discontinuity that is arbitrarily dependent upon when the user last loaded or refreshed the chart.
Solution
Fortunately, after understanding the problem, solving it is trivial: use security() normally for historical bars, but switch to explicitly requesting prior candle bars once the indicator is operating on realtime bars. I leave the source open here for any to use as they see fit. For testing, I include an input to allow switching back and forth between standard and corrected behavior.
Figure 1 displays the standard behavior we see in security() calls, and Figure 2 displays the behavior after my correction:
Figure 1: Typical security() behavior in Pine
Figure 2: Corrected security() behavior, forcing historical and realtime bars to refer to the same higher TF bar offset.
I publish this mostly as a reminder to myself, so I will not forget and then have to figure it out again next time it comes up in my scripting.
V21: Initial release.
LCI - Short Sale Restriction / SSR levelsThis script highlights the level at which a stock will go into SSR mode for the day. Useful when looking to short a stock
Heffae Resolution Commander (RAW)This is a script to call resolutions with some math on top of your base resolution.
Using the modulo operator to quantize integer values, it works by converting the modified resolution integer to a 4 digit string value.
Use the function within your own scripts to call funny resolutions otherwise difficult to calculate.
You cannot add series expressions to the resolution value since pine does not allow "series" as a resolution for a security call
However, you could easily stack a crapload of these together and use an expression to switch the referenced security function for your purposes.
This is the raw timeframe output as integer, not string.
To go back to string outputs (for use in security calls etc) unslash line 52 //resvalue
For those interested in the verbose version of the timeframe mod function, showing all the steps, here is a pastebin:
pastebin.com
Cheers! Drop a line / comment if you enjoy or have any questions on how to integrate this into your script@!
The Modulo operator is so much fun!
Heffae Resolution CommanderThis is a script to call resolutions with some math on top of your base resolution.
THIS IS NOT AN INDICATOR TO USE ON A CHART!!! The resolution call function is really useful for your own scripting ideas!
Using the modulo operator to quantize integer values, it works by converting the modified resolution integer to a 4 digit string value.
The function within this script is what is valuable, use it within your own scripts to call funny resolutions otherwise difficult to calculate.
You cannot add series expressions to the resolution value since pine does not allow "series " as a resolution for a security call
However, you could easily stack a crapload of these together and use
an expression to switch the referenced security function for your purposes.
The SMA and plot overlay are just there to show a visual example of how the function works.
You can view the raw timeframe output integer by getting rid of tostring(x) and // out the security calls,
plotting the raw function outputs.
For those interested in the verbose version of the timeframe mod function, showing all the steps, here is a pastebin:
pastebin.com
Cheers! Drop a line / comment if you enjoy or have any questions on how to integrate this into your script@!
The Modulo operator is so much fun!
Substratum Module [snowsilence]This module is meant to act as a framework and platform over which to develop other indicators. On its own it does essentially nothing, yet simplifies the work of adding basic customizations and flexibility to ideas immediately. The chart on this post is not a demo, so its better to just try adding the indicator to a test chart — you may find it more convenient to set "overlay=true" in the study header — and look into the settings for an intuitive sense of its purpose.
Please build off of this, let me know if you find it useful, and credit/reference me where it seems reasonable. Feedback is always appreciated!