DrawingTypesLibrary   "DrawingTypes" 
User Defined Types for basic drawing structure. Other types and methods will be built on these.
 Point 
  Point refers to point on chart
  Fields:
     price : pivot price
     bar : pivot bar
     bartime : pivot bar time
 LineProperties 
  Properties of line object
  Fields:
     xloc : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
     extend : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
     color : Line color
     style : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
     width : Line width. Default is 1
 Line 
  Line object created from points
  Fields:
     start : Starting point of the line
     end : Ending point of the line
     properties : LineProperties object which defines the style of line
     object : Derived line object
 LabelProperties 
  Properties of label object
  Fields:
     xloc : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
     yloc : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
     color : Label fill color
     style : Label style as defined in www.tradingview.com Default is label.style_none
     textcolor : text color. Default is color.black
     size : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
     textalign : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
     text_font_family : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
 Label 
  Label object
  Fields:
     point : Point where label is drawn
     lblText : label text
     tooltip : Tooltip text. Default is na
     properties : LabelProperties object
     object : Pine label object
 Linefill 
  Linefill object
  Fields:
     line1 : First line to create linefill
     line2 : Second line to create linefill
     fillColor : Fill color
     transparency : Fill transparency range from 0 to 100
     object : linefill object created from wrapper
 BoxProperties 
  BoxProperties object
  Fields:
     border_color : Box border color. Default is color.blue
     bgcolor : box background color
     border_width : Box border width. Default is 1
     border_style : Box border style. Default is line.style_solid
     extend : Extend property of box. default is extend.none
     xloc : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
 BoxText 
  Box Text properties.
  Fields:
     boxText : Text to be printed on the box
     text_size : Text size. Default is size.auto
     text_color : Box text color. Default is color.yellow. 
     text_halign : horizontal align style - default is text.align_center
     text_valign : vertical align style - default is text.align_center
     text_wrap : text wrap style - default is text.wrap_auto
     text_font_family : Text font. Default is
 Box 
  Box object
  Fields:
     p1 : Diagonal point one
     p2 : Diagonal point two
     properties : Box properties
     textProperties : Box text properties
     object : Box object created
Techindicator
Liquidation_linesLibrary   "Liquidationline" 
 f_calculateLeverage(_leverage, _maintainance, _value, _direction) 
  Parameters:
     _leverage 
     _maintainance 
     _value 
     _direction 
 f_liqline_update(_Liqui_Line, _killonlowhigh) 
  Parameters:
     _Liqui_Line 
     _killonlowhigh 
 f_liqline_draw(_Liqui_Line, _priceorliq) 
  Parameters:
     _Liqui_Line 
     _priceorliq 
 f_liqline_add(_Liqui_Line, linetoadd, _limit) 
  Parameters:
     _Liqui_Line 
     linetoadd 
     _limit 
 Liquidationline 
  Fields:
     creationtime 
     stoptime 
     price 
     leverage 
     maintainance 
     line_active 
     line_color 
     line_thickness 
     line_style 
     line_direction 
     line_finished 
     text_active 
     text_size 
     text_color 
this library can draw typical liquidation lines, which can be called e.g. by indicator signals
You can see the default implementation in the lower part of the code, starting with RUNTIME
Don't forget to increase max lines to 500 in your script.
It can look like this screenshot here, with only minor changes to your executing script. 
The base is the same
AntaresLibrary   "Antares" 
this library contains some utility functions that I use in my open source scripts including moving average helpers, candlstick helpers, money management, formatters, convertors, webhook integration, analysis, filters and drawing helpers
 ma(type, length, source) 
  Wraps all ma functions
  Parameters:
     type : Either SMA or EMA or RMA or WMA or VWMA
     length : Number of bars (length).
     source : Series of values to process.
  Returns: Moving average of `source` for `length` bars back by the of MA.
 bb(ma, length, mult, source) 
  Overwrites `ta.bb` duo to limitations of simple int.float mult. Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price, but can be adjusted to user preferences.
  Parameters:
     ma : Either SMA or EMA or RMA or WMA or VWMA
     length : Number of bars (length).
     mult : Standard deviation factor.
     source : Series of values to process.
  Returns: Bollinger Bands.
 atr(length, h, l, c) 
  Overwrites `ta.atr` duo to limitations of simple int length. Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close ), abs(low - close )).
  Parameters:
     length : Number of bars (length).
     h : High price high price.
     l : low price.
     c : Close price close price.
  Returns: Average true range.
 rsi(length, source) 
  Overwrites `ta.rsi` duo to limitations of simple int length. Relative strength index. It is calculated using the `ta.rma()` of upward and downward changes of `source` over the last `length` bars.
  Parameters:
     length : Number of bars (length).
     source : Series of values to process.
  Returns: Relative strength index.
 lowest(length, source, start) 
  Lowest value for a given number of bars back.
  Parameters:
     length : Number of bars (length).
     source : Series of values to process.
     start : Series number of bars that should be skipped before process.
  Returns: Lowest value in the series.
 highest(length, source, start) 
  Highest value for a given number of bars back.
  Parameters:
     length : Number of bars (length).
     source : Series of values to process.
     start : Series number of bars that should be skipped before process.
  Returns: Highest value in the series.
 atr_multiplier(rsi, atr_max_multiplier) 
  Dynamic atr multiplier calculated by RSI.
  Parameters:
     rsi : Relative strength index.
     atr_max_multiplier : The maximum multiplier of atr
  Returns: Dynamic multiplier of ATR
 offset(atr, atr_multiplier) 
  Safe dynamic offset you need to use in your stoploss, stop buy/sell, etc.
  Parameters:
     atr : Average true range.
     atr_multiplier : ATR multiplier got from `atr_multiplier(rsi, atr_max_multiplier)`
  Returns: Dynamic offset
 rsi_emotional(rsi, bottom, top) 
  Tells you if RSI is in emotional zone.
  Parameters:
     rsi : Relative Strength Index
     bottom : The zone that below it market reacts emotionally
     top : The zone that above it market reacts emotionally
  Returns: false if RSI was between `bottom` and `top` otherwise true
 rsi_signal(rsi, bottom, top) 
  Tells you if RSI is in good point to check your other strategy conditions.
  Parameters:
     rsi : Relative Strength Index
     bottom : The zone that below it market reacts emotionally
     top : The zone that above it market reacts emotionally
  Returns: 1 if RSI crossed out 30, 50 or 70. -1 if RSI crossed under 70, 50, 30. otherwise is 0
