arraysLibrary "arrays"
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
Trendoscope
Interactive Volume Profile - Based on LTF volumeHere is my first attempt on defining volume profile. In this script, I am using new feature of pine security_lower_tf
Upon loading the script, it will ask users to select Time range to show the volume profile. Once you select the time range, confirmation input will popup. Upon confirming the inputs, you will be able to view the volume profile
Settings are pretty simple. Some of them appear as part of confirmation.
Limitation due to availability of LTF bars
security_lower_tf can only fetch upto 100k bars, Hence, if we move the starting point beyond that, we will only see volume profile from the bar where LTF volume data is available. Increasing lower timeframe resolution will also increase the available range of volume profile. Option also available to use max range instead of time based range. If max bar range is selected, then volume profile is drawn based on all the bars for which LTF volume is available.
An example of all combinations are show below.
Selecting the granularity of volume profile
Number of levels can be set from settings which impacts the granularity of volume profile. Below is the example of how different values for number of levels behave.
Wolfe Scanner (Multi - zigzag) [HeWhoMustNotBeNamed]Before getting into the script, I would like to explain bit of history around this project. Wolfe was in the back of my mind for some time and I had several attempts so far.
🎯Initial Attempt
When I first developed harmonic patterns, I got many requests from users to develop script to automatically detect Wolfe formation. I thought it would be easy and started boasting everywhere that I am going to attempt this next. However I miserably failed that time and started realising it is not as simple as I thought it would be. I started with Wolfe in mind. But, ran into issues with loops. Soon figured out that finding and drawing wedge is more trickier. I decided will explore trendline first so that it can help find wedge better. Soon, the project turned into something else and resulted in Auto-TrendLines-HeWhoMustNotBeNamed and Wolfe left forgotten.
🎯Using predefined ratios
Wolfe also has predefined fib ratios which we can use to calculate the formation. But, upon initial development, it did not convince me that it matches visual inspection of Wolfe all the time. Hence, I decided to fall back on finding wedge first.
🎯 Further exploration in finding wedge
This attempt was not too bad. I did not try to jump into Wolfe and nor I bragged anywhere about attempting anything of this sort. My target this time was to find how to derive wedge. I knew then that if I manage to calculate wedge in efficient way, it can help further in finding Wolfe. While doing that, ended up deriving Wedge-and-Flag-Finder-Multi-zigzag - which is not a bad outcome. I got few reminders on Wolfe after this both in comments and in PM.
🎯You never fail until you stop trying!!
After 2 back to back hectic 50hr work weeks + other commitments, I thought I will spend some time on this. Took less than half weekend and here we are. I was surprised how much little time it took in this attempt. But, the plan was running in my subconscious for several weeks or even months. Last two days were just putting these plans into an action.
Now, let's discuss about the script.
🎲 Wolfe Concept
Wolfe concept is simple. Whenever a wedge is formed, draw a line joining pivot 1 and 4 as shown in the chart below:
Converging trendline forms the stop loss whereas line joining pivots 1 and 4 form the profit taking points.
🎲 Settings
Settings are pretty straightforward. Explained in the chart below.
Auto Harmonic Pattern - UltimateX [Trendoscope]IMPORTANT NOTE: (Read this before looking at any other thing on this indicator)
This indicator is created to supersede existing Auto-Harmonic-Pattern-Ultimate-Trendoscope invite only script. The script deviates a lot from the original Auto Harmonic Patterns Ultimate script in terms of number of available patterns, trading type and few other things. Hence, instead of updating the existing script, we have just decided to release as new script. Few FAQs in this regard are as below
What it means for users of AHPU and new users?
▶ Subscription of this script is not sold separately, but will be offered along with existing AHPU script. Meaning, there will be single subscription for both scripts together.
▶ All existing subscribers of AHPU will also get access to this script for the duration of their subscription term. Will start adding access to users starting from lifetime subscribers first.
▶ Any new subscriptions to AHPU will also get access to both the scripts together. We will eventually look to phase out existing AHPU once users are accustomed to new script and any possible bugs are resolved.
▶ Any trial requests will also get access to both scripts. You can request trial even if you have recently requested trial for AHPU.
Why did we create new script instead of updating the existing one?
▶ As mentioned before, this script deviates a lot from the original AHPU. Hence, it is released as new version to make sure smoother transition of users. If anyone is not comfortable using the new version, they can continue using the existing AHPU script until things settle down.
▶ Since the script is new implementation, it may also have initial bugs. It will help us resolve it in more streamlined way.
What are the main differences between these scripts?
▶ Uses single zigzag instead of multi as algorithm is further improved to detect almost everything using single zigzag.
▶ More number of patterns added. But, new patterns are disabled by default as some of them have very wide PRZ. Users can enable it via settings.
▶ Trading type with trailing entry - With wide PRZs, we also had to implement different method for calculating entry/stop. This is explained later in the script.
▶ Matrix implementation and enhanced stats - Entire implementation is redesigned to use matrix data structure instead of arrays. This allows lots of possibilities including enhanced closed trade stats.
▶ Support/Resistance widget is removed as it is proving to be bit of overhead. Users can make use of Support Resistance widget script which is a free to use script instead.
Let's get to the details of indicator now.
🎲 Indicator Components
🎯 Patterns Covered
● Classic Patterns
Gartley
Bat
Butterfly
Crab
Deep Crab
Cypher
Shark
Nenstar
● Anti/Alternate Patterns
Anti Nenstar
Anti Shark
Anti Cypher
Anti Crab
Anti Butterfly
Anti Bat
Anti Gartley
Navarro200
● Non-Standard Patterns (Disabled by default)
Five Zero
Three Drives
White Swan
Black Swan
Sea Pony
Leonardo
121
Snorm
Total
Below is a quick snapshot of indicator components.
Now, lets look at some of the individual components:
🎯 Open trade stats helps recognise trades in motion.
Apart from regular stats, it also contain different types of risk reward ratios.
Regular RR : RR calculated from entry to reach target with initial stop for risk consideration
Trailing RR : This is RR calculated for price to reach from one target to next target considering trailing stop for calculating risk
Live RR : This is calculated based on current price as entry and with given targets and stop levels. Live RR will be blank for targets which are already reached.
Targets are calculated only when entry is made. Hence, target details are not shown for patterns where it is still awaiting entry.
🎯 Closed trade stats helps understand historical performance of patterns.
By default closed stats are displayed in Compact mode. Which means, only total stats are shown. But, users can change this to show detailed stats via settings. Detailed stats take up entire screen most of the time. So, keep them only if it is required.
Closed stats present average Risk Reward, Trailing Risk Reward, Average Win Rate, and Average Trailing Win Rate for all the possible levels. As discussed before.
Regular RR : RR calculated from entry to reach target with initial stop for risk consideration
Trailing RR : This is RR calculated for price to reach from one target to next target considering trailing stop for calculating risk
Win Rate : Simple win rate calculation based on number of patterns reached target and number of valid patterns.
Trailing Win Rate : This is win rate calculated based on previous target to current target.
For example, if there are 48 valid patterns and out of which 24 patterns reach target1 and 12 patterns out of 24 reach target 2
Target1 WR : 50% (24/48)
Target1 TWR : Not applicable as there is no target before Target1
Target2 WR : 25% (12/48)
Target2 TWR : 50% (12/24)
🎲 Settings
Tooltips are provided to help with each and every settings. And they are as below.
🎲 Fully Customisable Alerts - Placeholders
Alerts are created via alert() method of pine. Hence, users will not see message box for alert template on alert widget.
Instead alerts widget look something like this:
To overcome this issue, script provides alert template placeholders as part of settings. In settings, you can already see Alert section where you can enable/disable alerts for different events.
▶ New Pattern Detection
▶ Entry Reached
▶ Target1-4 Reached
▶ Stop price reached
▶ Trade Complete - either by stop or reaching target 4
You can use following placeholders in the given text boxes to create your own alert template.
🎯 Common placeholders which are applicable for all alerts
{type} - Alert Type
- New Harmonic Pattern
- Harmonic Pattern Status Update
- Harmonic Pattern Trade Closure
{id} - Pattern Id. This is not fully unique id. But, this will be unique for all open trades. Once trade is closed, Ids are reused whenever feasible.
{ticker} - Ticker information
{timeframe} - Timeframe information
{price} - Current close price
{patterns} - Possible patterns for the projections or PRZ.
{direction} - Trade direction - Bullish or bearish
{entry} - Calculated entry for pattern
{stop} - Calculated stop for pattern
{tstop} - Trailing stop for the pattern in trade
{target1} - Target1 for pattern in trade
{target2} - Target2 for pattern in trade
{target3} - Target3 for pattern in trade
{target4} - Target4 for pattern in trade
🎯 There are few specific placeholders, which are applicable for some alert types.
Harmonic Pattern Status Update
{status} - Status of the Pattern in trade
{laststatus} - Previous status of the Pattern in trade
Harmonic Pattern Trade Closure
{result} - Trade result upon closure
Auto Chart Patterns - Ultimate [Trendoscope]Here is an attempt to gather and present stats and probabilities of different chart patterns. Here, we challenge few traditional biases such as rising wedge is bearish, falling wedge is bullish etc. All the chart patterns identified in this script are bi-directional. Meaning they offer opportunities to trade in either direction.
This indicator is built on the base of two free scripts
🎯 Wedge-and-Flag-Finder-Multi-zigzag
🎯 Trendline-Pairs-Deep-Search
🎲 Following are the major highlights/updates in the present script
▶ Uses the similar deep search algorithm for finding patterns. Pattern identification logic has been optimised to provide more accurate patterns.
▶ Provides suggestion on how to trade these patterns - along with entry, stop and target suggestions.
▶ Advanced options available in setting such as 'Safe Repaint' - which enables repaint only when trade has not started.
▶ Option to run algorithm within specified time window
▶ Comprehensive stats on historical patterns which include win ratio, risk reward, trailing win ratio and trailing risk reward.
▶ Open Trades Stats widget which can help tracking trades easily.
▶ Fully customisable alerts - which can be used to plugin into bots.
🎲 Chart Patterns Included
▶ Channel - Uptrend, Downtrend, Ranging
▶ Triangle - Expanding, Contracting
▶ Rising Wedge - Expanding, Contracting
▶ Falling Wedge - Expanding, Contracting
If unable to determine the type and yet pivots are inline to form two trend lines, then it goes to category - Indeterminate
🎲 Indicator Components
Below is a quick snapshot of indicator components.
Now, lets look at some of the individual components:
▶Open trade stats helps recognise trades in motion.
▶ Closed trade stats can either be shown with minimal stats or fully detailed stats.
🎲 Settings
▶ Generic Settings
▶ Zigzag and pattern selection
▶ Channel Settings
▶ Risk/Reward and Stats/Display Settings
🎲 Key Features
⬤ Safe Repaint :
This option allows redrawing pattern only if trade has not been taken. This increases accuracy of pattern detection. Example of impact of safe repaint is shows as below:
⬤ Trade Reversal or Breakout of Channels :
This option is useful to handle channels of different size. If the distance between channel trendlines are huge, then it is more advantageous to trade reversals. If the distance between trendlines of channel is small, it is more rewarding to trade the breakouts.
Here is an example of how this setting impacts the trade suggestions.
⬤ Detailed Closed Trade Stats :
Closed Stats settings give users option to see in depth details such as risk reward and win ratios for past patterns along with numbers.
⬤ Fully Customisable Alerts :
Alerts are implemented using alert method. Hence, users will not see text box in alert window where they can set alert format. To overcome this challenge, the indicator offers customisation of alerts through settings.
In the settings window, you notice below options for alerts
These settings allow users to enable/disable alerts for different status of patterns. The text box in the settings allows users to set customisable alert formats using specific placeholders.
Valid placeholders are:
{type} - Alert Type
{id} - Pattern id for which alert is generated
{ticker} - Ticker for which alert is generated
{timeframe} - Chart timeframe
{price} - Current close price
{pattern} - Name of the pattern
{longTrade} - Array containing stop, entry, target1 and target2 for long side of the trade for given pattern
{shortTrade} - Array containing stop, entry, target1 and target2 for short side of the trade for given pattern
{status} - Contains status of both long and short side of the trades as text
Default alert template set for all type of alerts is as below
{
"alert" : "{type}",
"id" : {id},
"ticker" : "{ticker}",
"timeframe" : "{timeframe}",
"price" : {price},
"pattern" : "{pattern}",
"long " : {longTrade},
"short " : {shortTrade},
"status" : "{status}"
}
An example alert looks like this:
If you just want to display pattern name and alert type, your alert message in the box should be something like this:
Type - {type}, Pattern - {pattern}
Will make a video on settings and usage when I get time :)
Zigzag MatrixNothing fancy. Just converted the new matrix library of zigzags ( mZigzag ) into indicator as I sensed it can be useful as indicator.
On top of the standard zigzag, the indicator also tracks given oscillators, moving average and volume indicators on each pivots. More indicators can be added programmatically - but it will take up space in chart. Hence, so far I have only added option to add one per each type (moving average, oscillator and volume)
Settings are as below
Trendline Pairs (Deep Search)After getting good response on Wedge-and-Flag-Finder-Multi-zigzag , I thought I will build little bit further into the script.
Main differences
Uses deep search algorithm for patterns instead of just using last 5 pivots
Flag pattern is removed so that we can concentrate mainly on trend line pairs
More number of overall patterns.
Trend Patterns Included
Channel - Rising, Falling, Ranging
Wedge - Rising, Falling + Expanding, Contracting types
Triangle - Expanding, Contracting
Indeterminate - Happens in rare cases where angle calculation results in error. It may still belong to one of the above patterns.
Please note:
This is published as free to use but protected source code indicator. This is because the script contains deep search algorithm which isn't made public yet and is also been used in other invite only scripts.
Will not be adding alerts to this indicator.
mZigzagLibrary "mZigzag"
Matrix implementation of zigzag to allow further possibilities.
Main advantage of this library over previous zigzag methods is that you can attach any number of indicator/oscillator information to zigzag
calculate(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots) calculates zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
newZG is true if a new pivot is added to array
doubleZG is true if last calculation returned two new pivots (Happens on extreme price change)
draw(length, ohlc, indicatorLabels, indicatorHigh, indicatorLow, numberOfPivots, lineColor, lineWidth, lineStyle, showHighLow, showRatios, showIndicators) draws zigzag and related information
Parameters:
length : is zigzag length
ohlc : array of OHLC values to be used for zigzag calculation
indicatorLabels : Array of name of indicators passed
indicatorHigh : Array of indicator values calculated based on high price of OHLC
indicatorLow : Array of indicators values calculated based on low price of OHLC
numberOfPivots : Number of pivots to be returned
lineColor : zigzag line color. set to blue by default
lineWidth : zigzag line width. set to 1 by default
lineStyle : zigzag line style. set to line.style_solid by default
showHighLow : show HH, HL, LH, LL labels
showRatios : show pivot retracement ratios from previous zigzag
showIndicators : show indicator values
Returns: pivotMatrix Matrix containing zigzag pivots, pivot bars, direction, ratio, and indicators added via indicatorHigh/indicatorLow
zigzaglines array of zigzag lines
zigzaglabels array of zigzag labels
Wedge and Flag Finder (Multi - zigzag)Here is a small attempt to automatically identify wedges and flags.
Tradingview standard wedge checks for only 4 pivots. In this version, I have considered 5 pivots instead - which can help reduce noise as 4 pivots forming wedge can be quite common. In future, will also try to add more pivots in pattern recognition to make the signal more accurate.
If wedge comes with a tail, then it is marked as flag :)
Settings are quite simple and they are as shown below
Intrabar OBV/PVTI got this idea from @fikira's script Intrabar-Price-Volume-Change-experimental
The indicator calculates OBV and PVT based on ticks. Since, the indicator relies on live ticks, it only starts execution after it is put on the charts. The script can be useful in analysing intraday buy and sell pressure. Details are color coded based on the values.
Data is presented in simple tabular format.
Formula for OBV and PVT can be found here:
www.investopedia.com
www.investopedia.com
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.
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
Auto Harmonic Projection - Ultimate [Trendoscope]Hello traders, Many who used Auto Harmonic Pattern - Ultimate had enquired with me about having option to project PRZ before patterns formed. We always replied that it is in pipeline but will not be part of existing script. Finally, we decided to utilise part of our Christmas and new year break to make it happen.
Lets get started..
⬜ Process
▶ Unlike Auto Harmonic Patterns Ultimate, instead of scanning whole XABCD for harmonic pattern, this script only collects XABC and projects PRZs (Possible D zones)
▶ Once possible patterns are found, lines are drawn to connect XABC and boxes to project PRZs. There can be more than 1 PRZs for XABC combination. If PRZs of multiple patterns overlap, they are joined and shown as single PRZ where all patterns are listed against it.
▶ If price crosses C, pattern is considered as failed. If price stays between C and PRZs for long time, patterns are timed out. In either case, patterns and projections are removed from chart.
▶ Pattern is considered to be active once price reach B. Until then Pattern is inactive.
▶ PRZs are tracked individually even if they belong to same pattern. PRZ is considered active only if price hits PRZ and completes the pattern. Till then PRZ is considered inactive.
▶ After activating, PRZs can either reach successful level if price moves in reversal direction. Or it can reach failure if price reaches stop.
▶ PRZs are removed from chart once it either reaches stop or success level. But, if more PRZs are present for pattern, pattern will still be there on chart.
▶ Pattern is kept active till all the PRZs are either hit stop or success or pattern itself is either failed or timed out.
Note:
Whenever we refer pattern - consider it as lines joining X, A, B, C and D if PRZ is active.
Wherever we refer PRZ - consider it as box representing potential reversal zones.
⬜ Screen components
▶ Inactive Patterns and PRZ - Patterns with inactive PRZs are represented as lines joining XABC. There will not be line connecting D and PRZs are shown with faded colour and smaller fonts.
▶ Active Patterns and PRZ - Patterns with active PRZ are represented with full pattern and line fills. PRZ will also show stop and success level. Note that success level is not target level - but a position used for validating the outcome.
▶ Stats table - Open stats table contains patterns and corresponding PRZ levels. Stats will have red background for bearish patterns/projections and green background for bullish patterns/projections. Content text colour is matched with that of PRZ and Pattern line colors so that users can identify the matching stats easily.
▶ Run timer - Tells how long the script backtest is running. Run timer will have red background for TRIAL access or if right access key is not used. Otherwise, it will have green background colour. This does not have much significance now as there are no closed stats available. It will be added in the future versions.
▶ Watermark - Watermark appears only if valid key is not used or TRIAL access key is used.
Bit more details about open stats table here
⬜ Settings
⚪ Alert Key
Alert key is given for active subscribers. This key is required in order to set alerts or in order to run the script for more than 30 bars on single instrument without interruption. Not having alert key will not stop users from using the indicator once they acquire access - but it will only limit few capabilities. Key is not given for trial access.
Key is prompted every time users add indicator to chart. If you are provided with key, please use it instead of the TRIAL access key.
If you are using valid key,
You will see run timer in green instead of red background
No TRIAL ACCESS watermark on the chart.
⚪ Zigzag and pattern detection settings
⚪ Pattern Selection settings
⚪ Stats and Display
⚪ Colors and themes
⚪ Backtest Settings
Not important for now as there are no closed pattern stats. Kept for future usage. Will impact the timer widget.
⚪ Alerts
▶ Types and settings
▶Setting alerts is simple. When indicator is loaded on chart (Make sure you are using the right alert key), goto alerts and select the AHProjection from Condition dropdown. Update other parameters such as alert name, webhook details as required and press create
▶ Examples of alerts
⬜ Status Tracking
Script tracks two types of statuses.
⚪ Harmonic Pattern Projection Status : Tracks projection as a whole for each combination of X, A, B, C. Different states available are
Awaiting Activation : Any pattern projection when formed by default goes into Inactive State and hence set to Awaiting Activation.
Projection Active : Once price reach B, then pattern projection is considered active
Entry Reached : Once price reach the nearest PRZ level, it is considered as Entry reached. Status will remain as entry reached even if PRZ is removed and next PRZ level is yet to be reached.
Projection Invalidated : If price goes beyond C level, then pattern projection is considered invalidated. It can happen at any stage and even after successful completion of few PRZ ranges.
Projection Timed Out : If price keeps between PRZ and C for considerable time, it will timed out and removed from chart.
⚪ Harmonic Pattern Projection PRZ Status Tracks individual PRZs separately which may or may not belong to same patterns. Different states available are
Awaiting Activation : Any PRZ is considered inactive before price reaching the PRZ level.
Active : Once price reaches PRZ, it will become active. Active PRZs are highlighted with line fill on chart. Active PRZ also display success and stop levels. PRZ is not removed unless price hits one of these levels or the entire pattern is timed out.
Successful : If an active PRZ price reaches success level, then PRZ projection is considered successful. Once successful, PRZ will removed from chart
Failed : If an active PRZ price reaches stop level, then PRZ projection is considered failure. Once failed PRZ will be removed from chart.
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
Auto TrendLines and Support Resistance - Ultimate [Trendoscope]Have been working on this script from sometime. Thought it would be right time to publish this now :)
This is enhanced and combined version of two open source scripts.
Auto-TrendLines-HeWhoMustNotBeNamed
Divergence-Support-Resistence
⬜ Major Enhancements to open source
▶ Concept of drawing trendlines remains same. But, logic has been altered to allow considering existing trendlines before scanning new one and also finding the strongest of all.
▶ Strength of trendlines now takes more factors into consideration such as weightage of each candles from two points with respect to a given trendline.
▶ Angle of the trendlines are calculated and considered for determination of overall trend.
▶ Trendlines come with invalidation point and trend definition also can be based on single trendline instead of multiple ones.
▶ Improved divergence and based support/resistance calculations which yield less but more significant levels.
⬜ Components
Below are the summary of indicator components
⚪ Trend Lines Summary Widget
This can have up-to 4 types of trend lines.
Uptrend Lower pivot based
Uptrend Higher pivot based
Downtrend Lower pivot based
Downtrend Higher pivot based
Direction of the lines dependent on slope of the trend as well. If angle is not steep, the trend lines are considered as neutral. Meanwhile, trend lines which are too steep are also ignored. Angle calculation depends on the ATR and Angle loopback input parameters which can be altered. Also TrendLines with negative Line strength or formed way too back are ignored based on the settings. Hence, it is perfectly normal to have less than 4 trend lines on charts at times.
⚪ S/R Summary Widget
This widget has been used in other indicators. Notations are same though there are logical improvements to derive only the high impact levels.
⬜ Settings
⚪ Trend Detection Settings
These are the settings used for scanning the trend lines. Summary of these settings are as below:
⚪ Pattern Detection Settings
The pattern detection settings help identify overall trend pattern and status based on the combination of higher and lower pivot trend lines.
Important bit here is the Sort Order which impacts the identification of overall trend. Available types are:
Distance : Sort based on distance from close price
LineStrength : Sort based on line strength of the trend line
Latest : Sort based on when the trend lines are formed.
⚪ Support/Resistance Settings
Base settings for calculating divergence based Support/Resistance.
⚪ Widgets
Widgets settings allow users to control display of Trend Lines and S/R summary widgets.
⚪ Alerts
Below are the settings for configuring alerts.
Alerts are formatted in Json for easier consumption via web-hook.
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.
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