HH-LL ZZAnother ZigZag, yes...
I believe though this concerns another angle/principle, therefore I wanted to share
How does it work?
Given:
source for level breach -> close
X breaches -> 3
Let's say this is the latest found 'lower low' (LL - blue dot under bar):
This bar has been triggered because 3 bars closed under low of previous 'trigger bar' (TB )
The high and low of this new TB will act as triggers
(aqua blue lines, seen in image above)
Then there are 2 options:
- again 3 bars closes under the latest TB , in that case the TB moves to that new LL.
- 3 bars closes higher than the high of previous TB
The high and low of this new TB act again as trigger
If a new TB LL/HH is found, the script checks previous LL/HH
and searches the highest/lowest point in between.
If necessary, the temporary highest/lowest will be adjusted:
Another example:
The last 2 points can change (repaint).
Yellow coloured lines/labels are set and won't change anymore.
Concluded:
In case of these settings:
source for level breach -> close
X breaches -> 3
once a new TB is found, the high and low act as trigger lines
- when 3 bars closes under that low , a new LL is found, this will be the new TB
- when 3 bars closes above that high , a new HH is found, this will be the new TB
and so on...
Settings:
source for level breach -> close or high/low - H/L
X breaches -> 1 -> 10
line style -> solid, dotted, dashed
show level breaches -> new found TB (blue/lime coloured)
show Support/Resistance (lines at the right)
repaint warning can be removed
show labels / lines
This ZZ can be used for Harmonic patterns, Trend evaluation, support/resistance,...
In this script, I also used new features
- text_font_family = font.family_monospace -> link
- display=display.pane -> link
Cheers!
Wskaźniki i strategie
Black Scholes Option Pricing Model w/ Greeks [Loxx]The Black Scholes Merton model
If you are new to options I strongly advise you to profit from Robert Shiller's lecture on same . It combines practical market insights with a strong authoritative grasp of key models in option theory. He explains many of the areas covered below and in the following pages with a lot intuition and relatable anecdotage. We start here with Black Scholes Merton which is probably the most popular option pricing framework, due largely to its simplicity and ease in terms of implementation. The closed-form solution is efficient in terms of speed and always compares favorably relative to any numerical technique. The Black–Scholes–Merton model is a mathematical go-to model for estimating the value of European calls and puts. In the early 1970’s, Myron Scholes, and Fisher Black made an important breakthrough in the pricing of complex financial instruments. Robert Merton simultaneously was working on the same problem and applied the term Black-Scholes model to describe new generation of pricing. The Black Scholes (1973) contribution developed insights originally proposed by Bachelier 70 years before. In 1997, Myron Scholes and Robert Merton received the Nobel Prize for Economics. Tragically, Fisher Black died in 1995. The Black–Scholes formula presents a theoretical estimate (or model estimate) of the price of European-style options independently of the risk of the underlying security. Future payoffs from options can be discounted using the risk-neutral rate. Earlier academic work on options (e.g., Malkiel and Quandt 1968, 1969) had contemplated using either empirical, econometric analyses or elaborate theoretical models that possessed parameters whose values could not be calibrated directly. In contrast, Black, Scholes, and Merton’s parameters were at their core simple and did not involve references to utility or to the shifting risk appetite of investors. Below, we present a standard type formula, where: c = Call option value, p = Put option value, S=Current stock (or other underlying) price, K or X=Strike price, r=Risk-free interest rate, q = dividend yield, T=Time to maturity and N denotes taking the normal cumulative probability. b = (r - q) = cost of carry. (via VinegarHill-Financelab )
Things to know
This can only be used on the daily timeframe
You must select the option type and the greeks you wish to show
This indicator is a work in process, functions may be updated in the future. I will also be adding additional greeks as I code them or they become available in finance literature. This indictor contains 18 greeks. Many more will be added later.
Inputs
Spot price: select from 33 different types of price inputs
Calculation Steps: how many iterations to be used in the BS model. In practice, this number would be anywhere from 5000 to 15000, for our purposes here, this is limited to 300
Strike Price: the strike price of the option you're wishing to model
% Implied Volatility: here you can manually enter implied volatility
Historical Volatility Period: the input period for historical volatility ; historical volatility isn't used in the BS process, this is to serve as a sort of benchmark for the implied volatility ,
Historical Volatility Type: choose from various types of implied volatility , search my indicators for details on each of these
Option Base Currency: this is to calculate the risk-free rate, this is used if you wish to automatically calculate the risk-free rate instead of using the manual input. this uses the 10 year bold yield of the corresponding country
% Manual Risk-free Rate: here you can manually enter the risk-free rate
Use manual input for Risk-free Rate? : choose manual or automatic for risk-free rate
% Manual Yearly Dividend Yield: here you can manually enter the yearly dividend yield
Adjust for Dividends?: choose if you even want to use use dividends
Automatically Calculate Yearly Dividend Yield? choose if you want to use automatic vs manual dividend yield calculation
Time Now Type: choose how you want to calculate time right now, see the tool tip
Days in Year: choose how many days in the year, 365 for all days, 252 for trading days, etc
Hours Per Day: how many hours per day? 24, 8 working hours, or 6.5 trading hours
Expiry date settings: here you can specify the exact time the option expires
The Black Scholes Greeks
The Option Greek formulae express the change in the option price with respect to a parameter change taking as fixed all the other inputs. ( Haug explores multiple parameter changes at once .) One significant use of Greek measures is to calibrate risk exposure. A market-making financial institution with a portfolio of options, for instance, would want a snap shot of its exposure to asset price, interest rates, dividend fluctuations. It would try to establish impacts of volatility and time decay. In the formulae below, the Greeks merely evaluate change to only one input at a time. In reality, we might expect a conflagration of changes in interest rates and stock prices etc. (via VigengarHill-Financelab )
First-order Greeks
Delta: Delta measures the rate of change of the theoretical option value with respect to changes in the underlying asset's price. Delta is the first derivative of the value
Vega: Vegameasures sensitivity to volatility. Vega is the derivative of the option value with respect to the volatility of the underlying asset.
Theta: Theta measures the sensitivity of the value of the derivative to the passage of time (see Option time value): the "time decay."
Rho: Rho measures sensitivity to the interest rate: it is the derivative of the option value with respect to the risk free interest rate (for the relevant outstanding term).
Lambda: Lambda, Omega, or elasticity is the percentage change in option value per percentage change in the underlying price, a measure of leverage, sometimes called gearing.
Epsilon: Epsilon, also known as psi, is the percentage change in option value per percentage change in the underlying dividend yield, a measure of the dividend risk. The dividend yield impact is in practice determined using a 10% increase in those yields. Obviously, this sensitivity can only be applied to derivative instruments of equity products.
Second-order Greeks
Gamma: Measures the rate of change in the delta with respect to changes in the underlying price. Gamma is the second derivative of the value function with respect to the underlying price.
Vanna: Vanna, also referred to as DvegaDspot and DdeltaDvol, is a second order derivative of the option value, once to the underlying spot price and once to volatility. It is mathematically equivalent to DdeltaDvol, the sensitivity of the option delta with respect to change in volatility; or alternatively, the partial of vega with respect to the underlying instrument's price. Vanna can be a useful sensitivity to monitor when maintaining a delta- or vega-hedged portfolio as vanna will help the trader to anticipate changes to the effectiveness of a delta-hedge as volatility changes or the effectiveness of a vega-hedge against change in the underlying spot price.
Charm: Charm or delta decay measures the instantaneous rate of change of delta over the passage of time.
Vomma: Vomma, volga, vega convexity, or DvegaDvol measures second order sensitivity to volatility. Vomma is the second derivative of the option value with respect to the volatility, or, stated another way, vomma measures the rate of change to vega as volatility changes.
Veta: Veta or DvegaDtime measures the rate of change in the vega with respect to the passage of time. Veta is the second derivative of the value function; once to volatility and once to time.
Vera: Vera (sometimes rhova) measures the rate of change in rho with respect to volatility. Vera is the second derivative of the value function; once to volatility and once to interest rate.
Third-order Greeks
Speed: Speed measures the rate of change in Gamma with respect to changes in the underlying price.
Zomma: Zomma measures the rate of change of gamma with respect to changes in volatility.
Color: Color, gamma decay or DgammaDtime measures the rate of change of gamma over the passage of time.
Ultima: Ultima measures the sensitivity of the option vomma with respect to change in volatility.
Dual Delta: Dual Delta determines how the option price changes in relation to the change in the option strike price; it is the first derivative of the option price relative to the option strike price
Dual Gamma: Dual Gamma determines by how much the coefficient will changedual delta when the option strike price changes; it is the second derivative of the option price relative to the option strike price.
Related Indicators
Cox-Ross-Rubinstein Binomial Tree Options Pricing Model
Implied Volatility Estimator using Black Scholes
Boyle Trinomial Options Pricing Model
TPO Market Profile [Kioseff Trading]REPOST; SCRIPT WORKS!!
Due to technical error, this script was republished! Thank you for your support (:
Hello!
This indicator comprises a real time TPO Market Profile!
The script works on any timeframe 1 second or greater - the script calculates relative to the timeframe selected for your chart.
The image above shows the 1-minute BTCUSD chart; 650 +/- tick levels are set.
To see the script in full functionality - try using bar replay on a cryptocurrency 1-minute chart (start at the beginning of a regular hours session). Be sure to adjust the tick spread if necessary (:
So far, the script's held up in real time - I've not had any array loop errors or timeouts. The TPO profile updates accordingly with changes in time / high and low prices. Letters are appended to the profile in real time.
The image above shows configurations for the indicator. I plan to update the indicator quite a bit over the coming days - more to come.
You can select the timeframe change the indicator accounts for. For instance, you can have set the indicator to reset every day, every 30 minutes, every 5 minutes, every week, month, etc.
In the image above, I configured the indicator to recalculate every 3 months. Consequently, the indicator will record a TPO profile for three consecutive, reset, then record a TPO profile for the next 3 months. This setting makes the indicator compatible with any timeframe greater than 1 minute.
You can also use a drag & drop time-start bar to modify the starting point for the market profile TPO calculation.
The indicator hosts an option to auto calculate the tick spread between levels. However, as you switch timeframes and assets, sometimes, you'll have to manually set the tick range (:
Thanks for checking it out; more to come!
Sep 4
Release Notes: UPDATE: The indicator can work on seconds-based charts.
The image above shows the indicator working on the 1-second chart.
(Screenshot is old; characters are now numbered instead of strange unicode)
Release Notes: Added value area + vah + val. Font update. Changed characters to numbered once the alphabet is exhausted. POC, VAH, and VAL label located left of the first bar of the interval. Initial balance range can be toggled. Spaced the characters (more legible). Quite a bit of aesthetic changes so check it out!
Soon, I'll release a version of the script that shows VAH, POC, VAL, and TPO letters from previous sessions. I coded this feature into this indicator; however, it was removed due to load time complications. This feature will be its own script (:
If the script has trouble loading please let me know (:
Tick StatisticsTick Statistics:
I have seen many questions/queries related to tick data in TV telegram channels. This script will help pine scripts to understand how ticks work, how to capture and process tick data.
This is an educational indicator script for pine scripters.
The indicator shall work only on real time candles. Tick data capture is initiated as soon as indicator is loaded on the chart. You might not get correct statistics on 1st candle in case indicator is loaded when real time candle is in progress, in such case you can monitor the statistics generated for subsequent candles.
Generated statistics is shown on the chart by placing 2 diamond shapes above and below the candle.
Diamond shape below the candle will have candles ‘tick data’ listed in a table. This can be view by placing mouse pointer on the diamond shape. Refer to point 1 below for more details.
Diamond shape above the candle will have statistics as mentioned in point no 2 onwards. To view the statistics place the mouse point on the diamond shape. The shape will appear in green color when both tick price and tick volume are both moving in the same direction. The diamond shape in red color means tick price and tick volume are moving in opposite direction.
The script captures tick by tick data and generate statistics below:
1. List of tick data with details below: (this is stored in the diamond shape placed below the candle)
a. Tick no
b. Tick type – Up tick (Up), Down tick (Dn), No change (--)
c. Tick price
d. Volume
e. Price difference (as compared to previous tick price)
f. Volume difference (as compared to previous tick volume)
2. Tick statistics
a. Total ticks
b. Number of up ticks
c. Number of down ticks
d. Number of No change ticks
3. Volume Statistics
a. Total volume
b. Up tick volume
c. Down tick volume
d. Volume associated with ticks where there is no change
e. Candle volume (just for reconciliation purpose)
4. Max-min statistics
a. Max volume = <> at price = <> at tick no = <>
b. Min volume = <> at price = <> at tick no = <>
c. Max price = <> at volume = <> at tick no = <>
d. Min price = <> at volume = <> at tick no = <>
5. Candle summary
a. Price << Up >> (if price is up as compared to 1st tick <> otherwise
b. Volume <> (if up tick volume is more than down tick volume <> otherwise
Strength of Divergence Across Multiple IndicatorsOverview:
One-stop shop for all your divergence needs, including:
(1) A single metric for divergence strength across multiple indicators.
(2) Labels that make it easy to spot where the truly strong divergence is by showing the overall divergence strength value along with the number of divergent indicators. Hovering over the label shows a breakdown of each divergent indicator and its individual divergence strength value.
(3) Fully customizable, including inputs for pivot lengths, divergence types, and weights for every component of the divergence strength calculation. This allows you to quickly and easily optimize the output for any chart. Don't worry, the default settings will have you covered if you're not interested in what's going on under the hood.
The Divergence Strength Calculation:
The total divergence strength value is the sum of the divergence strengths of all indicators for which divergence was detected at a given bar. Each indicator's individual divergence strength is comprised of two basic components: (1) |ΔPrice| - the magnitude of the change in price over the divergence period (pivot-to-pivot), and (2) |ΔIndicator| - the magnitude of the change in indicator value over the divergence period.
Because different indicators' scales and volatility can vary greatly, the Δ values are expressed in terms of standard deviation to ensure that the values are meaningful and equitable across all indicators and assets/instruments/currency pairs, etc:
|ΔIndicator| = |indicator_value_1 - indicator_value_2| / 2 * StDev(indicator_series,100)
Calculation Weights:
All components of the calculation are weighted and can be modified on the Inputs page in settings (weights are simply multipliers). For example, if you think hidden divergence should carry less weight than regular divergence, you can assign it a lesser weight. Or if you think RSI divergence is worth more than OBV divergence, you can adjust their weights accordingly. List of weights:
Regular divergence weight - default = 1
Hidden divergence weight - default = 1
ΔPrice weight - default = 0.5 (multiplied by the ΔPrice component)
ΔIndicator weight - default = 1.5 (multiplied by the ΔIndicator component)
RSI weight - default = 1.1
OBV weight - default = 0.8
MACD weight - default = 0.9
STOCH weight - default = 0.9
Development for additional indicators is ongoing, as is research into the optimal weight configuration(s).
Other Inputs:
Pivot lengths - specify the number of bars before and after each pivot high/low to consider it a valid candidate for divergence.
Lookback bars and Lookback pivots - specify the number of bars or the number of pivots to look back across.
Price sources - specify separate price sources for bullish and bearish divergence
Display settings - specify how lines and labels should display, including which divergence strength values should show the largest labels. Include/exclude specific divergence types and indicators.
Please report any bugs, or let me know if you have any enhancement suggestions or requests for additional indicators.
@reees
RSI Past Can Turn RSI Into a Directional ToolThe Relative Strength Index was created by J. Welles Wilder to measure overbought and oversold conditions. It’s also found popularity as an overall measure of direction because upward-trending stocks often hit overbought conditions. The opposite can be true with underperformers.
Today’s custom script, RSI Past, attempts to capture this secondary use of RSI as a directional indicator.
RSI Past achieves this by comparing how many bars have passed since RSI's most recent overbought and oversold readings. It then plots a simple difference between those two numbers.
Stocks with “bullish” signals will have positive readings that will increase each time RSI hits an overbought condition.
“Bearish” readings are just the opposite, growing more negative as oversold conditions occur.
An examination of some individual stocks may show the usefulness of this approach.
Meta Platforms , for example, hit an oversold condition almost exactly one year ago, and has remained under heavy selling pressure since:
Exxon Mobil , on the other hand, flipped to a bullish reading last October and has trended higher since:
This raises some interesting questions for Apple, shown on the main chart above. AAPL’s RSI Past has maintained a bullish reading for over a year -- unlike most other big technology stocks and the broader Nasdaq-100. Could this reflect bigger directional strength, especially with prices holding the $150 level that’s had relevance several times mid-2021?
TradeStation has, for decades, advanced the trading industry, providing access to stocks, options, futures and cryptocurrencies. See our Overview for more.
Important Information
TradeStation Securities, Inc., TradeStation Crypto, Inc., and TradeStation Technologies, Inc. are each wholly owned subsidiaries of TradeStation Group, Inc., all operating, and providing products and services, under the TradeStation brand and trademark. You Can Trade, Inc. is also a wholly owned subsidiary of TradeStation Group, Inc., operating under its own brand and trademarks. TradeStation Crypto, Inc. offers to self-directed investors and traders cryptocurrency brokerage services. It is neither licensed with the SEC or the CFTC nor is it a Member of NFA. When applying for, or purchasing, accounts, subscriptions, products, and services, it is important that you know which company you will be dealing with. Please click here for further important information explaining what this means.
This content is for informational and educational purposes only. This is not a recommendation regarding any investment or investment strategy. Any opinions expressed herein are those of the author and do not represent the views or opinions of TradeStation or any of its affiliates.
Investing involves risks. Past performance, whether actual or indicated by historical tests of strategies, is no guarantee of future performance or success. There is a possibility that you may sustain a loss equal to or greater than your entire investment regardless of which asset class you trade (equities, options, futures, or digital assets); therefore, you should not invest or risk money that you cannot afford to lose. Before trading any asset class, first read the relevant risk disclosure statements on the Important Documents page, found here: www.tradestation.com .
ABC 123 Harmonic Ratio Custom Range Interactive█ OVERVIEW
This indicator was designed based on Harmonic Trading : Volume One written by Scott Carney.
This is about harmonic ratios which expanded through retracement and projection.
Derivation is pretty much explained here such as Primary, Primary Derivation, Secondary Derivation and Secondary Derivation Extreme.
Derivation value depends on minimum retracement or maximum projection.
This derivation value utilize Fibonacci value which later expand to Harmonic Ratio.
█ INSPIRATION
Inspired by design, code and usage of CAGR . Basic usage of custom range / interactive, pretty much explained here . Credits to TradingView.
This build is based and visualized upon Harmonic Trading Ratios.
This build also was stripped down from XABCD Harmonic Pattern Custom Range Interactive .
█ CREDITS
Scott Carney, Harmonic Trading : Volume One (Page 18)
█ FEATURES
Table can positioned by any position and font size can be resized.
Labels can be either changed to alphabets or numbers.
█ HOW TO USE
Draw points from Point A to Point C.
Dont worry about magnet, point will attached depends on High or Low of the candle.
█ USAGE / TIPS EXAMPLES (Description explained in each image)
Machine Learning: kNN (New Approach)Description:
kNN is a very robust and simple method for data classification and prediction. It is very effective if the training data is large. However, it is distinguished by difficulty at determining its main parameter, K (a number of nearest neighbors), beforehand. The computation cost is also quite high because we need to compute distance of each instance to all training samples. Nevertheless, in algorithmic trading KNN is reported to perform on a par with such techniques as SVM and Random Forest. It is also widely used in the area of data science.
The input data is just a long series of prices over time without any particular features. The value to be predicted is just the next bar's price. The way that this problem is solved for both nearest neighbor techniques and for some other types of prediction algorithms is to create training records by taking, for instance, 10 consecutive prices and using the first 9 as predictor values and the 10th as the prediction value. Doing this way, given 100 data points in your time series you could create 10 different training records. It's possible to create even more training records than 10 by creating a new record starting at every data point. For instance, you could take the first 10 data points and create a record. Then you could take the 10 consecutive data points starting at the second data point, the 10 consecutive data points starting at the third data point, etc.
By default, shown are only 10 initial data points as predictor values and the 6th as the prediction value.
Here is a step-by-step workthrough on how to compute K nearest neighbors (KNN) algorithm for quantitative data:
1. Determine parameter K = number of nearest neighbors.
2. Calculate the distance between the instance and all the training samples. As we are dealing with one-dimensional distance, we simply take absolute value from the instance to value of x (| x – v |).
3. Rank the distance and determine nearest neighbors based on the K'th minimum distance.
4. Gather the values of the nearest neighbors.
5. Use average of nearest neighbors as the prediction value of the instance.
The original logic of the algorithm was slightly modified, and as a result at approx. N=17 the resulting curve nicely approximates that of the sma(20). See the description below. Beside the sma-like MA this algorithm also gives you a hint on the direction of the next bar move.
Delta Volume Channels [LucF]█ OVERVIEW
This indicator displays on-chart visuals aimed at making the most of delta volume information. It can color bars and display two channels: one for delta volume, another calculated from the price levels of bars where delta volume divergences occur. Markers and alerts can also be configured using key conditions, and filtered in many different ways. The indicator caters to traders who prefer chart visuals over raw values. It will work on historical bars and in real time, using intrabar analysis to calculate delta volume in both conditions.
█ CONCEPTS
Delta Volume
The volume delta concept divides a bar's volume in "up" and "down" volumes. The delta is calculated by subtracting down volume from up volume. Many calculation techniques exist to isolate up and down volume within a bar. The simplest techniques use the polarity of interbar price changes to assign their volume to up or down slots, e.g., On Balance Volume or the Klinger Oscillator . Others such as Chaikin Money Flow use assumptions based on a bar's OHLC values. The most precise calculation method uses tick data and assigns the volume of each tick to the up or down slot depending on whether the transaction occurs at the bid or ask price. While this technique is ideal, it requires huge amounts of data on historical bars, which usually limits the historical depth of charts and the number of symbols for which tick data is available.
This indicator uses intrabar analysis to achieve a compromise between the simplest and most precise methods of calculating volume delta. In the context where historical tick data is not yet available on TradingView, intrabar analysis is the most precise technique to calculate volume delta on historical bars on our charts. TradingView's Volume Profile built-in indicators use it, as do the CVD - Cumulative Volume Delta Candles and CVD - Cumulative Volume Delta (Chart) indicators published from the TradingView account . My Volume Delta Columns Pro indicator also uses intrabar analysis. Other volume delta indicators such as my Realtime 5D Profile use realtime chart updates to achieve more precise volume delta calculations. Indicators of that type cannot be used on historical bars however; they only work in real time.
This is the logic I use to assign intrabar volume to up or down slots:
• If the intrabar's open and close values are different, their relative position is used.
• If the intrabar's open and close values are the same, the difference between the intrabar's close and the previous intrabar's close is used.
• As a last resort, when there is no movement during an intrabar and it closes at the same price as the previous intrabar, the last known polarity is used.
Once all intrabars making up a chart bar have been analyzed and the up or down property of each intrabar's volume determined, the up volumes are added and the down volumes subtracted. The resulting value is volume delta for that chart bar, which can be used as an estimate of the buying/selling pressure on an instrument.
Delta Volume Percent (DV%)
This value is the proportion that delta volume represents of the total intrabar volume in the chart bar. Note that on some symbols/timeframes, the total intrabar volume may differ from the chart's volume for a bar, but that will not affect our calculations since we use the total intrabar volume.
Delta Volume Channel
The DV channel is the space between two moving averages: the reference line and a DV%-weighted version of that reference. The reference line is a moving average of a type, source and length which you select. The DV%-weighted line uses the same settings, but it averages the DV%-weighted price source.
The weight applied to the source of the reference line is calculated from two values, which are multiplied: DV% and the relative size of the bar's volume in relation to previous bars. The effect of this is that DV% values on bars with higher total volume will carry greater weight than those with lesser volume.
The DV channel can be in one of four states, each having its corresponding color:
• Bull (teal): The DV%-weighted line is above the reference line.
• Strong bull (lime): The bull condition is fulfilled and the bar's close is above the reference line and both the reference and the DV%-weighted lines are rising.
• Bear (maroon): The DV%-weighted line is below the reference line.
• Strong bear (pink): The bear condition is fulfilled and the bar's close is below the reference line and both the reference and the DV%-weighted lines are falling.
Divergences
In the context of this indicator, a divergence is any bar where the slope of the reference line does not match that of the DV%-weighted line. No directional bias is assigned to divergences when they occur.
Divergence Channel
The divergence channel is the space between two levels (by default, the bar's low and high ) saved when divergences occur. When price has breached a channel and a new divergence occurs, a new channel is created. Until that new channel is breached, bars where additional divergences occur will expand the channel's levels if the bar's price points are outside the channel.
Prices breaches of the divergence channel will change its state. Divergence channels can be in one of five different states:
• Bull (teal): Price has breached the channel to the upside.
• Strong bull (lime): The bull condition is fulfilled and the DV channel is in the strong bull state.
• Bear (maroon): Price has breached the channel to the downside.
• Strong bear (pink): The bear condition is fulfilled and the DV channel is in the strong bear state.
• Neutral (gray): The channel has not been breached.
█ HOW TO USE THE INDICATOR
Load the indicator on an active chart (see here if you don't know how).
The default configuration displays:
• The DV channel, without the reference or DV%-weighted lines.
• The Divergence channel, without its level lines.
• Bar colors using the state of the DV channel.
The default settings use an Arnaud-Legoux moving average on the close and a length of 20 bars. The DV%-weighted version of it uses a combination of DV% and relative volume to calculate the ultimate weight applied to the reference. The DV%-weighted line is capped to 5 standard deviations of the reference. The lower timeframe used to access intrabars automatically adjusts to the chart's timeframe and achieves optimal balance between the number of intrabars inspected in each chart bar, and the number of chart bars covered by the script's calculations.
The Divergence channel's levels are determined using the high and low of the bars where divergences occur. Breaches of the channel require a bar's low to move above the top of the channel, and the bar's high to move below the channel's bottom.
No markers appear on the chart; if you want to create alerts from this script, you will need first to define the conditions that will trigger the markers, then create the alert, which will trigger on those same conditions.
To learn more about how to use this indicator, you must understand the concepts it uses and the information it displays, which requires reading this description. There are no videos to explain it.
█ FEATURES
The script's inputs are divided in four sections: "DV channel", "Divergence channel", "Other Visuals" and "Marker/Alert Conditions". The first setting is the selection method used to determine the intrabar precision, i.e., how many lower timeframe bars (intrabars) are examined in each chart bar. The more intrabars you analyze, the more precise the calculation of DV% results will be, but the less chart coverage can be covered by the script's calculations.
DV Channel
Here, you control the visibility and colors of the reference line, its weighted version, and the DV channel between them.
You also specify what type of moving average you want to use as a reference line, its source and length. This acts as the DV channel's baseline. The DV%-weighted line is also a moving average of the same type and length as the reference line, except that it will be calculated from the DV%-weighted source used in the reference line. By default, the DV%-weighted line is capped to five standard deviations of the reference line. You can change that value here. This section is also where you can disable the relative volume component of the weight.
Divergence Channel
This is where you control the appearance of the divergence channel and the key price values used in determining the channel's levels and breaching conditions. These choices have an impact on the behavior of the channel. More generous level prices like the default low and high selection will produce more conservative channels, as will the default choice for breach prices.
In this section, you can also enable a mode where an attempt is made to estimate the channel's bias before price breaches the channel. When it is enabled, successive increases/decreases of the channel's top and bottom levels are counted as new divergences occur. When one count is greater than the other, a bull/bear bias is inferred from it.
Other Visuals
You specify here:
• The method used to color chart bars, if you choose to do so.
• The display of a mark appearing above or below bars when a divergence occurs.
• If you want raw values to appear in tooltips when you hover above chart bars. The default setting does not display them, which makes the script faster.
• If you want to display an information box which by default appears in the lower left of the chart.
It shows which lower timeframe is used for intrabars, and the average number of intrabars per chart bar.
Marker/Alert Conditions
Here, you specify the conditions that will trigger up or down markers. The trigger conditions can include a combination of state transitions of the DV and the divergence channels. The triggering conditions can be filtered using a variety of conditions.
Configuring the marker conditions is necessary before creating an alert from this script, as the alert will use the marker conditions to trigger.
Markers only appear on bar closes, so they will not repaint. Keep in mind, when looking at markers on historical bars, that they are positioned on the bar when it closes — NOT when it opens.
Raw values
The raw values calculated by this script can be inspected using a tooltip and the Data Window. The tooltip is visible when you hover over the top of chart bars. It will display on the last 500 bars of the chart, and shows the values of DV, DV%, the combined weight, and the intermediary values used to calculate them.
█ INTERPRETATION
The aim of the DV channel is to provide a visual representation of the buying/selling pressure calculated using delta volume. The simplest characteristic of the channel is its bull/bear state. One can then distinguish between its bull and strong bull states, as transitions from strong bull to bull states will generally happen when buyers are losing steam. While one should not infer a reversal from such transitions, they can be a good place to tighten stops. Only time will tell if a reversal will occur. One or more divergences will often occur before reversals.
The nature of the divergence channel's design makes it particularly adept at identifying consolidation areas if its settings are kept on the conservative side. A gray divergence channel should usually be considered a no-trade zone. More adventurous traders can use the DV channel to orient their trade entries if they accept the risk of trading in a neutral divergence channel, which by definition will not have been breached by price.
If your charts are already busy with other stuff you want to hold on to, you could consider using only the chart bar coloring component of this indicator:
At its simplest, one way to use this indicator would be to look for overlaps of the strong bull/bear colors in both the DV channel and a divergence channel, as these identify points where price is breaching the divergence channel when buy/sell pressure is consistent with the direction of the breach. I have highlighted all those points in the chart below. Not all of them would have produced profitable trades, but nothing is perfect in the markets. Also, keep in mind that the circles identify the visual you would be looking for — not the trade's entry level.
█ LIMITATIONS
• The script will not work on symbols where no volume is available. An error will appear when that is the case.
• Because a maximum of 100K intrabars can be analyzed by a script, a compromise is necessary between the number of intrabars analyzed per chart bar
and chart coverage. The more intrabars you analyze per chart bar, the less coverage you will obtain.
The setting of the "Intrabar precision" field in the "DV channel" section of the script's inputs
is where you control how the lower timeframe is calculated from the chart's timeframe.
█ NOTES
Volume Quality
If you use volume, it's important to understand its nature and quality, as it varies with sectors and instruments. My Volume X-ray indicator is one way you can appraise the quality of an instrument's intraday volume.
For Pine Script™ Coders
• This script uses the new overload of the fill() function which now makes it possible to do vertical gradients in Pine. I use it for both channels displayed by this script.
• I use the new arguments for plot() 's `display` parameter to control where the script plots some of its values,
namely those I only want to appear in the script's status line and in the Data Window.
• I wrote my script using the revised recommendations in the Style Guide from the Pine v5 User Manual.
█ THANKS
To PineCoders . I have used their lower_tf library in this script, to manage the calculation of the LTF and intrabar stats, and their Time library to convert a timeframe in seconds to a printable form for its display in the Information box.
To TradingView's Pine Script™ team. Their innovations and improvements, big and small, constantly expand the boundaries of the language. What this script does would not have been possible just a few months back.
And finally, thanks to all the users of my scripts who take the time to comment on my publications and suggest improvements. I do not reply to all but I do read your comments and do my best to implement your suggestions with the limited time that I have.
HSV and HSL gradient Tools ( Built-in Drop-in replacement )Library "hsvColor"
HSV and HSL Gradient Tool Alternatives and helpers. Demo'd is built-in in the middle with HSL/HSV gradients on top/bottom
TODO: Solve for #000000 issue
rgbhsv(_col)
RGB Color to HSV Values
Parameters:
_col : Color input (#abc012 or color.name or color.rgb(0,0,0,0))
Returns: values
rgbhsv(_r, _g, _b, _t)
RGB Color to HSV Values
Parameters:
_r : Red 0 - 255
_g : Green 0 - 255
_b : Blue 0 - 255
_t : Transp 0 - 100
Returns: values
hsv(_h, _s, _v, _a)
HSV colors, Auto fix if past boundaries
Parameters:
_h : Hue Input (-360 - 360) or further
_s : Saturation 0.- 1.
_v : Value 0.- 1.
_a : Alpha 0.- 1.
Returns: Color output
hue(_col)
returns 0-359 hue on color wheel
Parameters:
_col :
Returns: 360 degree hue value
hsv_gradient(signal, _startVal, _endVal, _startCol, _endCol)
Color Gradient Replacement Function for HSV calculated Gradents
Parameters:
signal : Control signal
_startVal : start color limit
_endVal : end color limit
_startCol : start color
_endCol : end color
Returns: HSV calculated gradient
hsl_gradient(signal, _startVal, _endVal, _startCol, _endCol)
Color Gradient Replacement Function for HSV calculated Gradents
Parameters:
signal : Control signal
_startVal : start color limit
_endVal : end color limit
_startCol : start color
_endCol : end color
Returns: HSV calculated gradient
STD-Filtered, N-Pole Gaussian Filter [Loxx]This is a Gaussian Filter with Standard Deviation Filtering that works for orders (poles) higher than the usual 4 poles that was originally available in Ehlers Gaussian Filter formulas. Because of that, it is a sort of generalized Gaussian filter that can calculate arbitrary (order) pole Gaussian Filter and which makes it a sort of a unique indicator. For this implementation, the practical mathematical maximum is 15 poles after which the precision of calculation is useless--the coefficients for levels above 15 poles are so high that the precision loss actually means very little. Despite this maximal precision utility, I've left the upper bound of poles open-ended so you can try poles of order 15 and above yourself. The default is set to 5 poles which is 1 pole greater than the normal maximum of 4 poles.
The purpose of the standard deviation filter is to filter out noise by and by default it will filter 1 standard deviation. Adjust this number and the filter selections (price, both, GMA, none) to reduce the signal noise.
What is Ehlers Gaussian filter?
This filter can be used for smoothing. It rejects high frequencies (fast movements) better than an EMA and has lower lag. published by John F. Ehlers in "Rocket Science For Traders".
A Gaussian filter is one whose transfer response is described by the familiar Gaussian bell-shaped curve. In the case of low-pass filters, only the upper half of the curve describes the filter. The use of gaussian filters is a move toward achieving the dual goal of reducing lag and reducing the lag of high-frequency components relative to the lag of lower-frequency components.
A gaussian filter with...
One Pole: f = alpha*g + (1-alpha)f
Two Poles: f = alpha*2g + 2(1-alpha)f - (1-alpha)2f
Three Poles: f = alpha*3g + 3(1-alpha)f - 3(1-alpha)2f + (1-alpha)3f
Four Poles: f = alpha*4g + 4(1-alpha)f - 6(1-alpha)2f + 4(1-alpha)3f - (1-alpha)4f
and so on...
For an equivalent number of poles the lag of a Gaussian is about half the lag of a Butterworth filters: Lag = N*P / pi^2, where,
N is the number of poles, and
P is the critical period
Special initialization of filter stages ensures proper working in scans with as few bars as possible.
From Ehlers Book: "The first objective of using smoothers is to eliminate or reduce the undesired high-frequency components in the eprice data. Therefore these smoothers are called low-pass filters, and they all work by some form of averaging. Butterworth low-pass filters can do this job, but nothing comes for free. A higher degree of filtering is necessarily accompanied by a larger amount of lag. We have come to see that is a fact of life."
References John F. Ehlers: "Rocket Science For Traders, Digital Signal Processing Applications", Chapter 15: "Infinite Impulse Response Filters"
Included
Loxx's Expanded Source Types
Signals
Alerts
Bar coloring
Related indicators
STD-Filtered, Gaussian Moving Average (GMA)
STD-Filtered, Gaussian-Kernel-Weighted Moving Average
One-Sided Gaussian Filter w/ Channels
Fisher Transform w/ Dynamic Zones
R-sqrd Adapt. Fisher Transform w/ D. Zones & Divs .
Portfolio PerformanceThis indicators will help you to compute portfolio performance and display results with a stats table and a nice monthly chart.
In this script you can do following:
Compose portfolio with up to 15 instruments
Change Initial capital / date range / rebalancing period
Compare portfolio performance with a benchmark
Compute basic stats
Compute instruments contribution
Display monthly performance of portfolio and benchmark
Change style for almost everything you see on your chart
Hope it will be useful for you!
Thanks to @MUQWISHI for helping me coding it.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Weighted percentile nearest rankYo, posting it for the whole internet, took the whole day to find / to design the actual working solution for weighted percentile 'nearest rank' algorithm, almost no reliable info online and a lot of library-style/textbook-style solutions that don't provide on real world production level.
The principle:
0) initial data
data = 22, 33, 11, 44, 55
weights = 5 , 3 , 2 , 1 , 4
array(s) size = 5
1) sort data array, apply the sorting pattern to the weights array, resulting:
data = 11, 22, 33, 44, 55
weights = 2 , 5 , 3 , 1 , 4
2) get weights cumsum and sum:
weights = 2, 5, 3 , 1 , 4
weights_cum = 2, 7, 10, 11, 15
weights_sum = 15
3) say we wanna find 50th percentile, get a threshold value:
n = 50
thres = weights_sum / 100 * n
7.5 = 15 / 100 * 50
4) iterate through weights_cum until you find a value that >= the threshold:
for i = 0 to size - 1
2 >= 7.5 ? nah
7 >= 7.5 ? nah
10 >= 7.5 ? aye
5) take the iteration index that resulted "aye", and find the data value with the same index, that's gonna be the resulting percentile.
i = 2
data = 33
This one is not an approximation, not an estimator, it's the actual weighted percentile nearest rank as it is.
I tested the thing extensively and it works perfectly.
For the skeptics, check lines 40, 41, 69 in the code, you can comment/uncomment dem to switch for unit (1) weights, resulting in the usual non-weighted percentile nearest rank that ideally matches the TV's built-in function.
Shoutout for @wallneradam for the sorting function mane
...
Live Long and Prosper
(Quartile Vol.; Vol. Aggregation; Range US Bars; Gaps) [Kioseff]Hello!
This indicator is a multifaceted tool that's, hopefully, useful for price action and volume analysis.
(This script makes use of the newly introduced "text_font" parameter)
With this script you'll have access to:
Range US Chart
Volume Aggregation Chart
Gaps Chart
Volume by Quartile
Consequently, you'll have access to:
First Quartile Volume Threshold
Second Quartile Volume Threshold
Third Quartile Volume Threshold
90th Percentile Volume Threshold
Fourth Quartile Volume Threshold
Q2 - Q1 Dispersion
Q3 - Q2 Dispersion
Q4 - Q3 Dispersion
Quartile Deviation
Interquartile Range
Avg. "n" bar return following "high" volume
Avg. "n" bar positive return following "high" volume
Avg. "n" bar negative following "high" volume
# of Positive Returns Following a Gap
# of Negative Returns Following a Gap
# of Gaps
# of Up Gaps
# of Down Gaps
Average # of bars to fill Up Gaps
Average # of bars to dill Down Gaps
Average Gap Up % increase
Average Gap Down % decrease
Cumulative % increase of all Up Gaps
Cumulative % decrease of all Down Gaps
Sort gaps by distance from price
Hide gaps that price substantially deviates from (gaps will reappear when price trades near the gap)
Segment Range US bars by date
Manually configure Range US price thresholds
Identify "congestion" areas with Range US bars
Range US Levels that must be exceeded for a new Range US bar to produce
Manually configure cumulative volume threshold for Volume Aggregation bars
Segment Volume Aggregation bars by date
Largest Volume Aggregation bar increases
Largest Volume Aggregation bar decreases
Calculate log returns after "high" volume sessions
Quartile Volume
The Quartile Volume portion of the script segments price/volume intervals by quartile.
The image above shows features of the indicator.
For statistics, the following metrics are recorded:
First Quartile
Second Quartile
Third Quartile
90th Percentile
Fourth Quartile
Q2 - Q1 Dispersion
Q3 - Q2 Dispersion
Q4 - Q3 Dispersion
Quartile Deviation
Interquartile Range
Color-coordinated price bars (by volume quartiles)
The percent rank for the volume of the current bar
Avg. "n" bar return following "high" volume
Avg. "n" bar positive return following "high" volume
Avg. "n" bar negative following "high" volume
The script colors bars via gradient.
By default, bars are colored lime when volume for the interval is "high" (exceeds upper quartile thresholds). The greener the bar, the higher the volume for the interval.
Bars are colored red when volume for the interval is "low" (fails to exceed lower quartile thresholds). The redder the bar, the lower the volume for the interval.
Naturally, brownish-colored bars reflect a volume interval that concluded near the median.
The image above exemplifies the process. This feature might be useful to categorize / objectively define high-volume clusters, low-volume clusters, high-volume price moves, low-volume price moves, etc.
For greater precision, you can select to color bars by volume quartile they belong to.
The image above shows color-coordinated price bars. More details shown in the image.
Additionally, you can select to plot the quartile/percentile that a price bar belongs to on the chart.
The image above shows price bars numbered by the volume quartile they belong to.
The script will distinguish successive 90th percentile violations, superimpose a linear regression channel atop the data sequence, and record pertinent statistics.
The image above shows the process.
Lastly, the user can plot an anchored VWAP using a built-in time function.
The image above shows the anchored VWAP.
Range US Chart
A Range US chart operates irrespective of time and volume - simply - bars produce after a user-defined price move is achieved/exceeded in either direction. A range us chart produces “trend candles” and “reversal candles”. A reversal candle always moves against the most immediate bar; a trend candle always moves in favor of the most immediate bar. The user defines the dollar amount price must travel up/down for a trend candle to fulfill, and for a reversal candle to fulfill.
Note: if a “down reversal” candle (red) Is produced, it’s impossible for the next candle to also be a down reversal candle - for the downside move to continue the criteria for a down trend candle must be fulfilled. Similarly, if an “up reversal” candle (green) Is produced, it’s impossible for the next candle to also be an up reversal candle - for the upside move to continue, the criteria for an uptrend trend candle must be fulfilled. Consequently, Range US bars frequently trade at the same level for extended periods. This is intentional, as this chart type is theorized to “filter noise” (whether Range US charts fulfill this theory is to your discretion).
Lastly, if an up trend candle (green) is produced, the next candle cannot be up a reversal up candle - only a trend up candle or reversal down candle can produce - vice versa for a trend down candle (the subsequent candle cannot be a reversal down candle). In this sense, an uptrend continues on successive trend up candles; a down trend continues on successive trend down candles.
The image above exemplifies Range US chart functionality.
The lower-right stats table shows the requisite price move for a "Trend" candle to produce and for a "Reversal" candle to produce.
The default settings for this chart time automatically calculate the required "Trend" candle price move and the required "Reversal" candle price move. However, both settings are configurable.
The image above shows manually configured parameters for a trend bar and reversal bar to produce. This feature allows the user to replicate the Range US chart hosted on extrinsic charting platforms.
However, please consider that this script does not use tick data; 1-minute OHLC data is used for calculations.
Consequently, configuring the trend bar and reversal bar requirement too low may return inaccurate data. For instance, if you set trend candles to form after a $1 price move then trend candles will form if price moves up $1 from a green Range US bar or down $1 from a red Range US bar. This is sufficient for lower priced assets; however, if you were trading, for instance, Bitcoin - a $1 price move can happen numerous times in one minute. This script can’t plot bars and record data until a 1-minute bar closes and a new 1-minute bar opens. Further, if Bitcoin moves up $1 twenty times and down $1 twenty times in a 1-minute bar - your Range US chart will record such variations as one price move. This data is inaccurate and likely useless.
To counter this quandary, a warning message will appear if you configure trend bar price moves or reversal bar price moves too low.
The image above shows the concealable warning message.
The image above is a flow diagram (made with shaky hands) illustrating the Range US bar formation process.
A google search will return additional information on the Range US chart type.
Volume Aggregation Bars
TradingView user and member of the TradingView Discord server @ferreirajames informed me of the Volume Aggregation chart type. The user commented in the "Suggestions" channel for the TradingView Discord server asking for the Volume Aggregation chart type. As an interim fix, I tried my hand at recreating the process, which is available in this script.
Similar to the Range US chart type, Volume Aggregation bars aren’t bound to a time-axis; the bars form after a user-defined, cumulative amount of volume is achieved or exceeded. Consequently, once the cumulative amount of volume is achieved or exceeded - a bar is produced at the corresponding price level.
Underlying theory: The chat type is conducive to identifying price levels where traders are “trapped”. Whether the process adequately distinguishes this circumstance is to your discretion.
The image above exemplifies the Volume Aggregation chart type.
Regardless of the current price, Volume Aggregation bars for after a requisite amount of volume is achieved/exceeded. Tick data isn't used; therefore, remainder values are carry over.
By default, the script automatically calculates a proportional cumulative volume total to dictate the formation of Volume Aggregation bars. However, the cumulative threshold is configurable.
The image above shows Volume Aggregation bars forming subsequent a user-defined cumulative volume total being exceeded.
Note: This chart type uses OHLC data from the timeframe of your chart. Therefore, for instance, setting the volume threshold too low will produce inaccurate, useless data.
A warning message will appear for such occurrence.
Gaps
The indicator incorporates a "Gaps" chart type.
The image above shows accompanying features.
A list of all unfilled gaps is accessible - gaps for this list are sorted by distance from current price.
Partially filled gaps are displayed in the corresponding gap box - the percentage amount the gap was filled is also displayed.
Gap statistics show:
# of Gaps
# of Up Gaps
# of Down Gaps
Average # of bars to fill Up Gaps
Average # of bars to dill Down Gaps
Average Gap Up % increase
Average Gap Down % decrease
Cumulative % increase of all Up Gaps
Cumulative % decrease of all Down Gaps
Naturally, there may be gaps formed thousands of bars ago that aren't close to price. Showing these gaps on the chart will "scrunch" the y-axis and make prices indistinguishable.
I've added a setting that allows the user to hide gaps that are "n" % away from the current price. The gap, if unfilled, will reappear when price trades within the user-defined percentage.
The image above shows an example. There's an unfilled down gap that's "hidden" because the current price is a further % away from price than what I've specified in the settings (1%). When prices trade back within 1% of the gap - it will reappear.
The image above shows the process in action. Prices moved back within 1% (can be any %) of the gap; therefore, it reappeared on the chart.
You can also set the % distance a gap must achieve for it to be considered a gap, recorded and plotted. Additionally, you can select to "visualize" gaps. Similar to the Range US chart and the Volume Aggregation chart, this setting will bars reflecting the most recent sequence of gaps - date and percentage distance of the gap are superimposed atop the bar.
Let me know if there's anything else you'd like included!
Note: The initial compilation time for this script is.... high. However, once the script's compiled, calculation load times are quick and you can sift through assets and timeframes relatively quick.
There's also a setting to "Improve Load Times" in the user-inputs table. This setting only improves the load times for post-compilation calculations and plots. The initial compilation load time is unchanged. Simply, once the indicator has "first loaded", all subsequent loads are quick.
Thank you! (:
Cup & HandleHi, here is my take on 'Cup & Handle'
Pivot Points - ph (highest points in a certain period) are stored in an array
When there is a new ph , previous ph's are compared to the latest one.
A temporary test line is drawn between these 2 points.
The script checks if a close (between these 2 points) doesn't break above this test line.
(test line is deleted afterwards)
If it doesn't, and the '% max breaks' are not breached, 2 circle shaped lines are drawn
(Top & Bottom line of the cup) which forms the Cup, together with the Handle.
The red box (Handle) is the maximum 33-50% retracement (% of cup height)
-> Only the latest pattern is shown, enabling 'Show Cup labels' shows the position of cup patterns in history.
They can be visualised by using 'Bar Replay'
'% max breaks' -> 'maximum highs/lows breaking through the Top/Bottom line
(% of bars between left & right extreme points of the Cup)
Settings:
- 'Left', 'Right' -> regulates Pivot Point values
- 'PP back' -> max lookback for Pivot High
More explanation can be found in following print screens,
or by checking the tooltips in the settings
Cheers!
Blockchain Fundamentals - Active Address Sentiment Osc. [CR]Blockchain Fundamentals: Active Address Sentiment Oscillator AASO
Back with another script today, this one is a useful tool in helping to determine bitcoins value. We are looking at 2 data sources: the daily active addresses on the BTC blockchain, and the daily returns of BTC.
THIS INDICATOR WILL ONLY GIVE YOU THE CORRECT RESULTS ON THE DAILY TIMEFRAME
There is an interesting relationship that you can see by comparing the two timeseries. But for us to create a good indicator we first need to normalize the data. So we look at the percent change over the past 28 days for each metric (DAA and price).
THIS INDICATOR WILL ONLY GIVE YOU THE CORRECT RESULTS ON THE DAILY TIMEFRAME
We then calculate standard deviation bands around the DAA metric. We finalize them by averaging the bands over a 28 day period.
When the Price series (yellow line) is higher than the SD bands BTC is considered overvalued or price is overheated. A pullback could be expected soon. When the Price series is below the SD bands BTC is considered undervalued or price is oversold.
THIS INDICATOR WILL ONLY GIVE YOU THE CORRECT RESULTS ON THE DAILY TIMEFRAME
This tool doesnt give signals on the one minute chart or tell you exactly when to buy or sell. BUT what it does do is act as a convenient macro sentiment indicator that is not based completely upon price.
In an attempt to narrow down the really juicy areas, if you seen the background color highlights with white, that means its likely a top or bottom. At the very least on a local sense and many times in a cyclical macro sense as well. It also narrows down the signal to a generally more profitable area.
This indicator is not meant to be used on timeframes other than daily (did I mention that already?). I am lazy and did not code the calculations to be MTF (which is why you have to use on the daily chart). If you want to code this, please forward it on to me and I will post an update with a heartfelt credit to you.
Gann Square of 144This indicator will create lines on the chart based on W.D. Gann's Square of 144. All the inputs will be detailed below
Why create this indicator?
I didn't find it on Tradingview (at least with open source). But the main reason is to study the strategy and be able to draw it fast. Manually drawing the square is not hard, but moving all together to the right spots and scale was time-consuming.
It has a lot of inputs...
Yes, each square point divisible by 6 has information with some options, so the user can create any configuration he wants. Also, it has the advantage of having the square built in seconds and adjusting itself on each new calculation.
About the inputs
Starting Date
This input will be used when the "Set Upper/Lower Prices and Start Bar Automatically" checkbox is not selected. The indicator will calculate all the line locations on the chart using the selected start date. When selecting this input, change the Manual Max and Min Prices to the better calculation
Manual Max/Min Price
This input will be used when the "Set Upper/Lower Prices and Start Bar Automatically" checkbox is not selected. The indicator will calculate all the line's locations on the chart using these prices
Set Upper/Lower Prices and Start Bar Automatically
Selects if the starting date will be automatically selected by the system or based on the input data. When it's set, the indicator will use the most recent bar as the middle point of the square, using the higher price as the Upper Price and the lowest price as the Lower Price in the latest 72 bars (or more based on the Candles Per Division parameter)
Update at a new bar
When this option is market, the indicator will update all created lines to match the new bar position, together with all the possible new Upper/Lower prices. Let it unchecked to watch the progression of the price while the square remains fixed in the chart.
Top X-Axis
When checked, it will display the labels on the Top of the square
Bottom X-Axis
When checked, it will display the labels on the Bottom of the square
Left X-Axis
When checked, it will display the labels on the left of the square
Right X-Axis
When checked, it will display the labels on the right of the square
Show Prices on the Right Y-Axis
When checked, it will display the prices together with the labels on the right of the square
Show Vertical Divisions
Show the lines that will divide the square into 9 equal parts
Show Extra Lines
Show unique lines that will come from the Top and bottom middle of the square, connecting the center to the 36 and 108 levels
Show Grid
When selected, it will display a grid in the square
Line Patterns
A selector with some options of built-in lines configuration. When any option besides None is selected, it will override the lines inputs below
Numbers Color
Select the color of each number on the Axis
Vertical Lines Color
Select the color of the vertical lines
Grid Color
Select the grid line color
Connections from corners to N
Each corner is represented by 2 characters, so they all fit in a single line
It will indicate where the line starts and where it ends
┏ ↓ = Top Left to Bottom
┏ → = Top Left to Right
┗ ↑ = Bottom Left to Top
┗ → = Bottom Left to Right
┓ ← = Top Right to Left
┓ ↓ = Top Right to Bottom
┛ ← = Bottom Right to Left
┛ ↑ = Bottom Right to Top
Besides selecting what line will be created, it's possible to select the color, the style, and the extension
How to use this indicator
When you dig into Gann's books for more information about the square of 144, you find that it was part of his setup with multiple indicators (technical and fundamental, and astrological). It is not a "one indicator" setup, so it's hard to say that you will find entries, exits, stop loss, and take profit in this. Still, it will help see trendiness, support, and resistance levels.
Mixing this with other indicators is probably a good idea, but some may find this indicator the only one needed.
Some aspects of the square
The end of the square is important, so where it starts is crucial. The end is important because it is where the price and time expire. The other parts of the square are defined based on their start and end, so placing them right is essential.
So, where to set the start of the square?
The last major low is the most indicated. The minimum price will be the lowest, and the max price will be the last major Top. Note that the indicator uses 1 candle on each point.
After finding the start, the minimum, and the maximum prices for the square, it will draw all lines. Another essential part of the square is The Midpoint.
The midpoint is the most crucial part of the square and is the best way to see if you positioned the square correctly. When the price is inside the square, using the starting candle as the start, a second higher low or a lower high occurs in that spot. When using the Vertical lines in the indicator, it's the middle square inside Gann's square.
The other divisions will be opposing each other most of the time. So if the price is rising in the 1/3 of the square, it's common to see the price fall in the 3/3 of the square.
More information about these aspects here
Considerations
This indicator was meant for price targets and a time calculator for possible support/resistances in the chart. It was created by William Delbert Gann and was part of his setup for trading almost a century ago. The lines will form geometric figures, which Gann used with high accuracy to predict tops/bottoms and when they would occur.
Annual Returns % Comparison [By MUQWISHI]Overview
The Annual Returns % Comparison indicator aimed to compare the historical annual percentage change of any two symbols. The indicator output shows a column-plot that was developed by two using a pine script table, so each period has pair columns showing the yearly percentage change for entered symbols.
Features
- Enter date range.
- Fill up with any two symbols.
- Choose the output data whether adjusted or not.
- Change the location of the table plot
- Color columns by a symbol.
- Size the height and width of columns.
- Color background, border, and text.
- The tooltip of the column value appears once the cursor sets above the specific column. As it seen below.
Let me know if you have any questions.
Thanks.
R:R Trading System FrameworkFirst off, huge thanks to @fikira! He was able to adapt what I built to work much more efficiently, allowing for more strategies to be used simultaneously. Simply put, I could not have gotten to this point without you. Thanks for what you do for the TV community. Second, I am fairly new to pinescript writing, so I welcome criticism, thoughtful input and improvement suggestions. I would love to grow this concept into something even better, if possible. So please let me know if you have any ideas for improvement. However I do juggle a lot of different things outside of TV, so implementations may be delayed.
I have decided, at this time, not to add alerts. First, because I feel most people looking to adapt this framework can add their own pretty easily. Also, given how customized the framework is currently, while also attempting to account for all the possible ways in which people may want alerts to function after they customize it, it seems best to leave them out as it doesn't exactly fit the idea of a framework.
For best viewing, I recommend hovering over the script's name > ... > Visual order > Bring to front. Also I found hollow candles with mono-toned colors (like pictured) are more visually appealing for me personally. I HIGHLY RECOMMEND USING WITH BAR REPLAY TO BETTER UNDERSTAND THE FRAMEWORK'S FUNCTIONALITY.
▶️ WHAT THIS FRAMEWORK IS
- A huge collection of concepts and capabilities for those trying to better understand, learn, or teach pinescript.
- A system designed to showcase Risk:Reward concepts more holistically by providing all of the most popular components of retail trading to include backtesting, trade visual plotting, position tracking, market condition shifts, and useful info while positioned to help highlight changes in your risk:reward based decision-making processes.
- A system that can showcase individual strategies regardless of trade direction, allowing you to develop hedging strategies without having multiple indicators that do not correlate with each other.
- Designed around the idea that you trade less numbers of assets but manage your positions and risk based on multiple concurrently running strategies to manage your risk exposure and reward potential.
- An attempt to combine all the things you need to execute with an active trading management style.
- A framework that uses backtested results (in this case the number of averaged bars it takes to hit key levels) in real-time to inform your risk:reward decision-making while in-trade (in this case in your Trade Tracking Table using dynamic color to show how you might be early, on-time, or late compared to the average amount of backtested time it normally takes to hit that specific key level).
▶️ WHAT THIS FRAMEWORK IS NOT
- A complete trading product. DO NOT USE as-is. It is a FRAMEWORK for you to generate ideas of your own and fairly easily implement your own triggering conditions in the appropriate sections of the script.
▶️ USE CASES
- If you decide you like the Stop, Target, Trailing Stop, and Risk:Reward components as-is, then just understanding how to plug in your Entry and Bullish / Bearish conditions (Triangles) and adjust the input texts to match your custom naming will be all you need to make it your own!
- If you want to adapt certain components, then this system gives you a great starting point to adapt your different concepts and ideas from.
▶️ SYSTEM COMPONENTS
- Each of the system's components are described via tooltips both in the input menu and in the tables' cells.
- Each label on the chart displays the corresponding price at those triggered conditions on hover with tooltips.
- The Trailing Stop only becomes active once it is above the Entry Price for that trade, and brightens to show it is active. The STOP line (right of price) moves once it takes over for the Entry Stop representing the level of the Trailing Stop at that time for that trade.
- The Lines / Labels to the right of price will brighten once price is above for Longs or below for Shorts. The Trade Tracking Table cells will add ☑️ once price is above for Longs or below for Shorts.
- The brighter boxes on the chart show the trades that occurred based on your criteria and are color coded for all components of each trade type to ensure your references are consistent. (Defaults are TV built-in strategies)
- The lighter boxes on the chart show the highest and lowest price levels reached during those trades, to highlight areas where improvements can be made or additional considerations can be accounted for by either adjusting Entry triggers or Bullish / Bearish triggers.
- Default Green and Red Triangles (Bullish / Bearish) default to having the same triggering condition as the Entry it corresponds to. This is to highlight either a pyramiding concept, early exit, or you can change to account for other things occurring during your trades which could help you with Stop and Target management/considerations.
TradingView and many of its community members have done a lot for me, so this is my attempt to give back.
Bjorgum Double Tap█ OVERVIEW
Double Tap is a pattern recognition script aimed at detecting Double Tops and Double Bottoms. Double Tap can be applied to the broker emulator to observe historical results, run as a trading bot for live trade alerts in real time with entry signals, take profit, and stop orders, or to simply detect patterns.
█ CONCEPTS
How Is A Pattern Defined?
Doubles are technical formations that are both reversal patterns and breakout patterns. These formations typically have a distinctive “M” or a “W” shape with price action breaking beyond the neckline formed by the center of the pattern. They can be recognized when a pivot fails to break when tested for a second time and the retracement that follows breaks beyond the key level opposite. This can trap entrants that were playing in the direction of the prior trend. Entries are made on the breakout with a target projected beyond the neckline equal to the height of the pattern.
Pattern Recognition
Patterns are recognized through the use of zig-zag; a method of filtering price action by connecting swing highs and lows in an alternating fashion to establish trend, support and resistance, or derive shapes from price action. The script looks for the highest or lowest point in a given number of bars and updates a list with the values as they form. If the levels are exceeded, the values are updated. If the direction changes and a new significant point is made, a new point is added to the list and the process starts again. Meanwhile, we scan the list of values looking for the distinctive shape to form as previously described.
█ STRATEGY RESULTS
Back Testing
Historical back testing is the most common method to test a strategy due in part to the general ease of gathering quick results. The underlying theory is that any strategy that worked well in the past is likely to work well in the future, and conversely, any strategy that performed poorly in the past is likely to perform poorly in the future. It is easy to poke holes in this theory, however, as for one to accept it as gospel, one would have to assume that future results will match what has come to pass. The randomness of markets may see to it otherwise, so it is important to scrutinize results. Some commonly used methods are to compare to other markets or benchmarks, perform statistical analysis on the results over many iterations and on differing datasets, walk-forward testing, out-of-sample analysis, or a variety of other techniques. There are many ways to interpret the results, so it is important to do research and gain knowledge in the field prior to taking meaningful conclusions from them.
👉 In short, it would be naive to place trust in one good backtest and expect positive results to continue. For this reason, results have been omitted from this publication.
Repainting
Repainting is simply the difference in behaviour of a strategy in real time vs the results calculated on the historical dataset. The strategy, by default, will wait for confirmed signals and is thus designed to not repaint. Waiting for bar close for entires aligns results in the real time data feed to those calculated on historical bars, which contain far less data. By doing this we align the behaviour of the strategy on the 2 data types, which brings significance to the calculated results. To override this behaviour and introduce repainting one can select "Recalculate on every tick" from the properties tab. It is important to note that by doing this alerts may not align with results seen in the strategy tester when the chart is reloaded, and thus to do so is to forgo backtesting and restricts a strategy to forward testing only.
👉 It is possible to use this script as an indicator as opposed to a full strategy by disabling "Use Strategy" in the "Inputs" tab. Basic alerts for detection will be sent when patterns are detected as opposed to complex order syntax. For alerts mid-bar enable "Recalculate on every tick" , and for confirmed signals ensure it is disabled.
█ EXIT ORDERS
Limit and Stop Orders
By default, the strategy will place a stop loss at the invalidation point of the pattern. This point is beyond the pattern high in the case of Double Tops, or beneath the pattern low in the case of Double Bottoms. The target or take profit point is an equal-legs measurement, or 100% of the pattern height in the direction of the pattern bias. Both the stop and the limit level can be adjusted from the user menu as a percentage of the pattern height.
Trailing Stops
Optional from the menu is the implementation of an ATR based trailing stop. The trailing stop is designed to begin when the target projection is reached. From there, the script looks back a user-defined number of bars for the highest or lowest point +/- the ATR value. For tighter stops the user can look back a lesser number of bars, or decrease the ATR multiple. When using either Alertatron or Trading Connector, each change in the trail value will trigger an alert to update the stop order on the exchange to reflect the new trail price. This reduces latency and slippage that can occur when relying on alerts only as real exchange orders fill faster and remain in place in the event of a disruption in communication between your strategy and the exchange, which ensures a higher level of safety.
👉 It is important to note that in the case the trailing stop is enabled, limit orders are excluded from the exit criteria. Rather, the point in time that the limit value is exceeded is the point that the trail begins. As such, this method will exit by stop loss only.
█ ALERTS
Five Built-in 3rd Party Destinations
The following are five options for delivering alerts from Double Tap to live trade execution via third party API solutions or chat bots to share your trades on social media. These destinations can be selected from the input menu and alert syntax will automatically configure in alerts appropriately to manage trades.
Custom JSON
JSON, or JavaScript Object Notation, is a readable format for structuring data. It is used primarily to transmit data between a server and a web application. In regards to this script, this may be a custom intermediary web application designed to catch alerts and interface with an exchange API. The JSON message is a trade map for an application to read equipped with where its been, where its going, targets, stops, quantity; a full diagnostic of the current state and its previous state. A web application could be configured to follow the messages sent in this format and conduct trades in sync with alerts running on the TV server.
Below is an example of a rendered JSON alert:
{
"passphrase": "1234",
"time": "2022-05-01T17:50:05Z",
"ticker": "ETHUSDTPERP",
"plot": {
"stop_price": 2600.15,
"limit_price": 3100.45
},
"strategy": {
"position_size": 0.1,
"order_action": "buy",
"market_position": "long",
"market_position_size": 0,
"prev_market_position": "flat",
"prev_market_position_size": 0
}
}
Trading Connector
Trading Connector is a third party fully autonomous Chrome extension designed to catch alert webhooks from TradingView and interface with MT4/MT5 to execute live trades from your machine. Alerts to Trading Connector are simple; just select the destination from the input drop down menu, set your ticker in the "TC Ticker" box in the "Alert Strings" section and enter your URL in the alert window when configuring your alert.
Alertatron
Alertatron is an automated algo platform for cryptocurrency trading that is designed to automate your trading strategies. Although the platform is currently restricted to crypto, it offers a versatile interface with high flexibility syntax for complex market orders and conditions. To direct alerts to Alertatron, select the platform from the 3rd party drop down, configure your API key in the ”Alertatron Key” box and add your URL in the alert message box when making alerts.
3 Commas
3 Commas is an easy and quick to use click-and-go third party crypto API solution. Alerts are simple without overly complex syntax. Messages are simply pasted into alerts and executed as alerts are triggered. There are 4 boxes at the bottom of the "Inputs" tab where the appropriate messages to be placed. These messages can be copied from 3 Commas after the bots are set up and pasted directly into the settings menu. Remember to select 3 Commas as a destination from the third party drop down and place the appropriate URL in the alert message window.
Discord
Some may wish to share their trades with their friends in a Discord chat via webhook chat bot. Messages are configured to notify of the pattern type with targets and stop values. A bot can be configured through the integration menu in a Discord chat to which you have appropriate access. Select Discord from the 3rd party drop down menu and place your chat bot URL in the alert message window when configuring alerts.
👉 For further information regarding alert setup, refer to the platform specific instructions given by the chosen third party provider.
█ IMPORTANT NOTES
Setting Alerts
For alert messages to be properly delivered on order fills it is necessary to place the following placeholder in the alert message box when creating an alert.
{{strategy.order.alert_message}}
This placeholder will auto-populate the alert message with the appropriate syntax that is designated for the 3rd party selected in the user menu.
Order Sizing and Commissions
The values that are sent in alert messages are populated from live metrics calculated by the strategy. This means that the actual values in the "Properties" tab are used and must be set by the user. The initial capital, order size, commission, etc. are all used in the calculations, so it is important to set these prior to executing live trades. Be sure to set the commission to the values used by the exchange as well.
👉 It is important to understand that the calculations on the account size take place from the beginning of the price history of the strategy. This means that if historical results have inflated or depleted the account size from the beginning of trade history until now, the values sent in alerts will reflect the calculated size based on the inputs in the "Properties" tab. To start fresh, the user must set the date in the "Inputs" tab to the current date as to remove trades from the trade history. Failure to follow this instruction can result in an unexpected order size being sent in the alert.
█ FOR PINECODERS
• With the recent introduction of matrices in Pine, the script utilizes a matrix to track pivot points with the bars they occurred on, while tracking if that pivot has been traded against to prevent duplicate detections after a trade is exited.
• Alert messages are populated with placeholders ; capability that previously was only possible in alertcondition() , but has recently been extended to `strategy.*()` functions for use in the `alert_message` argument. This allows delivery of live trade values to populate in strategy alert messages.
• New arguments have been added to strategy.exit() , which allow differentiated messages to be sent based on whether the exit occurred at the stop or the limit. The new arguments used in this script are `alert_profit` and `alert_loss` to send messages to Discord
Fourier Extrapolator of Price w/ Projection Forecast [Loxx]Due to popular demand, I'm pusblishing Fourier Extrapolator of Price w/ Projection Forecast.. As stated in it's twin indicator, this one is also multi-harmonic (or multi-tone) trigonometric model of a price series xi, i=1..n, is given by:
xi = m + Sum( a*Cos(w*i) + b*Sin(w*i), h=1..H )
Where:
xi - past price at i-th bar, total n past prices;
m - bias;
a and b - scaling coefficients of harmonics;
w - frequency of a harmonic ;
h - harmonic number;
H - total number of fitted harmonics.
Fitting this model means finding m, a, b, and w that make the modeled values to be close to real values. Finding the harmonic frequencies w is the most difficult part of fitting a trigonometric model. In the case of a Fourier series, these frequencies are set at 2*pi*h/n. But, the Fourier series extrapolation means simply repeating the n past prices into the future.
This indicator uses the Quinn-Fernandes algorithm to find the harmonic frequencies. It fits harmonics of the trigonometric series one by one until the specified total number of harmonics H is reached. After fitting a new harmonic , the coded algorithm computes the residue between the updated model and the real values and fits a new harmonic to the residue.
see here: A Fast Efficient Technique for the Estimation of Frequency , B. G. Quinn and J. M. Fernandes, Biometrika, Vol. 78, No. 3 (Sep., 1991), pp . 489-497 (9 pages) Published By: Oxford University Press
The indicator has the following input parameters:
src - input source
npast - number of past bars, to which trigonometric series is fitted;
Nfut - number of predicted future bars;
nharm - total number of harmonics in model;
frqtol - tolerance of frequency calculations.
The indicator plots two curves: the green/red curve indicates modeled past values and the yellow/fuchsia curve indicates the modeled future values.
The purpose of this indicator is to showcase the Fourier Extrapolator method to be used in future indicators.
VisibleChart█ OVERVIEW
This library is a Pine programmer’s tool containing functions that return values calculated from the range of visible bars on the chart.
This is now possible in Pine Script™ thanks to the recently-released chart.left_visible_bar_time and chart.right_visible_bar_time built-ins, which return the opening time of the leftmost and rightmost bars on the chart. These values update as traders scroll or zoom their charts, which gives way to a class of indicators that can dynamically recalculate and draw visuals on visible bars only, as users scroll or zoom their charts. We hope this library's functions help you make the most of the world of possibilities these new built-ins provide for Pine scripts.
For an example of a script using this library, have a look at the Chart VWAP indicator.
█ CONCEPTS
Chart properties
The new chart.left_visible_bar_time and chart.right_visible_bar_time variables return the opening time of the leftmost and rightmost bars on the chart. They are only two of many new built-ins in the `chart.*` namespace. See this blog post for more information, or look them up by typing "chart." in the Pine Script™ Reference Manual .
Dynamic recalculation of scripts on visible bars
Any script using chart.left_visible_bar_time or chart.right_visible_bar_time acquires a unique property, which triggers its recalculation when traders scroll or zoom their charts in such a way that the range of visible bars on the chart changes. This library's functions use the two recent built-ins to derive various values from the range of visible bars.
Designing your scripts for dynamic recalculation
For the library's functions to work correctly, they must be called on every bar. For reliable results, assign their results to global variables and then use the variables locally where needed — not the raw function calls.
Some functions like `barIsVisible()` or `open()` will return a value starting on the leftmost visible bar. Others such as `high()` or `low()` will also return a value starting on the leftmost visible bar, but their correct value can only be known on the rightmost visible bar, after all visible bars have been analyzed by the script.
You can plot values as the script executes on visible bars, but efficient code will, when possible, create resource-intensive labels, lines or tables only once in the global scope using var , and then use the setter functions to modify their properties on the last bar only. The example code included in this library uses this method.
Keep in mind that when your script uses chart.left_visible_bar_time or chart.right_visible_bar_time , your script will recalculate on all bars each time the user scrolls or zooms their chart. To provide script users with the best experience you should strive to keep calculations to a minimum and use efficient code so that traders are not always waiting for your script to recalculate every time they scroll or zoom their chart.
Another aspect to consider is the fact that the rightmost visible bar will not always be the last bar in the dataset. When script users scroll back in time, a large portion of the time series the script calculates on may be situated after the rightmost visible bar. We can never assume the rightmost visible bar is also the last bar of the time series. Use `barIsVisible()` to restrict calculations to visible bars, but also consider that your script can continue to execute past them.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
barIsVisible()
Condition to determine if a given bar is within the users visible time range.
Returns: (bool) True if the the calling bar is between the `chart.left_visible_bar_time` and the `chart.right_visible_bar_time`.
high()
Determines the value of the highest `high` in visible bars.
Returns: (float) The maximum high value of visible chart bars.
highBarIndex()
Determines the `bar_index` of the highest `high` in visible bars.
Returns: (int) The `bar_index` of the `high()`.
highBarTime()
Determines the bar time of the highest `high` in visible bars.
Returns: (int) The `time` of the `high()`.
low()
Determines the value of the lowest `low` in visible bars.
Returns: (float) The minimum low value of visible chart bars.
lowBarIndex()
Determines the `bar_index` of the lowest `low` in visible bars.
Returns: (int) The `bar_index` of the `low()`.
lowBarTime()
Determines the bar time of the lowest `low` in visible bars.
Returns: (int) The `time` of the `low()`.
open()
Determines the value of the opening price in the visible chart time range.
Returns: (float) The `open` of the leftmost visible chart bar.
close()
Determines the value of the closing price in the visible chart time range.
Returns: (float) The `close` of the rightmost visible chart bar.
leftBarIndex()
Determines the `bar_index` of the leftmost visible chart bar.
Returns: (int) A `bar_index`.
rightBarIndex()
Determines the `bar_index` of the rightmost visible chart bar.
Returns: (int) A `bar_index`
bars()
Determines the number of visible chart bars.
Returns: (int) The number of bars.
volume()
Determines the sum of volume of all visible chart bars.
Returns: (float) The cumulative sum of volume.
ohlcv()
Determines the open, high, low, close, and volume sum of the visible bar time range.
Returns: ( ) A tuple of the OHLCV values for the visible chart bars. Example: open is chart left, high is the highest visible high, etc.
chartYPct(pct)
Determines a price level as a percentage of the visible bar price range, which depends on the chart's top/bottom margins in "Settings/Appearance".
Parameters:
pct : (series float) Percentage of the visible price range (50 is 50%). Negative values are allowed.
Returns: (float) A price level equal to the `pct` of the price range between the high and low of visible chart bars. Example: 50 is halfway between the visible high and low.
chartXTimePct(pct)
Determines a time as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
chartXIndexPct(pct)
Determines a `bar_index` as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
whenVisible(src, whenCond, length)
Creates an array containing the `length` last `src` values where `whenCond` is true for visible chart bars.
Parameters:
src : (series int/float) The source of the values to be included.
whenCond : (series bool) The condition determining which values are included. Optional. The default is `true`.
length : (simple int) The number of last values to return. Optional. The default is all values.
Returns: (float ) The array ID of the accumulated `src` values.
avg(src)
Gathers values of the source over visible chart bars and averages them.
Parameters:
src : (series int/float) The source of the values to be averaged. Optional. Default is `close`.
Returns: (float) A cumulative average of values for the visible time range.
median(src)
Calculates the median of a source over visible chart bars.
Parameters:
src : (series int/float) The source of the values. Optional. Default is `close`.
Returns: (float) The median of the `src` for the visible time range.
vVwap(src)
Calculates a volume-weighted average for visible chart bars.
Parameters:
src : (series int/float) Source used for the VWAP calculation. Optional. Default is `hlc3`.
Returns: (float) The VWAP for the visible time range.