MLExtensionsLibrary   "MLExtensions" 
 normalizeDeriv(src, quadraticMeanLength) 
  Returns the smoothed hyperbolic tangent of the input series.
  Parameters:
     src :  The input series (i.e., the first-order derivative for price).
     quadraticMeanLength :   The length of the quadratic mean (RMS).
  Returns: nDeriv  The normalized derivative of the input series.
 normalize(src, min, max) 
  Rescales a source value with an unbounded range to a target range.
  Parameters:
     src :  The input series
     min :  The minimum value of the unbounded range
     max :  The maximum value of the unbounded range
  Returns:  The normalized series
 rescale(src, oldMin, oldMax, newMin, newMax) 
  Rescales a source value with a bounded range to anther bounded range
  Parameters:
     src :  The input series
     oldMin :  The minimum value of the range to rescale from
     oldMax :  The maximum value of the range to rescale from
     newMin :  The minimum value of the range to rescale to
     newMax :  The maximum value of the range to rescale to 
  Returns:  The rescaled series
 color_green(prediction) 
  Assigns varying shades of the color green based on the KNN classification
  Parameters:
     prediction : Value (int|float) of the prediction 
  Returns: color 
 color_red(prediction) 
  Assigns varying shades of the color red based on the KNN classification
  Parameters:
     prediction : Value of the prediction
  Returns: color
 tanh(src) 
  Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
  Parameters:
     src :  The input series (i.e., the normalized derivative).
  Returns: tanh  The hyperbolic tangent of the input series.
 dualPoleFilter(src, lookback) 
  Returns the smoothed hyperbolic tangent of the input series.
  Parameters:
     src :  The input series (i.e., the hyperbolic tangent).
     lookback :  The lookback window for the smoothing.
  Returns: filter  The smoothed hyperbolic tangent of the input series.
 tanhTransform(src, smoothingFrequency, quadraticMeanLength) 
  Returns the tanh transform of the input series.
  Parameters:
     src :  The input series (i.e., the result of the tanh calculation).
     smoothingFrequency 
     quadraticMeanLength 
  Returns: signal  The smoothed hyperbolic tangent transform of the input series.
 n_rsi(src, n1, n2) 
  Returns the normalized RSI ideal for use in ML algorithms.
  Parameters:
     src :  The input series (i.e., the result of the RSI calculation).
     n1 :  The length of the RSI.
     n2 :  The smoothing length of the RSI.
  Returns: signal  The normalized RSI.
 n_cci(src, n1, n2) 
  Returns the normalized CCI ideal for use in ML algorithms.
  Parameters:
     src :  The input series (i.e., the result of the CCI calculation).
     n1 :  The length of the CCI.
     n2 :  The smoothing length of the CCI.
  Returns: signal  The normalized CCI.
 n_wt(src, n1, n2) 
  Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
  Parameters:
     src :  The input series (i.e., the result of the WaveTrend Classic calculation).
     n1 
     n2 
  Returns: signal  The normalized WaveTrend Classic series.
 n_adx(highSrc, lowSrc, closeSrc, n1) 
  Returns the normalized ADX ideal for use in ML algorithms.
  Parameters:
     highSrc :  The input series for the high price.
     lowSrc :  The input series for the low price.
     closeSrc :  The input series for the close price.
     n1 :  The length of the ADX.
 regime_filter(src, threshold, useRegimeFilter) 
  Parameters:
     src 
     threshold 
     useRegimeFilter 
 filter_adx(src, length, adxThreshold, useAdxFilter) 
  filter_adx
  Parameters:
     src :  The source series.
     length :  The length of the ADX.
     adxThreshold :  The ADX threshold.
     useAdxFilter :  Whether to use the ADX filter.
  Returns:  The ADX.
 filter_volatility(minLength, maxLength, useVolatilityFilter) 
  filter_volatility
  Parameters:
     minLength :  The minimum length of the ATR.
     maxLength :  The maximum length of the ATR.
     useVolatilityFilter :  Whether to use the volatility filter.
  Returns:  Boolean indicating whether or not to let the signal pass through the filter.
 backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex, thisBarIndex) 
  Performs a basic backtest using the specified parameters and conditions.
  Parameters:
     high :  The input series for the high price.
     low :  The input series for the low price.
     open :  The input series for the open price.
     startLongTrade :  The series of conditions that indicate the start of a long trade.`
     endLongTrade :  The series of conditions that indicate the end of a long trade.
     startShortTrade :  The series of conditions that indicate the start of a short trade.
     endShortTrade :  The series of conditions that indicate the end of a short trade.
     isStopLossHit :  The stop loss hit indicator.
     maxBarsBackIndex :  The maximum number of bars to go back in the backtest.
     thisBarIndex :  The current bar index.
  Returns:  A tuple containing backtest values
 init_table() 
  init_table()
  Returns: tbl  The backtest results.
 update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, stopLosses) 
  update_table(tbl, tradeStats)
  Parameters:
     tbl :  The backtest results table.
     tradeStatsHeader :  The trade stats header.
     totalTrades :  The total number of trades.
     totalWins :  The total number of wins.
     totalLosses :  The total number of losses.
     winLossRatio :  The win loss ratio.
     winrate :  The winrate.
     stopLosses :  The total number of stop losses.
  Returns:  Updated backtest results table.
BasicVisibleChartBasic library for the visible range chart; with functions to allow plotting Fibs from body high/low as well as wick high/low
-Thanks to code from @PineCoders Visible Chart library (PineCoders/VisibleChart/4), which is a much more comprehensive library than this, but which does not include some functions that I find useful:
-Added the following exportable functions: highest/lowest body, highest/lowest close, highest/lowest open. These allow one to anchor fibs from bodies rather than wicks
-Added a Fib Box function in the example code
The above chart shows the example code plotting a Fib range drawn from bodies and a highlighted retracement zone  (61.8 % - 78.6% )
~~All Exportable Functions~~
 barIsVisible() 
 highestClose() 
 highestOpen() 
 highestBody() 
 lowestClose() 
 lowestOpen() 
 lowestBody() 
 high() 
 highBarTime() 
 low() 
 lowBarTime() 
 open() 
 close() 
MyLibraryLibrary   "MyLibrary" 
TODO: add library description here
 isHammer(fib, colorMatch) 
  TODO: add function description here
  Parameters:
     fib 
     colorMatch 
  Returns: TODO: add what function returns
eHarmonicpatternsLogScaleLibrary   "eHarmonicpatternsLogScale" 
Library provides functions to scan harmonic patterns both or normal and log scale
 getSupportedPatterns() 
 get_prz_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale) 
  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
     logScale : - calculate on log scale. Default is false
  Returns:   Start and end of consolidated PRZ range
 get_prz_range_xad(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale) 
  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
     logScale : - calculate on log scale. Default is false
  Returns:   Start and end of consolidated PRZ range
 get_projection_range(x, a, b, c, patternArray, errorPercent, start_adj, end_adj, logScale) 
  Provides Projection 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
     logScale : - calculate on log scale. Default is false
  Returns:   Array containing start and end ranges
 isHarmonicPattern(x, a, b, c, d, flags, defaultEnabled, errorPercent, logScale) 
  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 
     defaultEnabled 
     errorPercent : Error threshold
     logScale : - calculate on log scale. Default is false
  Returns:   Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
 isHarmonicProjection(x, a, b, c, flags, defaultEnabled, errorPercent, logScale) 
  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 
     defaultEnabled 
     errorPercent : Error threshold
     logScale : - calculate on log scale. Default is false
  Returns:   Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
E5TradingLibrary
  This library replaces the previous MetaWorldEngineFilterLibrary3.
 
Library   "E5TradingLibrary" 
 GetCandleStickSize(_src_high, _src_low) 
  returns size of the candle
  Parameters:
     _src_high 
     _src_low 
  Returns: candlestick size
 GetCandleStickBodySize(_src_open, _src_close) 
  returns size of the candle body
  Parameters:
     _src_open 
     _src_close 
  Returns: candlestick body size
 FilterLongerLowerWickCandles(_src_open, _src_close, _src_low) 
  Alters Candlestick Value to Magnify Candles with Long Wicks
  Parameters:
     _src_open 
     _src_close 
     _src_low 
  Returns: Midpoint of the candle body less the lower wick. If value returned has a large delta from midpoint of the body, then it is short wick
 IsBullish(_src_open, _src_close) 
  Determine if Candle is Bullish or Bearish
  Parameters:
     _src_open 
     _src_close 
  Returns: True is Bullish
 IsDoji(_candleIndex, _precision) 
  Determine if Candle is a Doji
  Parameters:
     _candleIndex 
     _precision 
  Returns: True if a Doji
 MACD(_src, _fastLength, _slowLength, _signalLength) 
  Computes MACD
  Parameters:
     _src 
     _fastLength 
     _slowLength 
     _signalLength 
  Returns: Returns MACD and Signal Line
 isFastSlowCrossed(SeriesA, SeriesB) 
  Computes if SeriesA crosses SeriesB
  Parameters:
     SeriesA 
     SeriesB 
  Returns: if SeriesA crosses SeriesB then true else false
 isReversalUpTrend(SeriesA, SeriesB) 
  Computes if SeriesA crosses over SeriesB to determine reversal uptrend
  Parameters:
     SeriesA 
     SeriesB 
  Returns: if SeriesA crosses over SeriesB then true else false
 isReversalDownTrend(SeriesA, SeriesB) 
  Computes if SeriesA crosses over SeriesB to determine reversal uptrend
  Parameters:
     SeriesA 
     SeriesB 
  Returns: if SeriesA crosses over SeriesB then true else false
 SSMA(_src, smalength) 
  Computes smoothed SMA
  Parameters:
     _src 
     smalength 
  Returns: a single concatenated string for evaluation
 GetTimeFrame() 
  Get Current timeframe in minutes
  Returns: an integer value in minutes
 getMA(_src, length, maType) 
  Gets a Moving Average based on type
  Parameters:
     _src 
     length 
     maType 
  Returns: A moving average with the given parameters
 ATRSwitch(_src, _ATRMult, _ATRLength) 
  Average True Range Trailing Stops by Sylvain Vervoort
  Parameters:
     _src 
     _ATRMult 
     _ATRLength 
  Returns: upper ATR Line, lower ATR Line and the switch point
HiveLibraryLibrary   "HiveLibrary" 
: Custom library
 RoundDown(number, decimals) 
  RoundDown() rounds the specified number down to the given number
of decimal places.
  Parameters:
     number : is the argument for rounding down & decimals is the number of digits after dot
     decimals 
  Returns: return is the rounded down value of the number
Library_SmoothersLibrary   "Library_Smoothers" 
 CorrectedMA(Src, Len) 
  CorrectedMA The strengths of the corrected Average (CA) is that the current value of the time series must exceed a the current volatility-dependent threshold, so that the filter increases or falls, avoiding false signals when the trend is in a weak phase.
  Parameters:
     Src 
     Len 
  Returns: The Corrected source.
 EHMA(src, len) 
  EMA Exponential Moving Average.
  Parameters:
     src : Source to act upon
     len 
  Returns: EMA of source
 FRAMA(src, len, FC, SC) 
  FRAMA Fractal Adaptive Moving Average
  Parameters:
     src : Source to act upon
     len : Length of moving average
     FC : Fast moving average
     SC : Slow moving average
  Returns: FRAMA of source
 Jurik(src, length, phase, power) 
  Jurik A low lag filter
  Parameters:
     src : Source
     length : Length for smoothing
     phase : Phase range is ±100
     power : Mathematical power to use. Doesn't need to be whole numbers
  Returns: Jurik of source
 SMMA(src, len) 
  SMMA Smoothed moving average. Think of the SMMA as a hybrid of its better-known siblings — the simple moving average (SMA) and the exponential moving average (EMA).
  Parameters:
     src : Source
     len 
  Returns: SMMA of source
 SuperSmoother(src, len) 
  SuperSmoother
  Parameters:
     src : Source to smooth
     len 
  Returns: SuperSmoother of the source
 TMA(src, len) 
  TMA Triangular Moving Average
  Parameters:
     src : Source
     len 
  Returns: TMA of source
 TSF(src, len) 
  TSF Time Series Forecast. Uses linear regression.
  Parameters:
     src : Source
     len 
  Returns: TSF of source
 VIDYA(src, len) 
  VIDYA Chande's Variable Index Dynamic Average. See www.fxcorporate.com
  Parameters:
     src : Source
     len 
  Returns: VIDYA of source
 VAWMA(src, len, startingWeight, volumeDefault) 
  VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does).
  Parameters:
     src : Source
     len : Length
     startingWeight 
     volumeDefault : The default value to use when a chart has no volume. 
  Returns: The VAWMA of the source.
 WWMA(src, len) 
  WWMA Welles Wilder Moving Average
  Parameters:
     src : Source
     len 
  Returns: The WWMA of the source
 ZLEMA(src, len) 
  ZLEMA Zero Lag Expotential Moving Average
  Parameters:
     src : Source
     len 
  Returns: The ZLEMA of the source
 SmootherType(mode, src, len, fastMA, slowMA, offset, phase, power, startingWeight, volumeDefault, Corrected) 
  Performs the specified moving average
  Parameters:
     mode : Name of moving average
     src : the source to apply the MA type
     len 
     fastMA : FRAMA fast moving average
     slowMA : FRAMA slow  moving average
     offset : Linear regression offset
     phase : Jurik phase
     power : Jurik power
     startingWeight : VAWMA starting weight 
     volumeDefault : VAWMA default volume
     Corrected 
  Returns: The MA smoothed source
HendrixLIBRARY - utilsLibrary   "HendrixLIBRARY" 
 getVolumeData() 
 getLTF(customTimeframe, ltf) 
  Parameters:
     customTimeframe 
     ltf 
 sumArray(a) 
  Parameters:
     a 
 arrs2vals(upVolumeArray, downVolumeArray, volArr) 
  Parameters:
     upVolumeArray 
     downVolumeArray 
     volArr 
 getVolumesFromUpDownArrays(upVolumeArray, downVolumeArray) 
  Parameters:
     upVolumeArray 
     downVolumeArray 
 getDeltaFromVolumes(upVolume, downVolume) 
  Parameters:
     upVolume 
     downVolume 
 getDeltaFromUpDownArrays(upVolumeArray, downVolumeArray) 
  Parameters:
     upVolumeArray 
     downVolumeArray 
 getUpColor() 
 getDownColor() 
 getBlackColor() 
 getColors() 
 printTableTR(txt) 
  Parameters:
     txt 
 printTableBR(txt) 
  Parameters:
     txt 
 printTableMR(txt) 
  Parameters:
     txt 
 print(txt, lbl) 
  Parameters:
     txt 
     lbl 
 printSyminfo(sym) 
  Parameters:
     sym
HSupertrendLibrary   "HSupertrend" 
Supertrend implementation based on harmonic patterns
 hsupertrend(zProperties, pProperties, errorPercent, showPatterns, patternColor) 
  derives supertrend based on harmonic patterns
  Parameters:
     zProperties : ZigzagProperties containing Zigzag length and source array
     pProperties : PatternProperties used for calculation
     errorPercent : Error threshold for scanning patterns
     showPatterns : Draw identified patterns structure on chart
     patternColor : Color of the pattern lines to be drawn
  Returns:  
 ZigzagProperties 
  ZigzagProperties contains values required for zigzag calculation
  Fields:
     length : Zigzag length
     source : Array containing custom OHLC. If not set, array.from(high, low) is used
 PatternProperties 
  PatternProperties are essential pattern parameters used for calculation of bullish and bearish zones
  Fields:
     base : Base for calculating entry and stop of pattern. Can be CD, minmax or correction. Default is CD
     entryPercent : Distance from D in terms of percent of Base in the direction of pattern
     stopPercent : Distance from D in terms of percent of Base in the opposite direction of pattern
     useClosePrices : When set uses close price for calculation of supertrend breakout
ChasinAlts_LibraryLibrary   "ChasinAlts_Library" 
 rci(_BCgtg, _Tgtg, _close, _smaLen, _bar_index) 
  Parameters:
     _BCgtg 
     _Tgtg 
     _close 
     _smaLen 
     _bar_index 
 printedBC(_time, _minPerc, _Tgtg, _lkbk) 
  Parameters:
     _time 
     _minPerc 
     _Tgtg 
     _lkbk 
 form123(_ppLen, _BCgtg, _Tgtg, _high, _low, _close, _bar_index) 
  Parameters:
     _ppLen 
     _BCgtg 
     _Tgtg 
     _high 
     _low 
     _close 
     _bar_index 
 obosCnt(_BCgtg, _Tgtg, _rci, _obosMin, _obosMax, _thresh) 
  Parameters:
     _BCgtg 
     _Tgtg 
     _rci 
     _obosMin 
     _obosMax 
     _thresh 
 div(_thresh, _HLestLen, _Tgtg, _BCgtg, _rci, _time, _price, _LSL, _SSL, _LTP, _STP, _colorid, _long, _short) 
  Parameters:
     _thresh 
     _HLestLen 
     _Tgtg 
     _BCgtg 
     _rci 
     _time 
     _price 
     _LSL 
     _SSL 
     _LTP 
     _STP 
     _colorid 
     _long 
     _short 
 tradeSim(_SL, _TP, _BCgtg, _Tgtg, _ppLen, _high, _low, _close, _bar_index, _time, _bull_rev, _bear_rev, _bull_obosCnt_gtg, _bear_obosCnt_gtg) 
  Parameters:
     _SL 
     _TP 
     _BCgtg 
     _Tgtg 
     _ppLen 
     _high 
     _low 
     _close 
     _bar_index 
     _time 
     _bull_rev 
     _bear_rev 
     _bull_obosCnt_gtg 
     _bear_obosCnt_gtg
TrailingStopsLibrary   "TrailingStops" 
This library contains functions to output trailing stop lines.
 f_marketStructureStop(_restartMode, _flipMode, _restartLowIn, _restartHighIn) 
  Parameters:
     _restartMode  - Defines how the stop lines persist. Allowed values are:
 
       "Always On" - The stop lines are always present and they just reset when they're crossed.
       "Flip" - The stop lines flip when they're crossed.
       "Manual" - The stop lines turn off when they're crossed, and turn back on again when _restartLowIn or _restartHighIn are passed into the function as true.
 
     _flipMode  - Defines whether the stop lines are broken by wicks or closes. Allowed values are "Wick", and "Close".
     _restartLowIn  - If _restartMode is "Manual", passing this parameter as true restarts the Low stop line.
     _restartHighIn   - If _restartMode is "Manual", passing this parameter as true restarts the High stop line.
 @returns  - floats for the Low and High stop line.
MarketStructureLibrary   "MarketStructure" 
This library contains functions for identifying Lows and Highs in a rule-based way, and deriving useful information from them.
 f_simpleLowHigh() 
This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
It doesn't have to be "the" high, so don't be confused.
By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for stops, I want them all, not just the ones that alternate in strict order.
@param - there are no parameters. The function uses the chart OHLC.
@returns boolean values for whether this bar confirms a Simple Low/High, and ints for the bar_index of that Low/High.
 f_localLowHigh() 
This function finds Local Lows and Highs, in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
By the rules, Local Lows and Highs must alternate, and in this function they do.
@param - there are no parameters. The function uses the chart OHLC.
@returns boolean values for whether this bar confirms a Local Low/High, and ints for the bar_index of that Low/High.
 f_enhancedSimpleLowHigh() 
This function finds Local Lows and Highs, but NOT in order. A Local High is any candle that has its Low taken out on close by a subsequent candle (and vice-versa for Local Lows).
The Local High does NOT have to be the candle with the highest High out of recent candles. It does NOT have to be a Williams High. It is not necessarily a swing high or a reversal or anything else.
By the rules, Local Lows and Highs must alternate. In this function they do not, so I'm calling them Simple Lows and Highs.
Simple Highs and Lows, by the above definition, can be useful for entries and stops. Because I intend to use them for trailing stops, I want them all, not just the ones that alternate in strict order.
The difference between this function and f_simpleLowHigh() is that it also tracks the lowest/highest recent level. This level can be useful for trailing stops.
In effect, these are like more "normal" highs and lows that you would pick by eye, but confirmed faster in many cases than by waiting for the low/high of that particular candle to be taken out on close, 
because they are instead confirmed by ANY subsequent candle having its low/high exceeded. Hence, I call these Enhanced Simple Lows/Highs.
The levels are taken from the extreme highs/lows, but the bar indexes are given for the candles that were actually used to confirm the Low/High. 
This is by design, because it might be misleading to label the extreme, since we didn't use that candle to confirm the Low/High..
@param - there are no parameters. The function uses the chart OHLC.
@returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
     ints for the bar_index of that Low/High
     floats for the values of the recent high/low levels
     floats for the trailing high/low levels (for debug/post-processing)
     bools for market structure bias
 f_trueLowHigh() 
This function finds True Lows and Highs.
A True High is the candle with the highest recent high, which then has its low taken out on close by a subsequent candle (and vice-versa for True Lows).
The difference between this and an Enhanced High is that confirmation requires not just any Simple High, but confirmation of the very candle that has the highest high.
Because of this, confirmation is often later, and multiple Simple Highs and Lows can develop within ranges formed by a single big candle without any of them being confirmed. This is by design.
A True High looks like the intuitive "real high" when you look at the chart. True Lows and Highs must alternate.
@param - there are no parameters. The function uses the chart OHLC.
@returns - boolean values for whether this bar confirms an Enhanced Simple Low/High
     ints for the bar_index of that Low/High
     floats for the values of the recent high/low levels
     floats for the trailing high/low levels (for debug/post-processing)
     bools for market structure bias
TechnicalRating█   OVERVIEW 
This library is a Pine Script™ programmer’s tool for incorporating TradingView's well-known technical ratings within their scripts. The ratings produced by this library are the same as those from the speedometers in the technical analysis summary and the "Rating" indicator in the  Screener , which use the aggregate biases of 26 technical indicators to calculate their results.
█   CONCEPTS 
 Ensemble analysis 
 Ensemble analysis  uses multiple weaker models to produce a potentially stronger one. A common form of ensemble analysis in technical analysis is the usage of aggregate indicators together in hopes of gaining further market insight and reinforcing trading decisions.
 Technical ratings 
 Technical ratings  provide a simplified way to analyze financial markets by combining signals from an ensemble of indicators into a singular value, allowing traders to assess market sentiment more quickly and conveniently than analyzing each constituent separately. By consolidating the signals from multiple indicators into a single rating, traders can more intuitively and easily interpret the "technical health" of the market.
 Calculating the rating value 
Using a variety of  built-in  TA functions and functions from our  ta  library, this script calculates technical ratings for moving averages, oscillators, and their overall result within the `calcRatingAll()` function.
The function uses the script's `calcRatingMA()` function to calculate the moving average technical rating from an ensemble of 15 moving averages and filters:
 • Six  Simple Moving Averages  and six  Exponential Moving Averages  with periods of 10, 20, 30, 50, 100, and 200
 • A  Hull Moving Average  with a period of 9
 • A  Volume-Weighted Moving Average  with a period of 20
 • An  Ichimoku Cloud  with a conversion line length of 9, base length of 26, and leading span B length of 52
The function uses the script's `calcRating()` function to calculate the oscillator technical rating from an ensemble of 11 oscillators:
 •  RSI  with a period of 14
 •  Stochastic  with a %K period of 14, a smoothing period of 3, and a %D period of 3
 •  CCI  with a period of 20
 •  ADX  with a DI length of 14 and an ADX smoothing period of 14
 •  Awesome Oscillator 
 •  Momentum  with a period of 10
 •  MACD  with fast, slow, and signal periods of 12, 26, and 9
 •  Stochastic RSI  with an RSI period of 14, a %K period of 14, a smoothing period of 3, and a %D period of 3
 •  Williams %R  with a period of 14
 •  Bull Bear Power  with a period of 50
 •  Ultimate Oscillator  with fast, middle, and slow lengths of 7, 14, and 28
Each indicator is assigned a value of +1, 0, or -1, representing a bullish, neutral, or bearish rating. The moving average rating is the mean of all ratings that use the `calcRatingMA()` function, and the oscillator rating is the mean of all ratings that use the `calcRating()` function. The overall rating is the mean of the moving average and oscillator ratings, which ranges between +1 and -1. This overall rating, along with the separate MA and oscillator ratings, can be used to gain insight into the technical strength of the market. For a more detailed breakdown of the signals and conditions used to calculate the indicators' ratings, consult our  Help Center  explanation.
 Determining rating status 
The `ratingStatus()` function produces a string representing the status of a series of ratings. The `strongBound` and `weakBound` parameters, with respective default values of 0.5 and 0.1, define the bounds for "strong" and "weak" ratings.
The rating status is determined as follows:
     Rating Value	    Rating Status
   < -strongBound	    Strong Sell
   < -weakBound	            Sell
-weakBound to weakBound	    Neutral
   >  weakBound	            Buy
   >  strongBound	    Strong Buy 
By customizing the `strongBound` and `weakBound` values, traders can tailor the `ratingStatus()` function to fit their trading style or strategy, leading to a more personalized approach to evaluating ratings.
 Look first. Then leap.  
█  FUNCTIONS  
This library contains the following functions:
 calcRatingAll() 
  Calculates 3 ratings (ratings total, MA ratings, indicator ratings) using the aggregate biases of 26 different technical indicators.
  Returns: A 3-element tuple: ( [(float) ratingTotal, (float) ratingOther, (float) ratingMA ].
 countRising(plot) 
  Calculates the number of times the values in the given series increase in value up to a maximum count of 5.
  Parameters:
     plot : (series float) The series of values to check for rising values.
  Returns: (int) The number of times the values in the series increased in value.
 ratingStatus(ratingValue, strongBound, weakBound) 
  Determines the rating status of a given series based on its values and defined bounds.
  Parameters:
     ratingValue : (series float) The series of values to determine the rating status for.
     strongBound : (series float) The upper bound for a "strong" rating.
     weakBound : (series float) The upper bound for a "weak" rating.
  Returns: (string) The rating status of the given series ("Strong Buy", "Buy", "Neutral", "Sell", or "Strong Sell").
TurntLibraryLibrary   "TurntLibrary" 
Collection of functions created for simplification/easy referencing. Includes variations of moving averages, length value oscillators, and a few other simple functions based upon HH/LL values.
 ma(source, length, type) 
  Apply a moving average to a float value
  Parameters:
     source : Value to be used 
     length : Number of bars to include in calculation
     type : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
  Returns: Smoothed value of initial float value
 curve(src, len, lb1, lb2) 
  Exaggerates curves of a float value designed for use as an exit signal.
  Parameters:
     src : Initial value to curve
     len : Number of bars to include in calculation
     lb1 : (Default = 1) First lookback length 
     lb2 : (Default = 2) Second lookback length 
  Returns: Curved Average
 fragma(src, len, space, str) 
  Average of a moving average and the previous value of the moving average
  Parameters:
     src : Initial float value to use
     len : Number of bars to include in calculation
     space : Lookback integer for second half of average
     str : Moving average type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
  Returns: Fragmented Average
 maxmin(x, y) 
  Difference of 2 float values, subtracting the lowest from the highest
  Parameters:
     x : Value 1
     y : Value 2
  Returns: The +Difference between 2 float values
 oscLen(val, type) 
  Variable Length using a oscillator value and a corresponding slope shape ("Incline",Decline","Peak","Trough")
  Parameters:
     val : Oscillator Value to use 
     type : Slope of length curve ("Incline",Decline","Peak","Trough")
  Returns: Variable Length Integer
 hlAverage(val, smooth, max, min, type, include) 
  Average of HH,LL with variable lengths based on the slope shape ("Incline","Decline","Trough") value relative to highest and lowest
  Parameters:
     val : Source Value to use 
     smooth 
     max 
     min 
     type 
     include : Add "val" to the averaging process, instead of more weight to highest or lowest value  
  Returns: Variable Length Average of Highest Lowest "val"
 pct(val) 
  Convert a positive float / price to a percentage of it's highest value on record
  Parameters:
     val : Value To convert to a percentage of it's highest value ever 
  Returns: Percentage
 hlrange(x, len) 
  Difference between Highest High and Lowest Low of float value
  Parameters:
     x : Value to use in calculation
     len : Number of bars to include in calculation
  Returns: Difference
 midpoint(x, len, smooth) 
  The average value of the float's Highest High and Lowest Low in a number of bars
  Parameters:
     x : Value to use in calculation 
     len 
     smooth : (Default=na) Optional smoothing type to use ("SMA","EMA","RMA","WMA","VWAP","SWMA","LRC")
  Returns: Midpoint
Obj_XABCD_HarmonicLibrary   "Obj_XABCD_Harmonic" 
Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
 init_params(pct_error, pct_asym, types, w_e, w_p, w_d) 
  Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
  Parameters:
     pct_error : Allowed % error of leg retracement ratio versus the defined harmonic ratio 
     pct_asym : Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
     types : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
     w_e : Weight of ratio % error (used in score calculation, dft = 1)
     w_p : Weight of PRZ confluence (used in score calculation, dft = 1)
     w_d : Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
  Returns: harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
 init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p) 
  Initialize an xabcd_harmonic object instance. 
       If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
       own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
       Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
       and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
       to re-initialize it (e.g. for re-validation and/or re-scoring).
  Parameters:
     xX : Point X bar index
     xY : Point X price/level
     aX : Point A bar index
     aY : Point A price/level
     bX : Point B bar index
     bY : Point B price/level
     cX : Point C bar index
     cY : Point C price/level
     dX : Point D bar index
     dY : Point D price/level
     params : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
     tp : Pattern type
     p : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
  Returns: xabcd_harmonic object instance if a valid harmonic, else na
 get_name(p) 
  Get the pattern name
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: Pattern name (string)
 get_symbol(p) 
  Get the pattern symbol
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: Pattern symbol (1 byte string)
 get_pid(p) 
  Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: Pattern ID (string)
 set_target(p, target, target_lvl, calc_target) 
  Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
  Parameters:
     p : Instance of xabcd_harmonic object
     target : Target (1 or 2)
     target_lvl : Target price/level (required if calc_target is not specified)
     calc_target : Target to auto calculate (required if target is not specified)
                 Options:  
  Returns: Target price/level (float)
 erase_pattern(p) 
  Erase the pattern
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: p
 draw_pattern(p) 
  Draw the pattern
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: Pattern lines 
 
 erase_label(p) 
  Erase the pattern label
  Parameters:
     p : Instance of xabcd_harmonic object
  Returns: p
 draw_label(p, txt, tooltip, clr, txt_clr) 
  Draw the pattern label. Default text is the pattern name.
  Parameters:
     p : Instance of xabcd_harmonic object
     txt : Label text
     tooltip : Tooltip text
     clr : Label color
     txt_clr : Text color
  Returns: Label
 harmonic_params 
  Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
  Fields:
     pct_error : 		Allowed % error of leg retracement ratio versus the defined harmonic ratio 
     pct_asym 
     types 
     w_e 
     w_p 
     w_d 
 xabcd_harmonic 
  Harmonic Pattern object
  Fields:
     bull : 			Bullish pattern flag 
     tp 
     xX 
     xY 
     aX 
     aY 
     bX 
     bY 
     cX 
     cY 
     dX 
     dY 
     r_xb 
     re_xb 
     r_ac 
     re_ac 
     r_bd 
     re_bd 
     r_xd 
     re_xd 
     score 
     score_eAvg 
     score_prz 
     score_eD 
     prz_bN 
     prz_bF 
     prz_xN 
     prz_xF 
     t1Hit : 		Target 1 flag
     t1 
     t2Hit 
     t2 
     sHit : 			Stop flag
     stop : 			Stop level
     entry : 		Entry level
     eHit 
     eX 
     eY 
     pLines 
     pLabel 
     pid 
     params
ZigZag█   OVERVIEW 
This library is a Pine Script™ programmer’s tool containing custom  user-defined types  and functions to calculate Zig Zag indicators within their scripts. It is not a stand-alone indicator.
Pine Script™ libraries are publications that contain reusable code for importing into Pine Script™ indicators, strategies, and other libraries. For more information on libraries and incorporating them into your scripts, see the  Libraries  section of the Pine Script™  User Manual .
█   CONCEPTS 
 Zig Zag 
 Zig Zag  is a popular indicator that filters out minor price fluctuations to denoise data and emphasize trends. Traders commonly use Zig Zag for trend confirmation, identifying potential support and resistance, and pattern detection. It is formed by identifying significant local high and low points in alternating order and connecting them with straight lines, omitting all other data points from their output. There are several ways to calculate the Zig Zag's data points and the conditions by which its direction changes. This script uses pivots as the data points, which are the highest or lowest values over a defined number of bars before and after them. The direction only reverses when a newly formed pivot deviates from the last Zig Zag point in the opposite direction by an amount greater than or equal to a specified percentage.
To learn more about Zig Zag and how to calculate it, see  this  entry from the Help Center.
█  FOR Pine Script™ CODERS 
 Notes 
This script's architecture utilizes  user-defined types  (UDTs) to create custom  objects  which are the equivalent of variables containing multiple parts, each able to hold independent values of different   types . UDTs are the newest addition to Pine Script™ and the most advanced feature the language has seen to date. The feature's introduction creates a new runway for experienced coders to push the boundaries of Pine. We recommend that newcomers to the language explore the basics first before diving into UDTs and objects. 
 Demonstration Code 
Our example code shows a simple use case by displaying a Zig Zag with user-defined settings. A new ZigZag object is instantiated on the first bar using a Settings object to control its attributes. The   fields  for the Settings object are declared using variables assigned to  input.*  functions, allowing control of the field values from the script's settings. The `update()` function is invoked on each bar to update the ZigZag object's fields and create new  lines  and  labels  when required.
 Look first. Then leap.  
█  TYPES  
This library contains the following types:
 Settings 
  Provides calculation and display attributes to ZigZag objects.
  Fields:
     devThreshold : The minimum percentage deviation from a point before the ZigZag will change direction. 
     depth : The number of bars required for pivot detection. 
     lineColor : Line color. 
     extendLast : Condition allowing a line to connect the most recent pivot with the current close. 
     displayReversalPrice : Condition to display the pivot price in the pivot label. 
     displayCumulativeVolume : Condition to display the cumulative volume for the pivot segment in the pivot label. 
     displayReversalPriceChange : Condition to display the change in price or percent from the previous pivot in the pivot label. 
     differencePriceMode : Reversal change display mode. Options are "Absolute" or "Percent". 
     draw : Condition to display lines and labels.
 Point 
  A coordinate containing time and price information.
  Fields:
     tm : A value in UNIX time. 
     price : A value on the Y axis (price).
 Pivot 
  A level of significance used to determine directional movement or potential support and resistance.
  Fields:
     ln : A line object connecting the `start` and `end` Point objects. 
     lb : A label object to display pivot values. 
     isHigh : A condition to determine if the pivot is a pivot high. 
     vol : Volume for the pivot segment. 
     start : The coordinate of the previous Point.
     end : The coordinate of the current Point.
 ZigZag 
  An object to maintain Zig Zag settings, pivots, and volume.
  Fields:
     settings : Settings object to provide calculation and display attributes.
     pivots : An array of Pivot objects. 
     sumVol : The volume sum for the pivot segment. 
     extend : Pivot object used to project a line from the last pivot to the last bar.
█  FUNCTIONS  
This library contains the following functions:
 lastPivot(this) 
  Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
  Parameters:
     this : (series ZigZag) A ZigZag object. 
  Returns: (Pivot) The last Pivot in the ZigZag.
 update(this) 
  Updates `this` ZigZag object with new pivots, volume, lines, labels.
  Parameters:
     this : (series ZigZag) a ZigZag object.         
  Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
 newInstance(settings) 
  Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
  Parameters:
     settings : (series Settings) A Settings object. 
  Returns: (ZigZag) A new ZigZag instance.
EMAFlowLibrary   "EMAFlow" 
Functions that manipulate a set of 5 MAs created within user-supplied maximum and minimum lengths. The MAs are spaced out (within the range) in a way that approximates how Fibonnaci numbers are spaced.
Using MA flow, as opposed to simple crosses of the minimum and maximum lengths, gives more detail, and can result in faster changes and more resistance to chop, depending how you use it.
 f_emaFlowBias() 
@function f_emaFlowBias: Gives a bullish or bearish bias reading based on the EMA flow from the user-supplied range.
@param int _min: The minimum length of the EMA set.
@param int _max: The maximum length of the EMA set.
@param: string _source: The source for the EMA set. Must be in standard format (open, close, ohlc4, etc.)
@returns: An integer, representing the bias: 1 is bearish, 2 is slightly bearish, 3 is neutral, 4 is slightly bullish, 5 is bullish.
taLibrary   "ta" 
Collection of all custom and enhanced TA indicators. Same as enhanced_ta. But, removed all the displays to make it faster.
 ma(source, maType, length) 
  returns custom moving averages
  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
  Returns: moving average for the given type and length
 atr(maType, length) 
  returns ATR with custom moving average
  Parameters:
     maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
     length : Moving Average Length
  Returns: ATR for the given moving average type and length
 atrpercent(maType, length) 
  returns ATR as percentage of close price
  Parameters:
     maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
     length : Moving Average Length
  Returns: ATR as percentage of close price for the given moving average type and length
 bb(source, maType, length, multiplier, sticky) 
  returns Bollinger band for custom moving average
  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: Bollinger band with custom moving average for given source, length and multiplier
 bbw(source, maType, length, multiplier, sticky) 
  returns Bollinger bandwidth for custom moving average
  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: Bollinger Bandwidth for custom moving average for given source, length and multiplier
 bpercentb(source, maType, length, multiplier, sticky) 
  returns Bollinger Percent B for custom moving average
  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: Bollinger Percent B for custom moving average for given source, length and multiplier
 kc(source, maType, length, multiplier, useTrueRange, sticky) 
  returns Keltner Channel for custom moving average
  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: Keltner Channel for custom moving average for given souce, length and multiplier
 kcw(source, maType, length, multiplier, useTrueRange, sticky) 
  returns Keltner Channel Width with custom moving average
  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: Keltner Channel Width for custom moving average
 kpercentk(source, maType, length, multiplier, useTrueRange, sticky) 
  returns Keltner Channel Percent K Width with custom moving average
  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: Keltner Percent K for given moving average, source, length and multiplier
 dc(length, useAlternateSource, alternateSource, sticky) 
  returns Custom Donchian Channel
  Parameters:
     length : - donchian channel length
     useAlternateSource : - Custom source is used only if useAlternateSource is set to true
     alternateSource : - Custom source
     sticky : - sticky boundaries which will only change when value is outside boundary.
  Returns: Donchian channel
 dcw(length, useAlternateSource, alternateSource, sticky) 
  returns Donchian Channel Width
  Parameters:
     length : - donchian channel length
     useAlternateSource : - Custom source is used only if useAlternateSource is set to true
     alternateSource : - Custom source
     sticky : - sticky boundaries which will only change when value is outside boundary.
  Returns: Donchian channel width
 dpercentd(useAlternateSource, alternateSource, length, sticky) 
  returns Donchian Channel Percent of price
  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: Donchian channel Percent D
 oscillatorRange(source, method, highlowLength, rangeLength, sticky) 
  oscillatorRange - returns Custom overbought/oversold areas for an oscillator input
  Parameters:
     source : - Osillator source such as RSI, COG etc.
     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
     rangeLength : - length used for calculating oversold/overbought range - usually same as oscillator length
     sticky : - overbought, oversold levels won't change unless crossed
  Returns: Dynamic overbought and oversold range for oscillator input
 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: Oscillator value along with dynamic overbought and oversold range for oscillator input
 multibands(bandType, source, maType, length, useTrueRange, sticky, numberOfBands, multiplierStart, multiplierStep) 
  multibands - returns Choice of oscillator with custom overbought/oversold range
  Parameters:
     bandType : - Band type - can be either bb or kc
     source : - custom source if required
     maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
     length : - Oscillator length - not used for TSI
     useTrueRange : - if set to false, uses high-low.
     sticky : - for sticky borders which only change upon source crossover/crossunder
     numberOfBands : - Number of bands to generate
     multiplierStart : - Starting ATR or Standard deviation multiplier for first band
     multiplierStep : - Incremental value for multiplier for each band
  Returns: array of band values sorted in ascending order
 mbandoscillator(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep) 
  mbandoscillator - Multiband oscillator created on the basis of bands
  Parameters:
     bandType : - Band type - can be either bb or kc
     source : - custom source if required
     maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
     length : - Oscillator length - not used for TSI
     useTrueRange : - if set to false, uses high-low.
     stickyBands : - for sticky borders which only change upon source crossover/crossunder for band detection
     numberOfBands : - Number of bands to generate
     multiplierStart : - Starting ATR or Standard deviation multiplier for first band
     multiplierStep : - Incremental value for multiplier for each band
  Returns: oscillator currentStates - Array containing states for last n bars
Hurst Exponent (Dubuc's variation method)Library   "Hurst" 
 hurst(length, samples, hi, lo) 
  Estimate the Hurst Exponent using Dubuc's variation method
  Parameters:
     length : The length of the history window to use. Large values do not cause lag.
     samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
     hi : The high value of the series to analyze.
     lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5.  A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation.  Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price).  Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and  the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com
Traders_Reality_LibLibrary   "Traders_Reality_Lib" 
This library contains common elements used in Traders Reality scripts
 calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor) 
  calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors:  Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors:  Bull bars are blue and bear are violet.
  Parameters:
     pvsraVolume : the instrument volume series (obtained from request.sequrity)
     pvsraHigh : the instrument high series (obtained from request.sequrity)
     pvsraLow : the instrument low series (obtained from request.sequrity)
     pvsraClose : the instrument close series (obtained from request.sequrity)
     pvsraOpen : the instrument open series (obtained from request.sequrity)
     redVectorColor : red vector candle color
     greenVectorColor : green vector candle color
     violetVectorColor : violet/pink vector candle color
     blueVectorColor : blue vector candle color
     darkGreyCandleColor : regular volume candle down candle color - not a vector 
     lightGrayCandleColor : regular volume candle up candle color - not a vector
@return  
 adr(length, barsBack) 
  Parameters:
     length : how many elements of the series to calculate on
     barsBack : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
 adrHigh(adr, fromDo) 
  Calculate the ADR high given an ADR
  Parameters:
     adr : the adr
     fromDo : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
 adrLow(adr, fromDo) 
  Parameters:
     adr : the adr
     fromDo : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
 splitSessionString(sessXTime) 
  given a session in the format 0000-0100:23456 split out the hours and minutes
  Parameters:
     sessXTime : the session time string usually in the format 0000-0100:23456
@return  
 calcSessionStartEnd(sessXTime, gmt) 
  calculate the start and end timestamps of the session
  Parameters:
     sessXTime : the session time string usually in the format 0000-0100:23456 
     gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return  
 drawOpenRange(sessXTime, sessXcol, showOrX, gmt) 
  draw open range for a session
  Parameters:
     sessXTime : session string in the format 0000-0100:23456 
     sessXcol : the color to be used for the opening range box shading
     showOrX : boolean flag to toggle displaying the opening range
     gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
 drawSessionHiLo(sessXTime, show_rectangleX, show_labelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle) 
  Parameters:
     sessXTime : session string in the format 0000-0100:23456 
     show_rectangleX : show the session high and low lines 
     show_labelX : show the session label
     sessXcolLabel : the color to be used for the hi/low lines and label
     sessXLabel : the session label text
     gmt : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     sessionLineStyle : the line stile for the session high low lines 
@return void
 calcDst() 
  calculate market session dst on/off flags 
@return   indicating if DST is on or off for a particular region
 timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis) 
  Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
  Parameters:
     previousDayOfWeek : Monday or Satruday
     hourOfDay : the hour of the day when psy calc is to start
     gmtOffset : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     oneWeekMillis : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
 getdayOpen() 
  get the daily open - basically exchange midnight
@return the daily open value which is float price
 newBar(res) 
  new_bar: check if we're on a new bar within the session in a given resolution
  Parameters:
     res : the desired resolution
@return true/false is a new bar for the session has started
 toPips(val) 
  to_pips Convert value to pips
  Parameters:
     val : the value to convert to pips
@return the value in pips
 rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry : series float the y coordinate of the lable
     rtext : the text of the label
     rstyle : the style for the lable
     rcolor : the color for the label
     valid : a boolean flag that allows for turning on or off a lable
     labelXOffset : how much to offset the label from the current position
 rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry : series float the y coordinate of the lable
     rtext : the text of the label
     rstyle : the style for the lable
     rcolor : the color for the label
     valid : a boolean flag that allows for turning on or off a lable
     labelXOffset : how much to offset the label from the current position
 rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series only on the last bar
  Parameters:
     ry : series float the y coordinate of the lable
     rtext : the text of the label
     rstyle : the style for the lable
     rcolor : the color for the label
     valid : a boolean flag that allows for turning on or off a lable
     labelXOffset : how much to offset the label from the current position
 drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, labelXOffset, validTimeFrame) 
  a function that draws a line and a label for a series
  Parameters:
     xSeries : series float the y coordinate of the line/label
     res : the desired resolution controlling when a new line will start
     tag : the text for the lable
     xColor : the color for the label
     xStyle : the style for the line
     xWidth : the width of the line
     xExtend : extend the line
     isLabelValid : a boolean flag that allows for turning on or off a label
     labelXOffset : how much to offset the label from the current position
     validTimeFrame : a boolean flag that allows for turning on or off a line drawn
 drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, labelXOffset, validTimeFrame) 
  a function that draws a line and a label for the daily open series
  Parameters:
     xSeries : series float the y coordinate of the line/label
     res : the desired resolution controlling when a new line will start
     tag : the text for the lable
     xColor : the color for the label
     xStyle : the style for the line
     xWidth : the width of the line
     xExtend : extend the line
     isLabelValid : a boolean flag that allows for turning on or off a label
     labelXOffset : how much to offset the label from the current position
     validTimeFrame : a boolean flag that allows for turning on or off a line drawn
 drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset) 
  draw a pivot line - the line starts one day into the past
  Parameters:
     pivotLevel : series of the pivot point
     res : the desired resolution
     tag : the text to appear
     pivotColor : the color of the line
     pivotLabelColor : the color of the label
     pivotStyle : the line style
     pivotWidth : the line width
     pivotExtend : extend the line
     isLabelValid : boolean param allows to turn label on and off
     validTimeFrame : only draw the line and label at a valid timeframe
     levelStart : basically when to start drawing the levels
     pivotLabelXOffset : how much to offset the label from its current postion
@return the pivot line series
 getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor) 
  convert the pvsra color to an internal code
  Parameters:
     pvsraColor : the calculated pvsra color
     redVectorColor : the user defined red vector color
     greenVectorColor : the user defined green vector color
     violetVectorColor : the user defined violet vector color
     blueVectorColor : the user defined blue vector color
     lightGrayCandleColor : the user defined regular up candle color
@return pvsra internal code
 updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor) 
  a function that draws the unrecovered vector candle zones
  Parameters:
     pvsra : internal code
     direction : above or below the current pa
     boxArr : the array containing the boxes that need to be updated
     maxlevels : the maximum number of boxes to draw
     pvsraHigh : the pvsra high value series
     pvsraLow : the pvsra low value series
     pvsraOpen : the pvsra open value series
     pvsraClose : the pvsra close value series
     transperancy : the transparencfy of the vecor candle zones
     zoneupdatetype : the zone update type
     zonecolor : the zone color if overriden
     zonetype : the zone type
     borderwidth : the width of the border
     coloroverride : if the color overriden
     redVectorColor : the user defined red vector color
     greenVectorColor : the user defined green vector color
     violetVectorColor : the user defined violet vector color
     blueVectorColor : the user defined blue vector color
     lightGrayCandleColor : the user defined regular up candle color
 cleanarr(arr) 
  clean an array from na values
  Parameters:
     arr : the array to clean
@return if the array was cleaned
 calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST) 
  calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
  Parameters:
     oneWeekMillis : a constant value
     showPsylevels : should psy levels be calculated
     psyType : the type of Psylevels - crypto or forex
     sydDST : is Sydney in DST
@return 






















