Max drawdown daysA friendly reminder to myself and rest of the traders that market can stay low for prolonged time!!
Details are pretty simple.
Here is small comparison of the stats for major US indices.
Can also be applied to stocks. Cells are highlighted in red background ii
Drawdown/Recovery is still in progress for historical stats
Current drawdown bars/recovery bars are higher than that of median of All time stats.
Hewhomustnotbenamed
eHarmonicpatternsExtendedLibrary "eHarmonicpatternsExtended"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations. Republishing as new library instead of existing eHarmonicpatterns because I need that copy for existing scripts.
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, b, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, b, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on BCD and XAD ranges
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj) Provides PRZ range based on XAD range only
Parameters:
x : X coordinate value
a : A coordinate value
b : B coordinate value
c : C coordinate value
patternArray : Pattern flags for which PRZ range needs to be calculated
errorPercent : Error threshold
start_adj : - Adjustments for entry levels
end_adj : - Adjustments for stop levels
Returns: Start and end of consolidated PRZ range
Historical Range (Using eStrategy library)⬜ The script is intended to cover few things.
▶ Strategy testing framework based on eStrategy library
▶ Using historicalrange of values for identifying better entry and exits.
This is also built on top of the Systematic Investment Plan script published here
⬜ Strategy testing framework
Strategy testing framework is different from tradingview default strategy testing from few ways to suit the needs of systematic investments.
▶ Supports recurring investment on top of initial investment to emulate adding further funds to the investment bucket on regular basis.
▶ Better calculation of drawdowns based on daily equity rather than drawdown calculated only on close of trade.
▶ Provides better control over how much strategy can reduce and reload
Having said that, this framework is not intended as replacement for tradingview strategy framework. It is not as comprehensive as tradingview strategy framework. But, created to address few specific styles of strategy.
▶ No detailed trade stats on individual trades. But, this can be implemented in future versions
▶ At present only facilitates long positions.
▶ UI features such as plotting trades on chart are not available.
▶ Does not take into consideration of slippage and brokerage - this is not an issue because the framework is not meant for short term trades. It is only made for daily timeframes.
▶ No pyramiding or leverage possible.
And many more...
Framework can be used for similar strategies based on market timing with few small changes.
⬜ Historical Range Strategy
Concept here is, instead of taking indicators such as oscillators as is, use historical percentile to derive better oversold and overbought conditions. Strategy provides different options to base historical range. This can either be based on
▶ Band percent
▶ Oscillator
Different choices of bands and oscillators are also available to chose. However, have not done extensive testing on all the combinations.
⬜ Settings
▶ Initial and recurring investment settings (As confirm inputs)
▶ Buy and hold and strategy specific settings to be used for stat calculation
▶ Band and oscillator parameters
These are straightforward parameters which is used for defining the base of either bands or oscillators.
▶ Percentile moving average parameter
Percentile MA is used with Percentile to find entry and exit signals based on crossover and crossunder.
Feedbacks and suggestions welcome.
eStrategyLibrary "eStrategy"
Library contains methods which can help build custom strategy for continuous investment plans and also compare it with systematic buy and hold.
sip(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice) Depicts systematic buy and hold over period of time
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalEquity - Present equity
customStrategy(startYear, initialDeposit, depositFrequency, recurringDeposit, buyPrice, sellPrice, initialInvestmentPercent, recurringInvestmentPercent, signal, tradePercent) Allows users to define custom strategy and enhance systematic buy and hold by adding take profit and reloads
Parameters:
startYear : Year on which SIP is started
initialDeposit : Initial one time investment at the start
depositFrequency : Frequency of recurring deposit - can be monthly or weekly
recurringDeposit : Recurring deposit amount
buyPrice : Indicatinve buy price. Use high to be conservative. low, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
sellPrice : Indicatinve sell price. Use low to be conservative. high, close, open, hl2, hlc3, ohlc4, hlcc4 are other options.
initialInvestmentPercent : percent of amount to invest from the initial depost. Keep rest of them as cash
recurringInvestmentPercent : percent of amount to invest from recurring deposit. Keep rest of them as cash
signal : can be 1, -1 or 0. 1 means buy/reload. -1 means take profit and 0 means neither.
tradePercent : percent of amount to trade when signal is not 0. If taking profit, it will sell the percent from existing position. If reloading, it will buy with percent from cash reserve
Returns: totalInvestment - initial + recurring deposits
totalQty - Quantity of units held for given instrument
totalCash = Amount of cash held
totalEquity - Overall equity = totalQty*close + totalCash
Systematic Investment PlanTradingview default strategy tester has few limitations. To name some:
Tradingview default strategy tester does not have option for periodic investment.
Does not allow reduce and refill kind of operations.
Comparison to buy and hold equity does not take into consideration on number of days invested
Hence, I created this as base for my further experiments with respect to strategies involving market timing.
Settings are quite simple and self explanatory.
historicalrangeLibrary "historicalrange"
Library provices a method to calculate historical percentile range of series.
hpercentrank(source) calculates historical percentrank of the source
Parameters:
source : Source for which historical percentrank needs to be calculated. Source should be ranging between 0-100. If using a source which can beyond 0-100, use short term percentrank to baseline them.
Returns: pArray - percentrank array which contains how many instances of source occurred at different levels.
upperPercentile - percentile based on higher value
lowerPercentile - percentile based on lower value
median - median value of the source
max - max value of the source
distancefromath(source) returns stats on historical distance from ath in terms of percentage
Parameters:
source : for which stats are calculated
Returns: percentile and related historical stats regarding distance from ath
distancefromma(maType, length, source) returns stats on historical distance from moving average in terms of percentage
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
source : for which stats are calculated
Returns: percentile and related historical stats regarding distance from ath
bpercentb(source, maType, length, multiplier, sticky) returns percentrank and stats on historical bpercentb levels
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Bollinger Percent B
kpercentk(source, maType, length, multiplier, useTrueRange, sticky) returns percentrank and stats on historical kpercentk levels
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Keltener Percent K
dpercentd(useAlternateSource, alternateSource, length, sticky) returns percentrank and stats on historical dpercentd levels
Parameters:
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
length : - donchian channel length
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: percentile and related historical stats regarding Donchian Percent D
oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky) oscillator - returns Choice of oscillator with custom overbought/oversold range
Parameters:
type : - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
length : - Oscillator length - not used for TSI
shortLength : - shortLength only used for TSI
longLength : - longLength only used for TSI
source : - custom source if required
highSource : - custom high source for stochastic oscillator
lowSource : - custom low source for stochastic oscillator
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
sticky : - overbought, oversold levels won't change unless crossed
Returns: percentile and related historical stats regarding oscillator
Manual Harmonic Projections - With interactive inputsThis is another script involving interactive inputs. This is similar to Manual-Harmonic-Patterns-With-interactive-inputs . But, instead of taking XABCD and verifying if it confirms to any pattern, here we only take XABC and project all PRZs.
Example, upon adding the script to chart, it will prompt to select 4 points on chart by clicking on it. if we select X, A, B, C as shown in the chart below, we can see the projection of multiple PRZs. Mid of nearest PRZ is considered as D and rest of the pattern is drawn based on this. However, the pattern can have multiple PRZs. All overlapping PRZs are combined together and shown as one along with merged pattern labels. But, if there is gap between PRZs, they are shown separately.
If no projections found, then patterns and projections are not drawn. However, you can still see XABC lines on the chart.
Manual Harmonic Patterns - With interactive inputsThis script is a drawing tool which allows users to draw XABCD on the chart and script will tell whether there is any harmonic patterns on the drawings made. The script is based on interactive inputs and requires users to chose XABCD points.
Please note
This is not a scanner and it will not scan historical bars for harmonic patterns. This needs to be used rather as drawing tool instead.
Script will not check if selected pivots are correct. It assumes users to know how to select the right XABCD based on pivot high/lows. Bullish pattern will have X, B and D as pivot lows and A,C as pivot highs. Similarly bearish patterns will have X, B, D as pivot highs and A, C as pivot lows.
Script will not check for overflow conditions. For example, if price crosses, XB or BD line, then pattern is considered to be invalid. But, this check cannot be made in this script and we require users to be aware of this condition and select input accordingly.
Order of inputs should be in ascending order. X pivot should come before A and then, B, C, D and F. This again is users responsibility to select pivots in right order.
What happens after selecting XABCD?
If selected pattern is valid harmonic pattern, it will
Draw XABCD lines and labels
Fill harmonic triangles
Show PRZ box which shoes the name of valid patterns.
If it is not valid harmonic pattern, then users will see blank XABCD line without any PRZ or filled harmonic triangles.
Example:
1. When it is valid pattern
2. When it is not valid pattern
eHarmonicpatternsLibrary "eHarmonicpatterns"
Library provides an alternative method to scan harmonic patterns. This is helpful in reducing iterations
scan_xab(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : AB/XA ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray) Checks if abc or axc ratio is in range of any harmonic pattern
Parameters:
abcRatio : BC/AB ratio
axcRatio : XC/AX ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_bcd(bcdRatio, err_min, err_max, patternArray) Checks if bcd ratio is in range of any harmonic pattern
Parameters:
bcdRatio : CD/BC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray) Checks if xad or xcd ratio is in range of any harmonic pattern
Parameters:
xadRatio : AD/XA ratio
xcdRatio : CD/XC ratio
err_min : minimum error threshold
err_max : maximum error threshold
patternArray : Array containing pattern check flags. Checks are made only if flags are true. Upon check flgs are overwritten.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
isHarmonicProjection(x, a, c, c, flags, errorPercent) Checks for harmonic pattern projection
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
X-Mas TreeLet's play a game!! Find your Christmas Tree and post it in the comments.
How to use the script?
Open any instrument which best describes the Christmas Tree (Preferably on hourly timeframe).
Apply X-Mas Tree script on the chart.
Enjoy the snowfall, changes in lightings and other animations. Animations only happen if the instrument is in trading session. So, stocks and indexes do not work on weekends and holidays. Use crypto as they are traded 24X7.
Unfortunately cannot post moving charts. But, snapshot of chart will do :)
Well, Please don't ask these questions for this script (Also thanks to @Bjorgum for contributing to this section) 😃
Can you please add alerts?
Does it repaint?
Can we use this for crypto/stock/forex bla bla?
Can you convert this to strategy?
How can I access this indicator?
Can you please give access or how much does it cost?
Can you make it available for MTF?
Indicator is broken. Getting so and so error message etc.
Wish you all MERRY X-MAS and HAPPY NEW YEAR!!
Supertrend - Ladder ATRThis is a supertrend with slight twisted concept which can be very benefecial in strong trending markets to reduce stop loss distance and exit slightly quicker.
⬜ Concept
▶ When the instrument is trending up, regular ATR shows high values if there are big green candles. This affect the stoploss distance in regular supertrend which leads to wide stops or delayed lagging. When you are in long trade, what matters for stoploss is how much a negative candle can move within bar. Hence, using ATR derived only based on red candles is more beneficial for trailing stops on long signals. Same applies to short trades where using ATR derived from only green candles is more efficient than overall ATR.
▶ ATR will be minimal when the volatility is less and ATR will increase with volatility. That means, once you are in trade, the trailing of stoploss also will vary based on ATR (or volatility). With regular ATR and supertrend, chances of stop loss distance widening is high with increased volatility even though stoploss levels will not move down. This again poses the risk of higher drawdown during trade closure and also keeps in the trade during ranging market. To avoid this, the second trick we are using here is only to reduce the atr stoploss difference when in trade. That is, when in long trade and negative candles ATR is increasing, we will not consider that. We will consider the new ATR only if it is lesser than previous bar ATR.
Effect of these changes on the trending market is quite visual. Lets take example of USDTRY
Settings are quite simple and does not vary much from regular supertrend settings.
Currency Strength Meter [HeWhoMustNotBeNamed]⬜ Note: This is not the strength of currency pairs. But, in this script we are trying to derive strength of individual currencies by matching against single base currency.
⬜ Process
This is based on similar concept as that of Magic Numbers for stocks. Idea is simple.
▶ Calculate strength of each currency against USD. Derive the strength for both price movement and volume movement.
▶ Similarly calculate momentum of price and volume change.
▶ If USD is base currency, inverse momentum and strength index for the given symbol.
▶ Once these calculations are done, rank each currencies based on individual score on given things.
▶ Add up all the ranks to derive combined rank
▶ sort the currencies in the ascending order of overall rank.
⬜ USAGE
▶ Identify a base currency. In our case, we have used USD as base currency as it is easy to get pairs of all currencies with USD.
▶ Identify most used combos for all other currencies which are paired with USD. Fx pair can either have USD as base currency or quote currency. It is desirable to use the pair which is most traded. For example, USDJPY is more traded pair than JPYUSD - hence it is advisable to use USDJPY instead of JPYUSD. Similarly AUDUSD is more traded than USDAUD - hence choosing AUDUSD for the purpose of this exercise is better approach. Notice that USDJPY has USD as base currency whereas AUDUSD has USD as quote currency. These calculations are handled internally to derive the right outcome irrespective of position of USD in the pair.
▶ Identify the forex broker which has all the selected forex tickers. All comparison is done against a single broker. Hence, choosing broker which does not wide range of forex pairs will show NAN for many rows.
▶ Once we set these, we get tabular output containing strength and oscillator based trend indexes for both price and volume indicator. Currencies are ordered in descending order of strength. Hence, top of the list can be considered as currency having highest strength and bottom of the table can be considered as currency having lowest strength. Please note that the calculation is valid only for selected timeframe and users can set other parameters such as moving average type, oscillator type, length etc which can alter the outcome.
▶ Use multiple timeframes to find out stronger and weaker currencies. Use directional indicators to understand where they are heading. Combine all these info to come up with currency pair you would like to trade :)
⬜ Settings
▶ Main settings and Currencies
Base Currency : This is set to USD by default as rest of the tickers used are paired with USD. Whatever the base currency is selected, rest of the tickers should follow the same combination.
Timeframe : Timeframe for which rankings need to be calculated.
Currencies : These should be the currency pair which involve base currency defined in the setting on either side.
▶ Display
Table : Allows users to set table location and size of the table. By default this is set to middle center and default size is normal. If user want to use multiple timeframes side by side, they can do so by changing these display settings.
Stat Type : To show either comparative ranking or actual indicator values
Crypto Volume/Strength ComparatorHello Traders,
Here is an attempt to perform comparative analysis between top cryptos based on strength (oscillator) and volume. Methodology used here is similar to Magic Number formula described in the post : Enhanced Magic Formula for fundamental analysis . But, instead of using fundamentals, we are making use of few technicals to derive similar outcome. Usage of the available stats will not be same as Magic number since we are using technicals.
⬜ Process
▶ Get crypto exchange based on prefix of instrument being used.
▶ For the given exchange, get data for all the tickers available in input fields.
▶ Calculate Oscillator, Momentum based on price for each tickers.
▶ Calculate Oscillator, Momentum based on volume for each tickers.
▶ Calculate Volatility for each tickers.
▶ Rank Price-Oscillator, Price-Momentum, Volume-Oscillator, Volume-Momentum, Volatility for each tickers.
▶ Calculate combined rank by adding up individual ranks.
▶ Calculate movement of rankings from bar to bar
▶ Sort tickers based on rank and populate them on table. Display direction of rankings.
⬜ Components
Display components are as follows:
⬜ Settings
Settings are pretty simple and straightforward
⬜ Calculations
▶ Oscillators : High values of oscillators are considered as ideal as the process is intended towards finding trend.
▶ Momentum : Momentum is calculated on the basis of Squeeze Momentum Indicator by @LazyBear.
▶ Volatility : Volatility is calculated on the basis of Williams Vix Fix by @ChrisMoody. Here too since we are in trend following mode, lower vix fix is considered ideal.
⬜ Few Notes
Tickers will show data only if selected exchange has them. Some tickers are not available in all exchanges. In that case, it will show NAN. This is kind of unavoidable as we need to have fixed size arrays for any calculations.
Indicator works only on crypto tickers which has valid exchange.
Tickers move through the rankings in real time. Background of all stats are based on gradient from green to red.
Tickers on top may not always have better long opportunity or tickers at bottom may not always be optimal for shorting. We need to consider how long the instrument may stay in the position or how fast it is moving in opposite direction. Hence, directions of the ranking movement are also shown on the table.
arrayutilsLibrary "_arrayutils"
Library contains utility functions using arrays.
delete(arr, index)
remove an item from array at specific index. Also deletes the item
Parameters:
arr : - array from which the item needs to be deleted
index : - index of item to be deleted
Returns: void
pop(arr)
remove the last item from array. Also deletes the item
Parameters:
arr : - array from which the last item needs to be removed and deleted
Returns: void
shift(arr)
remove an item from array at index 0. Also deletes the item
Parameters:
arr : - array from which the first item needs to be removed and deleted
Returns: void
unshift(arr, val, maxItems)
add an item to the beginning of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the other end
Returns: resulting array
clear(arr)
remove and delete all items in an array
Parameters:
arr : - array which needs to be cleared
Returns: void
push(arr, val, maxItems)
add an item to the end of an array with max items cap
Parameters:
arr : - array to which the item needs to be added at the beginning
val : - value of item which needs to be added
maxItems : - max items array can hold. After that, items are removed from the starting index
Returns: resulting array
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots : pivots array
barArray : pivot bar array
dir : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
length : length for which trend series need to be checked
highLow : filter pivot high or low
trend : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots : pivots array
firstIndex : First index of the series
lastIndex : Last index of the series
Returns: int trendIndexes
sma(source)
calculates sma for elements in array
Parameters:
source : source array
Returns: float sma
ema(source, length)
calculates ema for elements in array
Parameters:
source : source array
length : ema length
Returns: float ema
rma(source, length)
calculates rma for elements in array
Parameters:
source : source array
length : rma length
Returns: float rma
wma(source, length)
calculates wma for elements in array
Parameters:
source : source array
length : wma length
Returns: float wma
hma(source, length)
calculates hma for elements in array
Parameters:
source : source array
length : hma length
Returns: float hma
ma(source, matype, length)
wrapper for all moving averages based on array
Parameters:
source : source array
matype : moving average type. Valud values are: sma, ema, rma, wma and hma
length : moving average length length
Returns: float moving average
getFibSeries(numberOfFibs, start)
gets fib series in array
Parameters:
numberOfFibs : number of fibs
start : starting number
Returns: float fibArray
harmonicpatternsLibrary "harmonicpatterns"
harmonicpatterns: methods required for calculation of harmonic patterns. These are customised to be used in my scripts. But, also simple enough for others to make use of :)
isGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isGartleyPattern: Checks for harmonic pattern Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Gartley. False otherwise.
isBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isBatPattern: Checks for harmonic pattern Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Bat. False otherwise.
isButterflyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isButterflyPattern: Checks for harmonic pattern Butterfly
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Butterfly. False otherwise.
isCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isCrabPattern: Checks for harmonic pattern Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Crab. False otherwise.
isDeepCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isDeepCrabPattern: Checks for harmonic pattern DeepCrab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is DeepCrab. False otherwise.
isCypherPattern(xabRatio, axcRatio, xadRatio, err_min, err_max) isCypherPattern: Checks for harmonic pattern Cypher
Parameters:
xabRatio : AB/XA
axcRatio : XC/AX
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Cypher. False otherwise.
isSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isSharkPattern: Checks for harmonic pattern Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Shark. False otherwise.
isNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNenStarPattern: Checks for harmonic pattern Nenstar
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Nenstar. False otherwise.
isAntiNenStarPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiNenStarPattern: Checks for harmonic pattern Anti NenStar
Parameters:
xabRatio : - AB/XA
abcRatio : - BC/AB
bcdRatio : - CD/BC
xadRatio : - AD/XA
err_min : - Minumum error threshold
err_max : - Maximum error threshold
Returns: True if the pattern is Anti NenStar. False otherwise.
isAntiSharkPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiSharkPattern: Checks for harmonic pattern Anti Shark
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Shark. False otherwise.
isAntiCypherPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCypherPattern: Checks for harmonic pattern Anti Cypher
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Cypher. False otherwise.
isAntiCrabPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiCrabPattern: Checks for harmonic pattern Anti Crab
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Crab. False otherwise.
isAntiBatPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiBatPattern: Checks for harmonic pattern Anti Bat
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Bat. False otherwise.
isAntiGartleyPattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isAntiGartleyPattern: Checks for harmonic pattern Anti Gartley
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Anti Gartley. False otherwise.
isNavarro200Pattern(xabRatio, abcRatio, bcdRatio, xadRatio, err_min, err_max) isNavarro200Pattern: Checks for harmonic pattern Navarro200
Parameters:
xabRatio : AB/XA
abcRatio : BC/AB
bcdRatio : CD/BC
xadRatio : AD/XA
err_min : Minumum error threshold
err_max : Maximum error threshold
Returns: True if the pattern is Navarro200. False otherwise.
isHarmonicPattern(x, a, c, c, d, flags, errorPercent) isHarmonicPattern: Checks for harmonic patterns
Parameters:
x : X coordinate value
a : A coordinate value
c : B coordinate value
c : C coordinate value
d : D coordinate value
flags : flags to check patterns. Send empty array to enable all
errorPercent : Error threshold
Returns: Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
Divergence-Support/Resistance - Widget [HeWhoMustNotBeNamed]Unique live widget which provides information about support and resistance along with distance to immediate levels.
⬜ Custom Candle Source
Three options of candles available
▶ Regular OHLC candles
▶ Heikin-Ashi candles ( Taken leaf out of @Bjorgum's book - but, still could not do it as good as him :) )
▶ Moving average candles
⬜ Multiple zigzags and choice of oscillator
Like any other zigzag based indicator, I prefer using 4 zigzag levels.
And select oscillator of your choice to identify divergence. Oscillator lengths are automatically calculated based on zigzag lengths. You can also chose external oscillator.
⬜ Support and resistance widget settings
▶ Max S/R per zigzag - this is the number of last S/R levels recorded for each zigzag
▶ Max S/R for stats - even though there can be many number of S/R levels, we cannot show all of them in the widget due to space constraint. Hence, this is set to minimal value of 3. Can be changed via this input.
▶ Max S/R for Alerts - When sending stats through alerts, users can decide how many immediate S/R levels to be sent in them.
▶ Alert Choices - Can chose to get alerts when new S/R levels formed and also when existing S/R levels broken.
Personally think it is a very handy widget to have!!
Inverse Divergence [HeWhoMustNotBeNamed]Experimental.
In regular scenario divergence calculation follows these procedure
Pivots on price are considered as primary source
They are compared with pivots on oscillators
Trend bias of price is used
This is an experimental version where
Pivots on oscillators are considered as primary source
They are compared with pivots on price
Trend bias of oscillator is used. Using percentrank to define oscillator trend
Caution: Not meant for trading :)
Auto TrendLines [HeWhoMustNotBeNamed]I started off with the intention of creating script to identify Wolfe wave projection. But, soon ran into problem with loops. Realized drawing wedge is more difficult than drawing converging triangle. Hence, took a step back and started working on wedges and triangle identification. Ended up with a messy output which looked like this.
Had to take another step back and hence decided to make Trendlines detection script and here we are :)
⬜ Process
▶ Scan pivots which are in trend. This means, series of pivot Highs or pivot lows either in ascending order or descending order.
▶ Draw trend line between each of the pivots in the trend series. For example, if there are 5 pivot high uptrend pivots, draw mXn lines between each of these points.
▶ Select the trend line which is more accurate or stronger. Accuracy is measured by number of candles/wicks touching the line and number of candles which fall outside the line. Stronger trendlines will touch more candles and pivots with less overflow.
▶ Remove all lines except the most accurate one for each direction.
At any point of time, you will see upto 4 trend lines in this script.
▶ Trendline joining pivot highs in uptrending condition
▶ Trendline joining pivot lows in uptrending condition
▶ Trendline joining pivot highs in downtrending condition
▶ Trendline joining pivot lows in downtrending conditions
The older line will remain until the new one comes through of same type. Hence, you will still be able to see uptrending high and low trend lines for downtrending instruments which are created way back!! Also, new trendlines replace old ones only if they are more stronger (connect to more pivots with less overflow)
⬜ Settings
Settings are simple.
User can select preferred Zigzag Length and Search Depth. Higher numbers for these two parameters will present longer term trends whereas lower numbers will display shorter ones.
Trend Lines controlls will allow users to enable/disable specific type of trend line, set color and line style to it.
⬜ Few Examples
▶ Uptrending Market : NASDAQ:NDX
▶ Downtrending Market : NYSE:BABA
▶ Ranging Market : NYSE:PLTR
Multi-ZigZag Multi-Oscillator Trend DetectorThis table is intended to give you snapshot of how price and oscillators are moving along with zigzag pivots.
This is done in the same lines of Zigzag-Trend-Divergence-Detector
But, here are the differences
Table shows multiple oscillator movements at a same time instead of one selected oscillator
Divergence is not calculated and also supertrend based trend. Trend can be calculated based on zigzag movements. However, lets keep this for future enhancements.
This system also uses multiple zigzags instead of just one.
⬜ Process
▶ Derive multiple zigzags - Code is taken from Multi-ZigZag
▶ Along with zigzags - also calculate different oscillators and attach it to zigzag pivot.
▶ Calculate directions of zigzag pivots and corresponding oscillators.
▶ Plot everything in the table on last bar.
⬜ Table components
Table contains following data:
Directional legends are:
⇈ - Higher High (Green)
⇊ - Lower Low (Red)
⭡- Lower High (Orange)
⭣ - Higher Low (Lime)
⬜ Input Parameters
▶ Source : Default is close. If Unchecked - uses high/low data for calculating pivots. Can also use external input such as OBV
▶ Stats : Gives option to select the depth of output (History) and also lets you chose text size and table position.
▶ Oscillators : Oscillator length is derived by multiplying multiplier to zigzag length. For example, for zigzag 5, with 4 as multiplier, all oscillators are calculated with length 20. But, same for zigzag 8 will be 32 and so on.
▶ Available oscillators :
CCI - Commodity Channel Index
CMO - Chande Momentum Oscillator
COG - Center Of Gravity
MFI - Money Flow Index (Shows only if volume is present)
MOM - Momentum oscillator
ROC - Rate Of Change
RSI - Relative Strength Index
TSI - Total Strength Index
WPR - William Percent R
BB - Bollinger Percent B
KC - Keltner Channel Percent K
DC - Donchian Channel Percent D
ADC - Adoptive Donchian Channel Percent D ( Adoptive-Donchian-Channel )
⬜ Challenges
There are 12 oscillators and each zigzag has different length. Which means, there are 48 combinations of the ocillators.
First challenge was generating these values without creating lots of static initialization. Also, note, if the functions are not called on each bar, then they will not yield correct result. This is achieved through initializer function which runs on every bar and stores the oscillator values in an array which emulates multi dimensional array oscillator X zigzag length.
Next challenge was getting these values within function when we need it. While doing so I realized that values stored in array also have historical series and calling array.get will actully get you the entire series and not just the value. This is an important takeaway for me and this can be used for further complex implementations.
Thanks to @LonesomeTheBlue and @LucF for some timely suggestions and interesting technical discussions :)
Zigzag Candles SupertrendHere it is, as promised, supertrend based on Zigzag candles.
Earlier scripts on the Zigzag Candles expedition are here:
Zigzag-Candles
Zigzag-Candles-MA
Zigzag candles parameters Length and CandleSize remain as is. Along with this, we also add MALength and AtrMult to calculate ATR based on the new candles and to use it to derive supertrend.
UseZigzagCandles - selecting this will apply supertrend on zigzag candles and ignore the actual price candles completely.
UseClosePrices - Uses close price as base instead of high/low. Can be used in both modes of price candles and zigzag candles.
Zigzag Candles MAWe have the candles here: Zigzag-Candles
Lets create moving average!!
Just simple moving average at the moment. Since, items are in array. Not so easy to use standard functions of pine. Hence, will take that for future enhancements.
ATR and Supertrend next!!
Zigzag CandlesCan't deny that I am obsessed with zigzags. Been doing some crazy experiments with it and have many more in pipeline. I believe zigzag can be used to derive better trend following methods. Here is an attempt to visualize zigzag as candlesticks. Next steps probably to derive moving average, atr (although there was an attempt of AZR made earlier) and probably supertrend too ;)
Input parameters include ZigzagLength (to calculate zigzag) and CandleSize (number of zigzag pivots in each candle)
CandleSize can be 3 or more. Every time we collect pivots which are equal to CandleSize, we derive one candle. And when we derive a candle, we remove all old pivots except the last one. Becauase, the last pivot acts as open to the next bar and is required.
Body of the candle tells the start and end zigzag pivot in the range. And Wicks signify highest and lowest pivots in the range. High and Low wicks are placed at the pivot where high and lows are formed. Hence, you can see them at different positions each time.
Thanks to @RicardoSantos for suggesting boxes for candles - while I was trying to achieve this with plotbar
Multi Level ZigZag Harmonic PatternsLets make things bit complicated.
Main difference between this script and the earlier Multi Zigzag Harmonic Pattern is the calculation logic of Zigzag 2, 3 and 4
In the earlier script, all zigzags were plain and were calculated on the basis of different lengths. (Such as 5, 10, 15, 20). These were derived on the basis of Multi Zigzag indicator
In this script, Zigzag 2, 3 and 4 are calculated in slightly different way. They are calculated on the basis of previous zigzag. This means, Zigzag 1 will be the input for Zigzag2 calculation and Zigzag 2 will be the input for Zigzag3 and so on. This is demonstrated in the script - Multi Level Zigzag
One important parameter which is specific to this script is: UseZigZagChain
If checked:
Zigzag2 is formed based on Zigzag1
Zigzag3 is formed based on Zigzag2
Zigzag4 is formed based on Zigzag3
This can lead to patterns covering huge number of candles as this chaining causes exponential effect in each levels. (Effective length grows exponentially in each level)
If unchecked:
Zigzag2 is formed based on Zigzag1 (Same as when checked)
Zigzag3 is formed based on Zigzag1. But, length is set to zigzag2Length + zigzag3Length
Zigzag4 is formed based on Zigzag1. But, length is set to zigzag2Length + zigzag3Length + zigzag4Length
This reduces exponential increase of zigzag lengths over next levels.
Logical ratios of patterns are coded as below:
Notations:
Lines XABCD forms the pattern in all cases. (OXABCD in case of Three drives )
abc = BC retacement of AB, xab = AB retracement of XA and so on
ABCD Classic
0.618 <= abc <= 0.786
1.272 <= bcd <= 1.618
AB=CD
Price difference between AB and CD are equal
Time difference between AB and CD are equal
ABCD Extension
0.618 <= abc <= 0.786
1.272 <= AD/ BC (price) <= 1.618
Gartley
xab = 0.618
0.382 <= abc <= 0.886
1.272 <= bcd <= 1.618 OR xad = 0.786
Crab
0.382 <= xab <= 0.618
0.382 <= abc <= 0.886
2.24 <= bcd <= 3.618 OR xad = 1.618
Deep Crab
xab = 0.886
0.382 <= abc <= 0.886
2.0 <= bcd <= 3.618 OR xad = 1.618
Bat
0.382 <= xab <= 0.50
0.382 <= abc <= 0.886
1.618 <= bcd <= 2.618 OR xad = 0.886
Butterfly
xab = 0.786
0.382 <= abc <= 0.886
1.618 <= bcd <= 2.618 OR 1.272 <= xad <= 2.618
Shark
xab = 0.786
1.13 <= abc <= 1.618
1.618 <= bcd <= 2.24 OR 0.886 <= xad <= 1.13
Cypher
0.382 <= xab <= 0.618
1.13 <= abc <= 1.414
1.272 <= bcd <= 2.0 OR xad = 0.786
Three Drives
oxa = 0.618
1.27 <= xab <= 1.618
abc = 0.618
1.27 <= bcd <= 1.618
5-0
1.13 <= xab <= 1.618
1.618 <= abc <= 2.24
bcd = 0.5
Double Bottom
Last two pivot High Lows make W shape
Last Pivot Low is higher than previous Last Pivot Low.
Last Pivot High is lower than previous last Pivot High.
Price has not gone below Last Pivot Low
Price breaks out of last Pivot High to complete W shape
Double Top
Last two pivot High Lows make M shape
Last Pivot Low is higher than previous Last Pivot Low.
Last Pivot High is lower than previous last Pivot High.
Price has not gone above Last Pivot High
Price breaks out of last Pivot Low to complete M shape