NYCSessionLibrary "NYCSession"
Library for New York trading session time functions
@author abneralvarado
@version 1.0
isInNYSession(sessionStart, sessionEnd)
โโDetermines if the current bar is within New York trading session
โโParameters:
โโโโ sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM) like 0930 for 9:30 AM ET
โโโโ sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM) like 1600 for 4:00 PM ET
โโReturns: True if current bar is within the NY session time, false otherwise
getNYSessionStartTime(lookback, sessionStart)
โโGets the start time of NY session for a given bar
โโParameters:
โโโโ lookback (simple int) : Bar index to check (0 is current bar)
โโโโ sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
โโReturns: Unix timestamp for the start of NY session on the given bar's date
getNYSessionEndTime(lookback, sessionEnd)
โโGets the end time of NY session for a given bar
โโParameters:
โโโโ lookback (simple int) : Bar index to check (0 is current bar)
โโโโ sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
โโReturns: Unix timestamp for the end of NY session on the given bar's date
isNYSessionOpen(sessionStart)
โโChecks if current bar opens the NY session
โโParameters:
โโโโ sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
โโReturns: True if current bar marks the session opening, false otherwise
isNYSessionClose(sessionEnd)
โโChecks if current bar closes the NY session
โโParameters:
โโโโ sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
โโReturns: True if current bar marks the session closing, false otherwise
isWeekday()
โโDetermines if the current day is a weekday (Mon-Fri)
โโReturns: True if current bar is on a weekday, false otherwise
getSessionBackgroundColor(sessionStart, sessionEnd, bgColor)
โโGets session background color with transparency
โโParameters:
โโโโ sessionStart (simple int) : Starting time of NY session in 24hr format (HHMM)
โโโโ sessionEnd (simple int) : Ending time of NY session in 24hr format (HHMM)
โโโโ bgColor (color) : Background color for session highlighting
โโReturns: Color value for background or na if not in session
Penunjuk dan strategi
DoppelLibLibrary "DoppelLib"
getDailyClose(offset)
โโReturns the daily close for a specific offset.
For each offset value (from 1 to 21), the function uses a static request.security() call
to retrieve the daily close from the previous day at the specified offset.
โโParameters:
โโโโ offset (int) : (int) The offset value (from 1 to 21) representing the desired close value.
โโReturns: (float) The daily close for the specified offset or na if offset is out of range.
isVolumeAboveThreshold(vol, mediaPeriod, thresholdPercent)
โโChecks if the current volume is above the threshold based on its moving average.
The threshold is calculated as the average volume plus a percentage increment.
โโParameters:
โโโโ vol (float) : (series float) The volume series (e.g. the chart volume).
โโโโ mediaPeriod (int) : (int) The period for calculating the moving average.
โโโโ thresholdPercent (float) : (float) The percentage to add to the average for the threshold.
โโReturns: (bool) True if the volume exceeds the threshold, false otherwise.
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
โโCalculates the PVSRA candle color, determines if a vector candle has appeared,
and returns additional support parameters (average volume, volume spread, highest volume spread).
- "High" (Climax): volume >= 200% of the average OR (volume * candle spread) >= highest spread over the previous 10 bars.
-> Bull candle: green; Bear candle: red.
- "Medium": volume >= 150% of the average.
-> Bull candle: blue; Bear candle: violet.
- Otherwise, default (non-vector) candle colors are used.
โโParameters:
โโโโ pvsraVolume (float) : (series float) Volume series.
โโโโ pvsraHigh (float) : (series float) High price series.
โโโโ pvsraLow (float) : (series float) Low price series.
โโโโ pvsraClose (float) : (series float) Close price series.
โโโโ pvsraOpen (float) : (series float) Open price series.
โโโโ redVectorColor (simple color) : (simple color) Color for bearish candle in high scenario.
โโโโ greenVectorColor (simple color) : (simple color) Color for bullish candle in high scenario.
โโโโ violetVectorColor (simple color) : (simple color) Color for bearish candle in medium scenario.
โโโโ blueVectorColor (simple color) : (simple color) Color for bullish candle in medium scenario.
โโโโ darkGreyCandleColor (simple color) : (simple color) Color for bearish candle in non-vector situation.
โโโโ lightGrayCandleColor (simple color) : (simple color) Color for bullish candle in non-vector situation.
โโReturns: (tuple) A tuple containing: .
NR_VersatilitiesLibrary "NR_Versatilities"
Versatilities (aka, Versatile Utilities) includes:
- Seventeen Price Variants returned as a tuple,
- Eight Smoothing functions rolled into one,
- Pick any Past Value from any series with offset,
- Or just the previous value from any series.
pastVal(src, len)
โโFetches past value from src that came len distance ago
โโParameters:
โโโโ src (float) : source series
โโโโ len (int) : lookback distance - (optional) default is 1
โโReturns: latest src if len <= 0, else src
previous(src)
โโFetches past value from src that came len distance ago
โโParameters:
โโโโ src (float) : source series
โโReturns: previous value in the series if found, else current value
price_variants()
โโComputes Several different averages using current and previous OHLC values
โโReturns: Seventeen Uncommon Average Price Combinations
dynamic_MA(matyp, masrc, malen, lsmaoff, almasgm, almaoff, almaflr)
โโDynamically computes Eight different MAs on-demand individually, or an average of all taken together
โโParameters:
โโโโ matyp (string) : pick one of these MAs - ALMA, EMA, HMA, LSMA, RMA, SMA, SWMA, WMA, ALL
โโโโ masrc (float) : source series to compute MA
โโโโ malen (simple int) : lookback distance for MA
โโโโ lsmaoff (simple int) : optional LSMA offset - default is 0
โโโโ almasgm (simple float) : optional ALMA sigma - default is 5
โโโโ almaoff (simple float) : optional ALMA offset - default is 0.5
โโโโ almaflr (simple bool) : optional ALMA floor flag - default is false
โโReturns: MA series for chosen type or, an average of all of them, if chosen so
projectiontrackingLibrary "projectiontracking"
Library contains few data structures and methods for tracking harmonic patterns and projections via pinescript.
method erase(this)
โโerase Harmonic Projection Drawing
โโNamespace types: HarmonicProjectionDrawing
โโParameters:
โโโโ this (HarmonicProjectionDrawing) : HarmonicProjectionDrawing object
โโReturns: void
method erase(this)
โโerase HarmonicProjection
โโNamespace types: HarmonicProjection
โโParameters:
โโโโ this (HarmonicProjection) : HarmonicProjection object
โโReturns: void
method draw(this)
โโdraw HarmonicProjection
โโNamespace types: HarmonicProjection
โโParameters:
โโโโ this (HarmonicProjection) : HarmonicProjection object
โโReturns: HarmonicProjection object
method getRanges(projectionPrzRanges, dir)
โโConvert PRZRange to Projection ranges
โโNamespace types: array
โโParameters:
โโโโ projectionPrzRanges (array type from Trendoscope/HarmonicMapLib/1) : array of PrzRange objects
โโโโ dir (int) : Projection direction
โโReturns: array
ProjectionRange
โโHarmonic Projection Range
โโFields:
โโโโ patterns (array) : array of pattern names
โโโโ start (series float) : Start Range
โโโโ end (series float) : End Range
โโโโ status (series int) : Projection Status
ProjectionProperties
โโHarmonic Projection Properties
โโFields:
โโโโ fillMajorTriangles (series bool) : Use linefill for major triangles
โโโโ fillMinorTriangles (series bool) : Use linefill for minor triangles
โโโโ majorFillTransparency (series int) : transparency of major triangles
โโโโ minorFillTransparency (series int) : transparency of minor triangles
โโโโ showXABC (series bool) : Show XABC labels
โโโโ lblSizePivots (series string) : Pivot labels size
โโโโ showRatios (series bool) : Show ratio labels
โโโโ useLogScaleForScan (series bool) : Log scale is used for scanning projections
โโโโ activateOnB (series bool) : Activate projections on reaching B
โโโโ activationRatio (series float) : Use activation ratio for activation
โโโโ confirmationRatio (series float) : Confirmation ratio of projection before removal
HarmonicProjectionDrawing
โโHarmonic Projection Projection drawing objects
โโFields:
โโโโ xa (series line) : line xa
โโโโ ab (series line) : line ab
โโโโ bc (series line) : line bc
โโโโ xb (series line) : line xb
โโโโ ac (series line) : line ac
โโโโ x (series label) : Pivot label x
โโโโ a (series label) : Pivot label a
โโโโ b (series label) : Pivot label b
โโโโ c (series label) : Pivot label c
โโโโ xabRatio (series label) : Label XAB Ratio
โโโโ abcRatio (series label) : Label ABC Ratio
HarmonicProjection
โโHarmonic Projection Projection object
โโFields:
โโโโ patternId (series int) : id of the pattern
โโโโ dir (series int) : projection direction
โโโโ x (chart.point) : Pivot X
โโโโ a (chart.point) : Pivot A
โโโโ b (chart.point) : Pivot B
โโโโ c (chart.point) : Pivot C
โโโโ patternColor (series color) : Color in which pattern is displayed
โโโโ przRange (PrzRange type from Trendoscope/HarmonicMapLib/1) : PRZ Range
โโโโ activationPrice (series float) : Projection activation price
โโโโ reversalPrice (series float) : Projection reversal price
โโโโ status (series int) : Projection status
โโโโ properties (ProjectionProperties) : Projection properties
โโโโ projectionRanges (array) : array of Projection Ranges
โโโโ initialD (series float) : Initial D pivot
โโโโ d (chart.point) : Pivot D
โโโโ drawing (HarmonicProjectionDrawing) : HarmonicProjectionDrawing Object
HarmonicMapLibLibrary "HarmonicMapLib"
Harmonic Pattern Library implementation utilising maps
method tostring(this)
โโconvert Range value to string
โโNamespace types: Range
โโParameters:
โโโโ this (Range) : Range value
โโReturns: converted string representation
method tostring(this)
โโconvert array of Range value to string
โโNamespace types: array
โโParameters:
โโโโ this (array) : array object
โโReturns: converted string representation
method tostring(this)
โโconvert map of string to Range value to string
โโNamespace types: map
โโParameters:
โโโโ this (map) : map object
โโReturns: converted string representation
method tostring(this)
โโconvert RatioMap to string
โโNamespace types: RatioMap
โโParameters:
โโโโ this (RatioMap) : RatioMap object
โโReturns: converted string representation
method tostring(this)
โโconvert array of RatioMap to string
โโNamespace types: array
โโParameters:
โโโโ this (array) : array object
โโReturns: converted string representation
method tostring(this)
โโconvert map of string to RatioMap to string
โโNamespace types: map
โโParameters:
โโโโ this (map) : map object
โโReturns: converted string representation
method tostring(this)
โโconvert map of string to bool to string
โโNamespace types: map
โโParameters:
โโโโ this (map) : map object
โโReturns: converted string representation
method tostring(this)
โโconvert PrzRange to string
โโNamespace types: PrzRange
โโParameters:
โโโโ this (PrzRange) : PrzRange object
โโReturns: converted string representation
method tostring(this)
โโconvert array of PrzRange to string
โโNamespace types: array
โโParameters:
โโโโ this (array) : array object
โโReturns: converted string representation
getHarmonicMap()
โโCreates the RatioMap for harmonic patterns
โโReturns: map haronic ratio rules for all patterns
method evaluate(patternsMap, pattern, ratioRange, properties, ratioValue)
โโevaluates harmonic ratio range
โโNamespace types: map
โโParameters:
โโโโ patternsMap (map) : parameter containing valid pattern names
โโโโ pattern (string) : Pattern type to be evaluated
โโโโ ratioRange (Range) : ratio range to be checked
โโโโ properties (ScanProperties) : Scan Properties
โโโโ ratioValue (float)
โโReturns: void
method evaluate(przRange, pattern, ratioRange, priceRange, properties)
โโEvaluate PRZ ranges
โโNamespace types: map
โโParameters:
โโโโ przRange (map)
โโโโ pattern (string) : Pattern name
โโโโ ratioRange (Range) : Range of ratio for the pattern
โโโโ priceRange (Range) : Price range based on ratio
โโโโ properties (ScanProperties) : ScanProperties object
โโReturns: void
method scanRatio(currentPatterns, rules, properties, ratioName, ratioValue)
โโScan for particular named ratio of harmonic pattern to filter valid patterns
โโNamespace types: map
โโParameters:
โโโโ currentPatterns (map) : Current valid patterns map
โโโโ rules (map) : map Harmonic ratio rules
โโโโ properties (ScanProperties) : ScanProperties object
โโโโ ratioName (string) : Specific ratio name
โโโโ ratioValue (float) : ratio value to be checked
โโReturns: updated currentPatterns object
method scanPatterns(patterns, x, a, b, c, d, properties)
โโScan for patterns based on X, A, B, C, D values
โโNamespace types: map
โโParameters:
โโโโ patterns (map) : List of allowed patterns
โโโโ x (float) : X coordinate
โโโโ a (float) : A coordinate
โโโโ b (float) : B coordinate
โโโโ c (float) : C coordinate
โโโโ d (float) : D coordinate
โโโโ properties (ScanProperties) : ScanProperties object. If na, default values are initialised
โโReturns: updated valid patterns map
method scanProjections(patterns, x, a, b, c, properties)
โโScan for projections based on X, A, B, C values
โโNamespace types: map
โโParameters:
โโโโ patterns (map) : List of allowed patterns
โโโโ x (float) : X coordinate
โโโโ a (float) : A coordinate
โโโโ b (float) : B coordinate
โโโโ c (float) : C coordinate
โโโโ properties (ScanProperties) : ScanProperties object. If na, default values are initialised
โโReturns: updated valid projections map
method merge(this, other)
โโmerge two ranges into one
โโNamespace types: Range
โโParameters:
โโโโ this (Range) : first range
โโโโ other (Range) : second range
โโReturns: combined range
method union(this, other)
โโunion of two ranges into one
โโNamespace types: Range
โโParameters:
โโโโ this (Range) : first range
โโโโ other (Range) : second range
โโReturns: union range
method overlaps(this, other)
โโchecks if two ranges intersect
โโNamespace types: Range
โโParameters:
โโโโ this (Range) : first range
โโโโ other (Range) : second range
โโReturns: true if intersects, false otherwise
method consolidate(this)
โโConsolidate ranges into PRZ
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of Ranges
โโReturns: consolidated PRZ
method consolidateMany(this)
โโConsolidate ranges into multiple PRZ ranges
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of Ranges
โโReturns: consolidated array of PRZ ranges
method getRange(currentPatterns, x, a, b, c, properties)
โโGet D range based on X, A, B, C coordinates for the current patterns
โโNamespace types: map
โโParameters:
โโโโ currentPatterns (map) : List of valid patterns
โโโโ x (float) : X coordinate
โโโโ a (float) : A coordinate
โโโโ b (float) : B coordinate
โโโโ c (float) : C coordinate
โโโโ properties (ScanProperties) : ScanProperties object. If na, default values are initialised
โโReturns: map of D ranges
method getPrzRange(currentPatterns, x, a, b, c, properties)
โโGet PRZ range based on X, A, B, C coordinates for the current patterns
โโNamespace types: map
โโParameters:
โโโโ currentPatterns (map) : List of valid patterns
โโโโ x (float) : X coordinate
โโโโ a (float) : A coordinate
โโโโ b (float) : B coordinate
โโโโ c (float) : C coordinate
โโโโ properties (ScanProperties) : ScanProperties object. If na, default values are initialised
โโReturns: PRZRange for the pattern
method getProjectionRanges(currentPatterns, x, a, b, c, properties)
โโGet projection range based on X, A, B, C coordinates for the current patterns
โโNamespace types: map
โโParameters:
โโโโ currentPatterns (map) : List of valid patterns
โโโโ x (float) : X coordinate
โโโโ a (float) : A coordinate
โโโโ b (float) : B coordinate
โโโโ c (float) : C coordinate
โโโโ properties (ScanProperties) : ScanProperties object. If na, default values are initialised
โโReturns: array of projection ranges
Range
โโCollection of range values
โโFields:
โโโโ values (array) : array of float values
RatioMap
โโratio map for pattern
โโFields:
โโโโ ratioMap (map) : map of string to Range (array of float)
ScanProperties
โโPattern Scanning properties
โโFields:
โโโโ strictMode (series bool) : strict scanning mode will check for overflows
โโโโ logScale (series bool) : scan ratios in log scale
โโโโ errorMin (series float) : min error threshold
โโโโ errorMax (series float)
โโโโ mintick (series float) : minimum tick value of price
PrzRange
โโPotential reversal zone range
โโFields:
โโโโ patterns (array) : array of pattern names for the given XABCD combination
โโโโ prz (Range) : PRZ range
datastructuresLibrary "datastructures"
Collection of complex data structures not generally present as part of pinescript and can be used for collection and transformation of the data
method init(this)
โโinitialise StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet to be initialised
โโReturns: current object of StringSet
method add(this, value)
โโadd value to StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
@value the key of stringset to be set
โโโโ value (string)
โโReturns: current object of StringSet
method clear(this)
โโclear StringSet contents
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
โโReturns: current object of StringSet
method remove(this, value)
โโremove value from StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
@value the key of stringset to be removed
โโโโ value (string)
โโReturns: current object of StringSet
method size(this)
โโget size of the StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
โโReturns: size of StringSet map
method isEmpty(this)
โโcheck if stringset is empty
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
โโReturns: true if empty else returns false
method iterator(this)
โโget values of the StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
โโReturns: values of StringSet
method contains(this, value)
โโcheck if value is present in StringSet
โโNamespace types: StringSet
โโParameters:
โโโโ this (StringSet) : StringSet object
โโโโ value (string)
โโReturns: true if Value is present. False otherwise
method initialiseCountMap(types, numberOfStates)
โโInitialise a new map of string to Count
โโNamespace types: array
โโParameters:
โโโโ types (array) : array of string containing map keys
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method initialiseCountMap(types, numberOfStates)
โโInitialise a new map of string to Count
โโNamespace types: map
โโParameters:
โโโโ types (map) : map containing types and configurable boolean flag
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method get(this, key, n)
โโget count based on primary string key and secondary int key
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to to Count
โโโโ key (string) : primary key
โโโโ n (int) : secondary key
โโReturns: derived count from map of map
method get(this, key, n)
โโget array of int associated with key and n
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to to MapToInts
โโโโ key (string) : primary string key
โโโโ n (int) : secondary int key
โโReturns: derived array of int for the given key combination
method get(this, key, n)
โโget array of float associated with key and n
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to to MapToFloats
โโโโ key (string) : primary string key
โโโโ n (int) : secondary int key
โโReturns: derived array of float
method get(this, key)
โโget values of Ints based on key
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to Ints
โโโโ key (string) : string key
โโReturns: values inside Ints object associated in the map
method set(this, key, n, value)
โโset count for specific primary and secondary key
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to to Count
โโโโ key (string) : primary string key
โโโโ n (int) : secondary int key
โโโโ value (int) : the new count value to be set
โโReturns: updated value for key and n
method increment(this, key, n)
โโincrement count for specific primary and secondary key
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to to Count
โโโโ key (string) : primary string key
โโโโ n (int) : secondary int key
โโReturns: incremented value
method increment(this, key, n)
โโintcrement the value of Ints based on key and n (secondary key)
โโNamespace types: map
โโParameters:
โโโโ this (map) : map of string to Ints
โโโโ key (string) : string key
โโโโ n (int) : secondary int key
โโReturns: incremented nth object of Ints associated with key
method initialiseIntsMap(types, numberOfStates)
โโInitialise a new map of string to Map to Ints
โโNamespace types: array
โโParameters:
โโโโ types (array) : array of string containing map keys
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method initialiseIntsMap(types, numberOfStates)
โโInitialise a new map of string to Map to Ints
โโNamespace types: map
โโParameters:
โโโโ types (map) : map with boolean flag
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method initialiseFloatsMap(types, numberOfStates)
โโInitialise a new map of string to Map to Floats
โโNamespace types: array
โโParameters:
โโโโ types (array) : array of string containing map keys
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method initialiseFloatsMap(types, numberOfStates)
โโInitialise a new map of string to Map to Floats
โโNamespace types: map
โโParameters:
โโโโ types (map) : map with boolean flag
โโโโ numberOfStates (int) : number of items to be tracked for each type
โโReturns: new map() with empty initialisation
method initialiseMapOfInts(types, numberOfStates)
โโInitialise map of two dimentional Ints based on types and number of states
โโNamespace types: array
โโParameters:
โโโโ types (array) : types array for which a new Map to Ints to be created
โโโโ numberOfStates (int) : number of states for which the Ints needs to be initialised
โโReturns: new map of string to two dimension array of int (Ints)
method initialiseMapOfInts(types, numberOfStates)
โโInitialise map of two dimentional Ints based on types and number of states
โโNamespace types: map
โโParameters:
โโโโ types (map) : types map for which a new Map to Ints to be created along with bool flag
โโโโ numberOfStates (int) : number of states for which the Ints needs to be initialised
โโReturns: new map of string to two dimension array of int (Ints)
StringSet
โโSet implementation using map
โโFields:
โโโโ strSet (map) : map of string to bool
Count
โโtype containing map of int to int
โโFields:
โโโโ count (map) : map of int to int used for counting
Ints
โโcustom type to enable array of array of int
โโFields:
โโโโ values (array) : int array
Floats
โโcustom type to enable array of array of float
โโFields:
โโโโ values (array) : float array
MapToInts
โโtype containing map of int to int array
โโFields:
โโโโ vmap (map) : map of int to Ints used as counting collection
MapToFloats
โโtype containing map of int to float array
โโFields:
โโโโ vmap (map) : map of int to Floats used as floating stat collection
drawingutilsLibrary "drawingutils"
methods used in my scripts for some basic and customized drawings and arrays.
method line(this, p1, p2, lineColor, style, width, xloc, extend)
โโDraws line and adds to the array
โโNamespace types: array
โโParameters:
โโโโ this (array) : array to which the created line needs to be added
โโโโ p1 (chart.point) : point1 of the line
โโโโ p2 (chart.point) : point2 of the line
โโโโ lineColor (color) : line color
โโโโ style (string) : line style
โโโโ width (int) : line width
โโโโ xloc (string) : xloc.bar_index or xloc.bar_time
โโโโ extend (string) : default is extend.none
โโReturns: line created
method label(this, p, txt, tooltip, xloc, yloc, color, style, textcolor, size, textalign)
โโDraws label and adds to the array
โโNamespace types: array
โโParameters:
โโโโ this (array) : array to which the created label needs to be added
โโโโ p (chart.point) : point at which the label needs to be drawn
โโโโ txt (string) : label text
โโโโ tooltip (string) : tooltip text
โโโโ xloc (string) : xloc value - xloc.bar_index or xloc.bar_time
โโโโ yloc (string) : y location of the label
โโโโ color (color) : label color
โโโโ style (string) : label style
โโโโ textcolor (color) : label text color
โโโโ size (string) : Size of the label
โโโโ textalign (string) : text alignment
โโReturns: label created
method linefill(this, ln1, ln2, fillColor, transparency)
โโDraws linefill and adds to array
โโNamespace types: array
โโParameters:
โโโโ this (array) : array to which the created linefill needs to be added
โโโโ ln1 (line) : line1 of the fill
โโโโ ln2 (line) : line2 of the fill
โโโโ fillColor (color) : fill Color
โโโโ transparency (int) : fill transparency
โโReturns: linefill created
draw_labelled_line(target, lblText, linecolor, labelcolor, index, highlight, linesArray, labelsArray, highlightSize, tinySize, yloc, textalign)
โโDraws labelled line
โโParameters:
โโโโ target (float) : target price
โโโโ lblText (string) : label text
โโโโ linecolor (color) : line color
โโโโ labelcolor (color) : label color
โโโโ index (int) : index to calculate the distance offset
โโโโ highlight (bool) : highlight true/false
โโโโ linesArray (array) : array of lines where the created line is added
โโโโ labelsArray (array) : array of labels where the created label is added
โโโโ highlightSize (string) : Size of highlighted text
โโโโ tinySize (string) : size of non highlighted text
โโโโ yloc (string) : y location
โโโโ textalign (string) : text alignment
โโReturns: void
draw_labelled_box(y1, y2, labelColor, labelText, index, boxArray, labelArray, borderColor, borderStyle, borderWidth, textAlign, highlight, highLightLabel)
โโDraws custom labelled box
โโParameters:
โโโโ y1 (float) : price 1 of the box
โโโโ y2 (float) : price 2 of the box
โโโโ labelColor (color) : label color
โโโโ labelText (string) : label text
โโโโ index (int) : index to calculate the offset distance
โโโโ boxArray (array) : box array to which the box needs to be added
โโโโ labelArray (array) : label array to which the label needs to be added
โโโโ borderColor (color) : border color
โโโโ borderStyle (string) : border style
โโโโ borderWidth (int) : border width
โโโโ textAlign (string) : text align of the label
โโโโ highlight (bool) : highlight label text
โโโโ highLightLabel (bool) : highlight label size
โโReturns: void
MTFDataLibrary "MTFData"
Functions to store multi timeframe candle data and swing points.
getCandleData(timeframe, openArray, highArray, lowArray, closeArray, timeArray, olcLookback, alltfs_olcLookback, tfIndex)
โโStores current or higher timeframe candle data in arrays.
โโParameters:
โโโโ timeframe (string) : The timeframe, for example "240" for 4h
โโโโ openArray (array) : An array to store the candle open price
โโโโ highArray (array) : An array to store the candle high price
โโโโ lowArray (array) : An array to store the candle low price
โโโโ closeArray (array) : An array to store the candle close price
โโโโ timeArray (array) : An array to store the candle time
โโโโ olcLookback (int) : The history reference of the lookback limiting candle
โโโโ alltfs_olcLookback (array) : An array holding the candle time of olcLookback candles ago, which can be used for limiting lookbacks
โโโโ tfIndex (int) : The timeframe's index in the alltfs_olcLookback array
โโReturns: true if the timeframe changed
trackHiLo(tfchange, timeframe, openArray, highArray, lowArray, closeArray, timeArray, highWickArray, highBodyArray, highTimeArray, lowWickArray, lowBodyArray, lowTimeArray, alltfs_olcLookback, tfIndex)
โโStores current or higher timeframe swingpoint data into arrays.
โโParameters:
โโโโ tfchange (bool) : Must be true when the timeframe has changed (a new candle has opened)
โโโโ timeframe (string) : The timeframe, for example "240" for 4h
โโโโ openArray (array) : An array that stores the timeframe's candle open price
โโโโ highArray (array) : An array that stores the timeframe's candle high price
โโโโ lowArray (array) : An array that stores the timeframe's candle low price
โโโโ closeArray (array) : An array that stores the timeframe's candle close price
โโโโ timeArray (array) : An array that stores the timeframe's candle time
โโโโ highWickArray (array) : An array to store the swing high price
โโโโ highBodyArray (array) : An array to store the swing high's highest body price
โโโโ highTimeArray (array) : An array to store the swing high candle's time
โโโโ lowWickArray (array) : An array to store the swing low price
โโโโ lowBodyArray (array) : An array to store the swing low's lowest body price
โโโโ lowTimeArray (array) : An array to store the swing high candle's time
โโโโ alltfs_olcLookback (array) : An array holding the time of the max allowed swing point age
โโโโ tfIndex (int) : The timeframe's index in the alltfs_olcLookback array
โโReturns: Nothing. The array handling happens inside the function.
tfReadable(tfInSec)
โโConverts a timeframe string ("240") into a more readable string ("4h").
โโParameters:
โโโโ tfInSec (int) : The timeframe that should be converted, as timeframe.in_seconds()
โโReturns: A more readable timeframe string
TrendLibrary "Trend"
calculateSlopeTrend(source, length, thresholdMultiplier)
โโParameters:
โโโโ source (float)
โโโโ length (int)
โโโโ thresholdMultiplier (float)
Purpose:
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
Parameters:
`source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
`length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
`thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
Calculation Steps:
Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`:
If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
Return Value:
The function returns an integer representing the determined trend direction:
`1`: Upward trend
`-1`: Downward trend
`0`: Flat trend
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
TimeframeUtilsCustomLibrary "TimeframeUtilsCustom"
Timeframe utilities library
f_timeframe_to_minutes(tf)
โโConverts timeframe string to minutes
โโParameters:
โโโโ tf (string) : String representation of timeframe
โโReturns: Number of minutes in the given timeframe
f_bars_for_hours(timeframe_minutes, hours)
โโCalculate number of bars for a specified time period
โโParameters:
โโโโ timeframe_minutes (int) : Current timeframe in minutes
โโโโ hours (int) : Number of hours to calculate bars for
โโReturns: Number of bars representing the specified hours
f_bars_for_days(timeframe_minutes, days)
โโCalculate number of bars for a specified number of days
โโParameters:
โโโโ timeframe_minutes (int) : Current timeframe in minutes
โโโโ days (int) : Number of days to calculate bars for
โโReturns: Number of bars representing the specified days
PivotLabelsLibrary "PivotLabels"
drawPivots(qtyLabels, leftLegs, rightLegs)
โโDisplays a label for each of the last `qtyLabels` pivots.
Colors high pivots in green, low pivots in red, and breached pivots in gray.
โโParameters:
โโโโ qtyLabels (int) : (simple int) Quantity of last labels to display.
โโโโ leftLegs (int) : (simple int) Left pivot legs.
โโโโ rightLegs (int) : (simple int) Right pivot legs.
โโReturns: Nothing.
FA_PA_LIBLibrary "FA_PA_LIB"
A collection of custom tools & utility functions commonly used for coding Dr Al Brooks, Price Action System with my scripts
getBodySize()
โโGets the current candle's body size (in POINTS, divide by 10 to get pips)
โโReturns: The current candle's body size in POINTS
getTopWickSize()
โโGets the current candle's top wick size (in POINTS, divide by 10 to get pips)
โโReturns: The current candle's top wick size in POINTS
getTopWickPercent()
โโGets the current candle's top wick size (in POINTS, divide by 10 to get pips)
โโReturns: Percent of total candle width that is occupied by the upper wick
getBottomWickSize()
โโGets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
โโReturns: The current candle's bottom wick size in POINTS
getBottomWickPercent()
โโGets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
โโReturns: Percent of total candle width that is occupied by the lower wick
getBarMidPoint()
โโGets the current candle's midpoint wick to wick
โโReturns: The current candle's mid point
getBodyPercent()
โโGets the current candle's body size as a percentage of its entire size including its wicks
โโReturns: The current candle's body size percentage (00.00)
bullFib(priceLow, priceHigh, fibRatio)
โโCalculates a bullish fibonacci value
โโParameters:
โโโโ priceLow (float) : The lowest price point
โโโโ priceHigh (float) : The highest price point
โโโโ fibRatio (float) : The fibonacci % ratio to calculate
โโReturns: The fibonacci value of the given ratio between the two price points
bearFib(priceLow, priceHigh, fibRatio)
โโCalculates a bearish fibonacci value
โโParameters:
โโโโ priceLow (float) : The lowest price point
โโโโ priceHigh (float) : The highest price point
โโโโ fibRatio (float) : The fibonacci % ratio to calculate
โโReturns: The fibonacci value of the given ratio between the two price points
isBr()
โโChecks if the current bar is a Bear Bar
โโReturns: A boolean - true if the current bar is bear candle
isBl()
โโChecks if the current bar is a Bull Bar
โโReturns: A boolean - true if the current bar is Bull candle
isTrendBar()
โโChecks if the current bar is a Trend Bar. Candle that its body size is greater than 50% of entire candle size
โโReturns: A boolean - true if the current bar is Trend candle
isBlTrendBar()
โโChecks if the current bar is a Bull Trend Bar. Bullish candle that its body size is greater than 50% of entire candle size
โโReturns: A boolean - true if the current bar is Bull Trend candle
isBrTrendBar()
โโChecks if the current bar is a Bull Trend Bar. Bullish candle that its body size is greater than 50% of entire candle size
โโReturns: A boolean - true if the current bar is Bull Trend candle
isBlRevB()
โโChecks if the current bar is a Bull Reversal Bar. Bullish candle that closes on upper half of candle body
โโReturns: A boolean - true if the current bar is Bull Reversal candle
isBrRevB()
โโChecks if the current bar is a Bear Reversal Bar. BulBearish candle that closes on lower half of candle body
โโReturns: A boolean - true if the current bar is Bear Reversal candle
isDoji(wickSize, bodySize)
โโChecks if the current bar is a doji candle based on the given parameters
โโParameters:
โโโโ wickSize (float) : (default=2) The maximum top wick size compared to the bottom (and vice versa)
โโโโ bodySize (float) : (default=0.05) The maximum body size as a percentage compared to the entire candle size
โโReturns: A boolean - true if the current bar matches the requirements of a doji candle
isHammer(fib, colorMatch)
โโChecks if the current bar is a hammer candle based on the given parameters
โโParameters:
โโโโ fib (float) : (default=0.382) The fib to base candle body on
โโโโ colorMatch (bool) : (default=true) Does the candle need to be green? (true/false)
โโReturns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(fib, colorMatch)
โโChecks if the current bar is a shooting star candle based on the given parameters
โโParameters:
โโโโ fib (float) : (default=0.382) The fib to base candle body on
โโโโ colorMatch (bool) : (default=false) Does the candle need to be red? (true/false)
โโReturns: A boolean - true if the current bar matches the requirements of a shooting star candle
isBlOB()
โโDetects Bullish outside bars(OB)
โโReturns: Returns true if the current bar is a bull outside bar
isBrOB()
โโDetects Bearish outside bars(OB)
โโReturns: Returns true if the current bar is a bear outside bar
bollingerBandsV2Library "bollingerBandsV2"
Bollinger bands related functions
get_multiple_bollinger_bands(stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, length, source)
โโ: Calculates 7 sets of bollinger bands, with 7 different standard deviations
โโParameters:
โโโโ stdv1 (float) : (simple int): standard deviation 1
โโโโ stdv2 (float) : (simple int): standard deviation 2
โโโโ stdv3 (float) : (simple int): standard deviation 3
โโโโ stdv4 (float) : (simple int): standard deviation 4
โโโโ stdv5 (float) : (simple int): standard deviation 5
โโโโ stdv6 (float) : (simple int): standard deviation 6
โโโโ stdv7 (float) : (simple int): standard deviation 7
โโโโ length (simple int) : (simple int): Length for the bands
โโโโ source (float) : (simple float): source for the calculation
โโReturns: : Returns 8 levels plus the range of all the levels.
get_bb_volatility(bb_highest, bb_lowest, ma_length, lookback)
โโ: Provides a volatility indicator based on Bollinger Bands, and indicates wheather the volatility is increasing or decreasing.
โโParameters:
โโโโ bb_highest (float) : (simple float): Top Bollinger Band on which to calculate the range.
โโโโ bb_lowest (float) : (simple float): Bottom Bollinger Band on which to calculate the range.
โโโโ ma_length (simple int) : (simple int): Length to use in the smoothing of Bollinger Bands range.
โโโโ lookback (int) : (simple int): Lookback period to identify a change in the Bollinger Bands range.
โโReturns: : Returns 8 levels plus the range of all the levels.
get_bbVolatility_data(source, length, stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, trend_direction)
โโ: Generates Bollinger Bands Volatility
โโParameters:
โโโโ source (float) : (float): Source for Bollinger Bands
โโโโ length (simple int) : (int): Length for Bollinger Bands
โโโโ stdv1 (int) : (int): Standard Deviation 1
โโโโ stdv2 (int) : (int): Standard Deviation 2
โโโโ stdv3 (int) : (int): Standard Deviation 3
โโโโ stdv4 (int) : (int): Standard Deviation 4
โโโโ stdv5 (int) : (int): Standard Deviation 5
โโโโ stdv6 (int) : (int): Standard Deviation 6
โโโโ stdv7 (int) : (int): Standard Deviation 7
โโโโ trend_direction (string) : (string): Current direction of the trend
โโReturns: : Returns a map with the levels, plus direction flag and the data table
ZigZagโ Overview
This Pine Scriptโข library provides a comprehensive implementation of the ZigZag indicator using advanced object-oriented programming techniques. It serves as a developer resource rather than a standalone indicator, enabling Pine Scriptโข programmers to incorporate sophisticated ZigZag calculations into their own scripts.
Pine Scriptโข libraries contain reusable code that can be imported into indicators, strategies, and other libraries. For more information, consult the Libraries section of the Pine Scriptโข User Manual.
โ About the Original
This library is based on TradingView's official ZigZag implementation .
The original code provides a solid foundation with user-defined types and methods for calculating ZigZag pivot points.
โ What is ZigZag?
The ZigZag indicator filters out minor price movements to highlight significant market trends.
It works by:
1. Identifying significant pivot points (local highs and lows)
2. Connecting these points with straight lines
3. Ignoring smaller price movements that fall below a specified threshold
Traders typically use ZigZag for:
- Trend confirmation
- Identifying support and resistance levels
- Pattern recognition (such as Elliott Waves)
- Filtering out market noise
The algorithm identifies pivot points by analyzing price action over a specified number of bars, then only changes direction when price movement exceeds a user-defined percentage threshold.
โ My Enhancements
This modified version extends the original library with several key improvements:
1. Support and Resistance Visualization
- Adds horizontal lines at pivot points
- Customizable line length (offset from pivot)
- Adjustable line width and color
- Option to extend lines to the right edge of the chart
2. Support and Resistance Zones
- Creates semi-transparent zone areas around pivot points
- Customizable width for better visibility of important price levels
- Separate colors for support (lows) and resistance (highs)
- Visual representation of price areas rather than just single lines
3. Zig Zag Lines
- Separate colors for upward and downward ZigZag movements
- Visually distinguishes between bullish and bearish price swings
- Customizable colors for text
- Width customization
4. Enhanced Settings Structure
- Added new fields to the Settings type to support the additional features
- Extended Pivot type with supportResistance and supportResistanceZone fields
- Comprehensive configuration options for visual elements
These enhancements make the ZigZag more useful for technical analysis by clearly highlighting support/resistance levels and zones, and providing clearer visual cues about market direction.
โ Technical Implementation
This library leverages Pine Scriptโข's user-defined types (UDTs) to create a robust object-oriented architecture:
- Settings : Stores configuration parameters for calculation and display
- Pivot : Represents pivot points with their visual elements and properties
- ZigZag : Manages the overall state and behavior of the indicator
The implementation follows best practices from the Pine Scriptโข User Manual's Style Guide and uses advanced language features like methods and object references. These UDTs represent Pine Scriptโข's most advanced feature set, enabling sophisticated data structures and improved code organization.
For newcomers to Pine Scriptโข, it's recommended to understand the language fundamentals before working with the UDT implementation in this library.
โ Usage Example
//@version=6
indicator("ZigZag Example", overlay = true, shorttitle = 'ZZA', max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
import andre_007/ZigZag/1 as ZIG
var group_1 = "ZigZag Settings"
//@variable Draw Zig Zag on the chart.
bool showZigZag = input.bool(true, "Show Zig-Zag Lines", group = group_1, tooltip = "If checked, the Zig Zag will be drawn on the chart.", inline = "1")
// @variable The deviation percentage from the last local high or low required to form a new Zig Zag point.
float deviationInput = input.float(5.0, "Deviation (%)", minval = 0.00001, maxval = 100.0,
tooltip = "The minimum percentage deviation from a previous pivot point required to change the Zig Zag's direction.", group = group_1, inline = "2")
// @variable The number of bars required for pivot detection.
int depthInput = input.int(10, "Depth", minval = 1, tooltip = "The number of bars required for pivot point detection.", group = group_1, inline = "3")
// @variable registerPivot (series bool) Optional. If `true`, the function compares a detected pivot
// point's coordinates to the latest `Pivot` object's `end` chart point, then
// updates the latest `Pivot` instance or adds a new instance to the `ZigZag`
// object's `pivots` array. If `false`, it does not modify the `ZigZag` object's
// data. The default is `true`.
bool allowZigZagOnOneBarInput = input.bool(true, "Allow Zig Zag on One Bar", tooltip = "If checked, the Zig Zag calculation can register a pivot high and pivot low on the same bar.",
group = group_1, inline = "allowZigZagOnOneBar")
var group_2 = "Display Settings"
// @variable The color of the Zig Zag's lines (up).
color lineColorUpInput = input.color(color.green, "Line Colors for Up/Down", group = group_2, inline = "4")
// @variable The color of the Zig Zag's lines (down).
color lineColorDownInput = input.color(color.red, "", group = group_2, inline = "4",
tooltip = "The color of the Zig Zag's lines")
// @variable The width of the Zig Zag's lines.
int lineWidthInput = input.int(1, "Line Width", minval = 1, tooltip = "The width of the Zig Zag's lines.", group = group_2, inline = "w")
// @variable If `true`, the Zig Zag will also display a line connecting the last known pivot to the current `close`.
bool extendInput = input.bool(true, "Extend to Last Bar", tooltip = "If checked, the last pivot will be connected to the current close.",
group = group_1, inline = "5")
// @variable If `true`, the pivot labels will display their price values.
bool showPriceInput = input.bool(true, "Display Reversal Price",
tooltip = "If checked, the pivot labels will display their price values.", group = group_2, inline = "6")
// @variable If `true`, each pivot label will display the volume accumulated since the previous pivot.
bool showVolInput = input.bool(true, "Display Cumulative Volume",
tooltip = "If checked, the pivot labels will display the volume accumulated since the previous pivot.", group = group_2, inline = "7")
// @variable If `true`, each pivot label will display the change in price from the previous pivot.
bool showChgInput = input.bool(true, "Display Reversal Price Change",
tooltip = "If checked, the pivot labels will display the change in price from the previous pivot.", group = group_2, inline = "8")
// @variable Controls whether the labels show price changes as raw values or percentages when `showChgInput` is `true`.
string priceDiffInput = input.string("Absolute", "", options = ,
tooltip = "Controls whether the labels show price changes as raw values or percentages when 'Display Reversal Price Change' is checked.",
group = group_2, inline = "8")
// @variable If `true`, the Zig Zag will display support and resistance lines.
bool showSupportResistanceInput = input.bool(true, "Show Support/Resistance Lines",
tooltip = "If checked, the Zig Zag will display support and resistance lines.", group = group_2, inline = "9")
// @variable The number of bars to extend the support and resistance lines from the last pivot point.
int supportResistanceOffsetInput = input.int(50, "Support/Resistance Offset", minval = 0,
tooltip = "The number of bars to extend the support and resistance lines from the last pivot point.", group = group_2, inline = "10")
// @variable The width of the support and resistance lines.
int supportResistanceWidthInput = input.int(1, "Support/Resistance Width", minval = 1,
tooltip = "The width of the support and resistance lines.", group = group_2, inline = "11")
// @variable The color of the support lines.
color supportColorInput = input.color(color.red, "Support/Resistance Color", group = group_2, inline = "12")
// @variable The color of the resistance lines.
color resistanceColorInput = input.color(color.green, "", group = group_2, inline = "12",
tooltip = "The color of the support/resistance lines.")
// @variable If `true`, the support and resistance lines will be drawn as zones.
bool showSupportResistanceZoneInput = input.bool(true, "Show Support/Resistance Zones",
tooltip = "If checked, the support and resistance lines will be drawn as zones.", group = group_2, inline = "12-1")
// @variable The color of the support zones.
color supportZoneColorInput = input.color(color.new(color.red, 70), "Support Zone Color", group = group_2, inline = "12-2")
// @variable The color of the resistance zones.
color resistanceZoneColorInput = input.color(color.new(color.green, 70), "", group = group_2, inline = "12-2",
tooltip = "The color of the support/resistance zones.")
// @variable The width of the support and resistance zones.
int supportResistanceZoneWidthInput = input.int(10, "Support/Resistance Zone Width", minval = 1,
tooltip = "The width of the support and resistance zones.", group = group_2, inline = "12-3")
// @variable If `true`, the support and resistance lines will extend to the right of the chart.
bool supportResistanceExtendInput = input.bool(false, "Extend to Right",
tooltip = "If checked, the lines will extend to the right of the chart.", group = group_2, inline = "13")
// @variable References a `Settings` instance that defines the `ZigZag` object's calculation and display properties.
var ZIG.Settings settings =
ZIG.Settings.new(
devThreshold = deviationInput,
depth = depthInput,
lineColorUp = lineColorUpInput,
lineColorDown = lineColorDownInput,
textUpColor = lineColorUpInput,
textDownColor = lineColorDownInput,
lineWidth = lineWidthInput,
extendLast = extendInput,
displayReversalPrice = showPriceInput,
displayCumulativeVolume = showVolInput,
displayReversalPriceChange = showChgInput,
differencePriceMode = priceDiffInput,
draw = showZigZag,
allowZigZagOnOneBar = allowZigZagOnOneBarInput,
drawSupportResistance = showSupportResistanceInput,
supportResistanceOffset = supportResistanceOffsetInput,
supportResistanceWidth = supportResistanceWidthInput,
supportColor = supportColorInput,
resistanceColor = resistanceColorInput,
supportResistanceExtend = supportResistanceExtendInput,
supportResistanceZoneWidth = supportResistanceZoneWidthInput,
drawSupportResistanceZone = showSupportResistanceZoneInput,
supportZoneColor = supportZoneColorInput,
resistanceZoneColor = resistanceZoneColorInput
)
// @variable References a `ZigZag` object created using the `settings`.
var ZIG.ZigZag zigZag = ZIG.newInstance(settings)
// Update the `zigZag` on every bar.
zigZag.update()
//#endregion
The example code demonstrates how to create a ZigZag indicator with customizable settings. It:
1. Creates a Settings object with user-defined parameters
2. Instantiates a ZigZag object using these settings
3. Updates the ZigZag on each bar to detect new pivot points
4. Automatically draws lines and labels when pivots are detected
This approach provides maximum flexibility while maintaining readability and ease of use.
vidya_calculateLibrary "vidya_calculate"
:
Calculates the Variable Index Dynamic Average (VIDYA).
Computes the VIDYA, which adjusts the degree of smoothing based on the strength of price momentum (absolute value of CMO),
and then returns the 15-period(variable) Simple Moving Average (SMA) of that VIDYA.
VIDYA tends to follow prices more closely when price fluctuations are large, and is smoothed more when fluctuations are small.
CMO = Chande Momentum Oscillator.
vidya(src, vidyaLength, vidyaMomentum, vidyaTrendPeriod)
โโ: Calculates the Variable Index Dynamic Average (VIDYA)
โโParameters:
โโโโ src (float) : : Source
โโโโ vidyaLength (int) : : VIDYA Length
โโโโ vidyaMomentum (int) : : VIDYA Momentum
โโโโ vidyaTrendPeriod (int) : : VIDYA Trend Period (Display)
โโReturns: : the 15-period(variable) Simple Moving Average (SMA) of that VIDYA
ChartPatternSetupsLibrary "ChartPatternSetups"
detectSymmetricalTriangle(lookback)
โโDetects a Symmetrical Triangle (Bullish or Bearish) and provides trade levels.
โโParameters:
โโโโ lookback (int) : Number of bars to look back for pivots.
โโReturns: Tuple of (isBullish, isBearish, entry, sl, tp).
detectAscendingTriangle(lookback)
โโDetects an Ascending Triangle (Bullish) and provides trade levels.
โโParameters:
โโโโ lookback (int) : Number of bars to look back for pivots.
โโReturns: Tuple of (isDetected, entry, sl, tp).
detectDescendingTriangle(lookback)
โโDetects a Descending Triangle (Bearish) and provides trade levels.
โโParameters:
โโโโ lookback (int) : Number of bars to look back for pivots.
โโReturns: Tuple of (isDetected, entry, sl, tp).
detectFallingWedge(lookback)
โโDetects a Falling Wedge (Bullish) and provides trade levels.
โโParameters:
โโโโ lookback (int) : Number of bars to look back for pivots.
โโReturns: Tuple of (isDetected, entry, sl, tp).
detectRisingWedge(lookback)
โโDetects a Rising Wedge (Bearish) and provides trade levels.
โโParameters:
โโโโ lookback (int) : Number of bars to look back for pivots.
โโReturns: Tuple of (isDetected, entry, sl, tp).
SCoLibraryAmsterdamLibrary "SCoLibraryAmsterdam"
This library contains functions to check Amsterdam strategy price events
calcTrendMom(FilterTrendWithMa50, FilterTrendWithMa200)
This function define the current trend and momentum force according to 4wma, 12wma, 21ema and 200sma
Parameters:
FilterTrendWithMa50 (bool) : is set to true will filter trend result with 50sma
FilterTrendWithMa200 (bool) : is set to true will filter trend result with 200sma
Returns: Return a positive value if trend is up (2 : strong momentum, 1 : weak momentum) and a negative value if trend is negative (-2 : strong momentum, -1 : weak momentum)
calcPriceAmstNodeMa01(close, AtrPeriod, AtrMultiplier)
This function checks if close, 4wma and 12wma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceAmstNodeMa123(close, AtrPeriod, AtrMultiplier)
This function checks if close, 12wma, 21ema and 50sma are in contraction within a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the period used to calculate the average true range (ATR)
AtrMultiplier (float) : is the multiplier of the average true range
Returns: Return true or false
calcPriceInsidebar()
This function checks inside bar candle configuration
Returns: true or false
calcPrice12wmaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 12wma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice21emaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 21ema by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice50smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 50sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPrice200smaExtended(close, PeriodNormalization, ExtensionPercent)
This function checks if close is over extended from the 200sma by a multiple of the average true range
Parameters:
close (float)
PeriodNormalization (int)
ExtensionPercent (float)
Returns: Return true or false
calcPriceClimax(close, AtrPeriod, MovingAvgAtrMulti, VolAtrMulti)
This function checks if price is in climax evolution by comparing the extension between 4wma and 12wma, and a multiple of the average true range
Parameters:
close (float)
AtrPeriod (simple int) : is the average true range period
MovingAvgAtrMulti (float) : is the extension ratio
VolAtrMulti (float) : is the volume extension relative to the 21sma volume
Returns: Return true or false
LinearRegressionLibrary "LinearRegression"
Calculates a variety of linear regression and deviation types, with optional emphasis weighting. Additionally, multiple of slope and Pearsonโs R calculations.
calcSlope(_src, _len, _condition)
โโCalculates the slope of a linear regression over the specified length.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The length of the lookback period for the linear regression.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
โโReturns: (float) The slope of the linear regression.
calcReg(_src, _len, _condition)
โโCalculates a basic linear regression, returning y1, y2, slope, and average.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) An array of 4 values: .
calcRegStandard(_src, _len, _emphasis, _condition)
โโCalculates an Standard linear regression with optional emphasis.
โโParameters:
โโโโ _src (float) : (series float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRegRidge(_src, _len, lambda, _emphasis, _condition)
โโCalculates a ridge regression with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ lambda (float) : (float) The ridge regularization parameter.
โโโโ _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRegLasso(_src, _len, lambda, _emphasis, _condition)
โโCalculates a Lasso regression with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ lambda (float) : (float) The Lasso regularization parameter.
โโโโ _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcElasticNetLinReg(_src, _len, lambda1, lambda2, _emphasis, _condition)
โโCalculates an Elastic Net regression with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ lambda1 (float) : (float) L1 regularization parameter (Lasso).
โโโโ lambda2 (float) : (float) L2 regularization parameter (Ridge).
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRegHuber(_src, _len, delta, iterations, _emphasis, _condition)
โโCalculates a Huber regression using Iteratively Reweighted Least Squares (IRLS).
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ delta (float) : (float) Huber threshold parameter.
โโโโ iterations (int) : (int) Number of IRLS iterations.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRegLAD(_src, _len, iterations, _emphasis, _condition)
โโCalculates a Least Absolute Deviations (LAD) regression via IRLS.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ iterations (int) : (int) Number of IRLS iterations for LAD.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRegBayesian(_src, _len, priorMean, priorSpan, sigma, _emphasis, _condition)
โโCalculates a Bayesian linear regression with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data series.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ priorMean (float) : (float) The prior mean for the slope.
โโโโ priorSpan (float) : (float) The prior variance (or span) for the slope.
โโโโ sigma (float) : (float) The assumed standard deviation of residuals.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: (float ) .
calcRFromLinReg(_src, _len, _slope, _average, _y1, _condition)
โโCalculates the Pearson correlation coefficient (R) based on linear regression parameters.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _average (float) : (float) The average value of the source data series.
โโโโ _y1 (float) : (float) The starting point (y-intercept of the oldest bar) for the linear regression.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
โโReturns: (float) The Pearson correlation coefficient (R) adjusted for the direction of the slope.
calcRFromSource(_src, _len, _condition)
โโCalculates the correlation coefficient (R) using a specified length and source data.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency.
โโReturns: (float) The correlation coefficient (R).
calcSlopeLengthZero(_src, _len, _minLen, _step, _condition)
โโIdentifies the length at which the slope is flattest (closest to zero).
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length to consider (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from (cannot exceed the max length).
โโโโ _step (int) : (int) The increment step for lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length at which the slope is flattest.
calcSlopeLengthHighest(_src, _len, _minLen, _step, _condition)
โโIdentifies the length at which the slope is highest.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length at which the slope is highest.
calcSlopeLengthLowest(_src, _len, _minLen, _step, _condition)
โโIdentifies the length at which the slope is lowest.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length at which the slope is lowest.
calcSlopeLengthAbsolute(_src, _len, _minLen, _step, _condition)
โโIdentifies the length at which the absolute slope value is highest.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length at which the absolute slope value is highest.
calcRLengthZero(_src, _len, _minLen, _step, _condition)
โโIdentifies the length with the lowest absolute R value.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length with the lowest absolute R value.
calcRLengthHighest(_src, _len, _minLen, _step, _condition)
โโIdentifies the length with the highest R value.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length with the highest R value.
calcRLengthLowest(_src, _len, _minLen, _step, _condition)
โโIdentifies the length with the lowest R value.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length with the lowest R value.
calcRLengthAbsolute(_src, _len, _minLen, _step, _condition)
โโIdentifies the length with the highest absolute R value.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The maximum lookback length (minimum of 2).
โโโโ _minLen (int) : (int) The minimum length to start from.
โโโโ _step (int) : (int) The step for incrementing lengths.
โโโโ _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast.
โโReturns: (int) The length with the highest absolute R value.
calcDevReverse(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates the regressive linear deviation in reverse order, with optional emphasis on recent data.
โโParameters:
โโโโ _src (float) : (float) The source data.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
โโโโ _inputDev (float) : (float) The input deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevForward(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates the progressive linear deviation in forward order (oldest to most recent bar), with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data array, where _src is oldest and _src is most recent.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The y-intercept of the linear regression (value at the most recent bar, adjusted by slope).
โโโโ _inputDev (float) : (float) The input deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevBalanced(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates the balanced linear deviation with optional emphasis on recent or older data.
โโParameters:
โโโโ _src (float) : (float) Source data array, where _src is the most recent and _src is the oldest.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The y-intercept of the linear regression (value at the oldest bar).
โโโโ _inputDev (float) : (float) The input deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevMean(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates the mean absolute deviation from a forward-applied linear trend (oldest to most recent), with optional emphasis.
โโParameters:
โโโโ _src (float) : (float) The source data array, where _src is the most recent and _src is the oldest.
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
โโโโ _inputDev (float) : (float) The input deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevMedian(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates the median absolute deviation with optional emphasis on recent data.
โโParameters:
โโโโ _src (float) : (float) The source data array (index 0 = oldest, index _len - 1 = most recent).
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression.
โโโโ _inputDev (float) : (float) The deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns:
calcDevPercent(_y1, _inputDev, _condition)
โโCalculates the percent deviation from a given value and a specified percentage.
โโParameters:
โโโโ _y1 (float) : (float) The base value from which to calculate deviation.
โโโโ _inputDev (float) : (float) The deviation percentage.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevFitted(_len, _slope, _y1, _emphasis, _condition)
โโCalculates the weighted fitted deviation based on high and low series data, showing max deviation, with optional emphasis.
โโParameters:
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcDevATR(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition)
โโCalculates an ATR-style deviation with optional emphasis on recent data.
โโParameters:
โโโโ _src (float) : (float) The source data (typically close).
โโโโ _len (int) : (int) The length of the lookback period.
โโโโ _slope (float) : (float) The slope of the linear regression.
โโโโ _y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression.
โโโโ _inputDev (float) : (float) The input deviation multiplier.
โโโโ _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars.
โโโโ _condition (bool) : (bool) Flag to enable calculation (true = calculate).
โโReturns: A 2-element tuple: .
calcPricePositionPercent(_top, _bot, _src)
โโCalculates the percent position of a price within a linear regression channel. Top=100%, Bottom=0%.
โโParameters:
โโโโ _top (float) : (float) The top (positive) deviation, corresponding to 100%.
โโโโ _bot (float) : (float) The bottom (negative) deviation, corresponding to 0%.
โโโโ _src (float) : (float) The source price.
โโReturns: (float) The percent position within the channel.
plotLinReg(_len, _y1, _y2, _slope, _devTop, _devBot, _scaleTypeLog, _lineWidth, _extendLines, _channelStyle, _colorFill, _colUpLine, _colDnLine, _colUpFill, _colDnFill)
โโPlots the linear regression line and its deviations, with configurable styles and fill.
โโParameters:
โโโโ _len (int) : (int) The lookback period for the linear regression.
โโโโ _y1 (float) : (float) The starting y-value of the regression line.
โโโโ _y2 (float) : (float) The ending y-value of the regression line.
โโโโ _slope (float) : (float) The slope of the regression line (used to determine line color).
โโโโ _devTop (float) : (float) The top deviation to add to the line.
โโโโ _devBot (float) : (float) The bottom deviation to subtract from the line.
โโโโ _scaleTypeLog (bool) : (bool) Use a log scale if true; otherwise, linear scale.
โโโโ _lineWidth (int) : (int) The width of the plotted lines.
โโโโ _extendLines (string) : (string) How lines should extend (none, left, right, both).
โโโโ _channelStyle (string) : (string) The style of the channel lines (solid, dashed, dotted).
โโโโ _colorFill (bool) : (bool) Whether to fill the space between the top and bottom deviation lines.
โโโโ _colUpLine (color) : (color) Line color when slope is positive.
โโโโ _colDnLine (color) : (color) Line color when slope is negative.
โโโโ _colUpFill (color) : (color) Fill color when slope is positive.
โโโโ _colDnFill (color) : (color) Fill color when slope is negative.
JsonAlertJsonAlert Library โ Convert TradingView Alerts to JSON for Server Processing! ๐ก
๐ The JsonAlert library makes it easy to send TradingView alerts as structured JSON to your server, allowing seamless integration with automated trading systems, databases, or webhook-based services.
๐ Features:
โ
Converts TradingView alert data into JSON format
โ
Supports custom key-value pairs for flexibility
โ
Allows frequency control (once per bar, once per bar close, every update)
โ
Easy to integrate with server-side PHP or other languages
Note that you have to pass one string array for keys and one string array for values , also you should pass alert frequency .
๐ Example Usage in Pine Script:
//@version=6
indicator("My script" , overlay = true)
import Penhan/JsonAlert/1 as alrt
if high > low
var array keys = array.from("ticker", "timeframe", "pattern")
var array values = array.from( syminfo.ticker , timeframe.period , str.tostring(123.45) )
alrt.alarm (keys, values , alert.freq_once_per_bar)
๐ก Json Output Example:
{"ticker": "BTCUSDT","timeframe": "1","pattern": "123.45"}
๐ฅ๏ธ Server-Side PHP Example:
There you can integrate JsonAlert with your server in seconds! :)
DateTimeLibrary with enums that can be used as script inputs to allow users to set their preferred date and/or time formats. The user-selected formats can be passed to the library functions (which use ๐๐๐.๐๐๐๐๐๐_๐๐๐๐() under the hood) to get formatted date and time strings from a UNIX time.
PREFACE
The target audience of this publication is users creating their own indicators/strategies.
Sometimes a date and/or time needs to be displayed to the user. As a Pine Coder, it is natural to focus our initial attention on the primary calculations or functions of a script, which can lead to the display format of dates and times being an afterthought. While it may not be crucial for the main use case of a script, increased customizability can help push indicators/strategies to the next level in the eyes of the user.
The purpose of this library is to provide an easy-to-use mechanism for allowing script users to choose the formats of dates and times that are displayed to them. Not only is this helpful for users from around the world who may be accustomed to different date/time formats, but it also makes it easier for the script author because it offloads the date/time formatting decision from the author to the user.
HOW TO USE
Step 1
Import the library. Replace with the latest available version number for this library.
//@version=6
indicator("Example")
import n00btraders/DateTime/ as dt
Step 2
Select a date format and/or time format enum to be used as an input.
dateFormatInput = input.enum(dt.DateFormat.FORMAT_3, "Date format")
timeFormatInput = input.enum(dt.TimeFormat.TWENTY_FOUR_HOURS, "Time hours format")
Step 3
Pass the user's selection as the `format` parameter in the formatting functions from this library. The `timestamp` & `timezone` parameters can be any value that would otherwise be used in ๐๐๐.๐๐๐๐๐๐_๐๐๐๐(๐๐๐๐, ๐๐๐๐๐๐, ๐๐๐๐๐ฃ๐๐๐).
string formattedDate = dt.formatDate(timestamp, dateFormatInput, timezone)
string formattedTime = dt.formatTime(timestamp, timeFormatInput, timezone)
LIMITATIONS
The library's ease-of-use comes at a few costs:
Fixed date/time formats.
Using the library's pre-defined date & time formats means that additional custom formats cannot be utilized. For example, this library does not include seconds or fractional seconds in formatted time strings. If a script's use case requires displaying the 'seconds' from a time of day, then ๐๐๐.๐๐๐๐๐๐_๐๐๐๐() must be used directly.
Fixed time zone offset format.
The `formatTime()` function of this library can optionally add the time zone offset at the end of the time string, but the format of the offset cannot be specified. Note: if the default format for time zone offset is not sufficient, the Timezone library can be imported directly to get the time zone offset string in a preferred format.
ADVANTAGES
There are benefits to utilizing this library instead of directly using ๐๐๐.๐๐๐๐๐๐_๐๐๐๐():
Easy to use from the user's perspective.
The date & time format enums provide a similar look and feel to the "Date format" and "Time hours format" options that already exist in the TradingView chart settings.
Easy to use from the author's perspective.
The exported functions from this library are modeled to behave similarly to the ๐๐๐.๐๐๐๐๐๐_๐๐๐๐(๐๐๐๐, ๐๐๐๐๐๐, ๐๐๐๐๐ฃ๐๐๐) built-in function from Pine Script.
Format quarter of the year.
The date formatting function from this library can display a fiscal quarter if it's included in the user-selected format. This is currently not possible with the built-in ๐๐๐.๐๐๐๐๐๐_๐๐๐๐().
EXPORTED ENUM TYPES
This section will list the available date/time formats that can be used as a script input. Each enum type has a detailed //@๐๐๐๐๐๐๐๐ description in the source code to help determine the best choice for your scripts.
Date Format Enums:
๐ณ๐๐๐๐ต๐๐๐๐๐
๐ณ๐๐๐๐ต๐๐๐๐๐๐ณ๐๐ข๐พ๐๐๐๐๐๐ฐ๐๐๐
๐ณ๐๐๐๐ต๐๐๐๐๐๐ณ๐๐ข๐พ๐๐๐๐๐๐ต๐๐๐
๐ฒ๐๐๐๐๐๐ณ๐๐๐๐ต๐๐๐๐๐
Supporting Date Enums:
๐ณ๐๐๐๐ฟ๐๐๐๐๐ก
Time Format Enums:
๐๐๐๐๐ต๐๐๐๐๐
Supporting Time Enums:
๐๐๐๐๐ฐ๐๐๐๐๐๐๐๐๐๐๐
๐๐๐๐๐๐๐๐๐๐๐๐๐
๐๐๐๐๐ฟ๐๐๐๐๐๐ก
Note: all exported enums have custom titles for each field. This means that the supporting enums could also be exposed to the end-user as script inputs if necessary. The supporting enums are used as optional parameters in this library's formatting functions to allow further customizability.
EXPORTED FUNCTIONS
formatDate(timestamp, format, timezone, prefix, trim)
โโConverts a UNIX time into a date string formatted according to the selected `format`.
โโParameters:
โโโโ timestamp (series int) : A UNIX time.
โโโโ format (series DateFormat) : A date format.
โโโโ timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
โโโโ prefix (series DatePrefix) : Optional day of week prefix.
โโโโ trim (series bool) : Optional truncation of numeric month / day.
โโReturns: Calendar date string using the selected format.
โธปโธปโธปโธปโธปโธปโธปโธป
Required parameters: `timestamp`, `format`.
Note: there is a version of this function for each Date Format enum type. The only difference is the type of the `format` parameter.
Tip: hover over the `formatDate()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
formatTime(timestamp, format, timezone, trim, separator, postfix, space, offset)
โโConverts a UNIX time into a formatted time string using the 24-hour clock or 12-hour clock.
โโParameters:
โโโโ timestamp (series int) : A UNIX time.
โโโโ format (series TimeFormat) : A time format.
โโโโ timezone (series string) : A UTC/GMT offset or IANA time zone identifier.
โโโโ trim (series TimeAbbreviation) : Optional truncation of the hour and minute portion.
โโโโ separator (series TimeSeparator) : Optional time separator.
โโโโ postfix (series TimePostfix) : Optional format for the AM/PM postfix.
โโโโ space (series bool) : Optional space between the time and the postfix.
โโโโ offset (series bool) : Optional UTC offset as a suffix.
โโReturns: Time of day string using the selected format.
โธปโธปโธปโธปโธปโธปโธปโธป
Required parameters: `timestamp`, `format`.
Note: the `trim`, `postfix`, and `space` optional parameters are not applicable and will be ignored when using the 24-hour clock (`format` = TimeFormat.TWENTY_FOUR_HOURS).
Tip: hover over the `formatTime()` function in the Pine Editor to display useful details:
Function description
Parameter descriptions + default values
Example function usage
Example outputs for combinations of TimeFormat.* enum values & optional parameters
NOTES
This library can be used in conjunction with the Timezone library to increase the usability of scripts that can benefit from allowing the user to input their preferred time zone.
Credits to HoanGhetti for publishing an informative Markdown resource which I referenced to create the formatted function descriptions that pop up when hovering over `formatDate()` and `formatTime()` function calls in the Pine Editor.
dataTableUtilitiesLibrary "dataTableUtilities"
generate_dataTable(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, include_comments)
โโ: Generates and shows a data table.
โโParameters:
โโโโ dataTable_map (map)
โโโโ title (string) : (string): Title of the table
โโโโ tableYpos (string) : (string): Vertical position of the table
โโโโ tableXpos (string) : (string): Horizontal position of the table
โโโโ textSize (string) : (string): Text size
โโโโ includes_multiple_maps (bool)
โโโโ include_comments (bool)
โโReturns: : None
generate_dataTable_multiple_columns(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, total_columns)
โโ: Generates and shows a data table.
โโParameters:
โโโโ dataTable_map (map)
โโโโ title (string) : (string): Title of the table
โโโโ tableYpos (string) : (string): Vertical position of the table
โโโโ tableXpos (string) : (string): Horizontal position of the table
โโโโ textSize (string) : (string): Text size
โโโโ includes_multiple_maps (bool)
โโโโ total_columns (int)
โโReturns: : None
ootaLibrary "oota"
Collection of all custom and enhanced TA indicators - Object oriented methods implementation
method tr(c, useTrueRange)
โโreturns true range of the candle
โโNamespace types: Candle
โโParameters:
โโโโ c (Candle) : Candle object containing ohlc data
โโโโ useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
method ma(maType, length, source)
โโreturns custom moving averages
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ source (float) : Moving Average Source
โโReturns: moving average for the given type and length
method atr(maType, length, useTrueRange, c)
โโreturns ATR with custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: ATR for the given moving average type and length
method atrpercent(maType, length, useTrueRange, c)
โโreturns ATR as percentage of close price
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ useTrueRange (bool) : Use true range for atr calculation instead of just high/low difference
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: ATR as percentage of close price for the given moving average type and length
method bb(maType, length, multiplier, sticky, c)
โโreturns Bollinger band for custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Bollinger band with custom moving average for given source, length and multiplier
method bbw(maType, length, multiplier, sticky, c)
โโreturns Bollinger bandwidth for custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ sticky (simple bool) : sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Bollinger Bandwidth for custom moving average for given source, length and multiplier
method bpercentb(maType, length, multiplier, sticky, c)
โโreturns Bollinger Percent B for custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Bollinger Percent B for custom moving average for given source, length and multiplier
method kc(maType, length, multiplier, useTrueRange, sticky, c)
โโreturns Keltner Channel for custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ useTrueRange (simple bool) : - if set to false, uses high-low.
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Keltner Channel for custom moving average for given souce, length and multiplier
method kcw(maType, length, multiplier, useTrueRange, sticky, c)
โโreturns Keltner Channel Width with custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ useTrueRange (simple bool) : - if set to false, uses high-low.
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Keltner Channel Width for custom moving average
method kpercentk(maType, length, multiplier, useTrueRange, sticky, c)
โโreturns Keltner Channel Percent K Width with custom moving average
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom series type
โโโโ length (simple int) : Moving Average Length
โโโโ multiplier (float) : Standard Deviation multiplier
โโโโ useTrueRange (simple bool) : - if set to false, uses high-low.
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Keltner Percent K for given moving average, source, length and multiplier
method dc(c, length, sticky)
โโreturns Custom Donchian Channel
โโNamespace types: Candle
โโParameters:
โโโโ c (Candle) : Candle object containing ohlc
โโโโ length (simple int) : - donchian channel length
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโReturns: Donchian channel
method dcw(c, length, sticky)
โโreturns Donchian Channel Width
โโNamespace types: Candle
โโParameters:
โโโโ c (Candle) : Candle object containing ohlc
โโโโ length (simple int) : - donchian channel length
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโReturns: Donchian channel width
method dpercentd(c, length, sticky)
โโreturns Donchian Channel Percent of price
โโNamespace types: Candle
โโParameters:
โโโโ c (Candle) : Candle object containing ohlc
โโโโ length (simple int) : - donchian channel length
โโโโ sticky (simple bool) : - sticky boundaries which will only change when value is outside boundary.
โโReturns: Donchian channel Percent D
method supertrend(maType, length, multiplier, useTrueRange, waitForClose, delayed, c)
โโsupertrend Simple supertrend based on atr but also takes into consideration of custom MA Type, sources
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ maType (simple CustomSeries) : Custom Series
โโโโ length (simple int) : ATR Length
โโโโ multiplier (simple float) : ATR Multiplier
โโโโ useTrueRange (simple bool) : - if set to false, uses high-low.
โโโโ waitForClose (simple bool) : : Considers source for direction change crossover if checked. Else, uses highSource and lowSource.
โโโโ delayed (simple bool) : : if set to true lags supertrend atr stop based on target levels.
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: dir : Supertrend direction
supertrend : BuyStop if direction is 1 else SellStop
method oscillatorRange(seriesType, source, highlowLength, rangeLength, sticky)
โโoscillatorRange - returns Custom overbought/oversold areas for an oscillator input
โโNamespace types: simple CustomSeries
โโParameters:
โโโโ seriesType (simple CustomSeries) : - Custom series type
โโโโ source (float) : - Osillator source such as RSI, COG etc.
โโโโ highlowLength (simple int) : - length on which highlow of the oscillator is calculated
โโโโ rangeLength (simple int) : - length used for calculating oversold/overbought range - usually same as oscillator length
โโโโ sticky (simple bool) : - overbought, oversold levels won't change unless crossed
โโReturns: Dynamic overbought and oversold range for oscillator input
method oscillator(oscillatorType, length, shortLength, longLength, c)
โโoscillator - returns Choice of oscillator with custom overbought/oversold range
โโNamespace types: simple OscillatorType
โโParameters:
โโโโ oscillatorType (simple OscillatorType) : OscillatorType object
โโโโ length (simple int) : - Oscillator length - not used for TSI
โโโโ shortLength (simple int) : - shortLength only used for TSI
โโโโ longLength (simple int) : - longLength only used for TSI
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Oscillator value
method oscillatorWithRange(oscillatorType, length, shortLength, longLength, seriesType, highlowLength, sticky, c)
โโoscillatorWithRange - returns Choice of oscillator with custom overbought/oversold range
โโNamespace types: simple OscillatorType
โโParameters:
โโโโ oscillatorType (simple OscillatorType) : OscillatorType object
โโโโ length (simple int) : - Oscillator length - not used for TSI
โโโโ shortLength (simple int) : - shortLength only used for TSI
โโโโ longLength (simple int) : - longLength only used for TSI
โโโโ seriesType (simple CustomSeries) : - CustomSeries enum type
โโโโ highlowLength (simple int) : - length on which highlow of the oscillator is calculated
โโโโ sticky (simple bool) : - overbought, oversold levels won't change unless crossed
โโโโ c (Candle) : Candle object containing ohlc
โโReturns: Oscillator value along with dynamic overbought and oversold range for oscillator input
Candle
โโCustom candle object
โโFields:
โโโโ o (series float) : open
โโโโ h (series float) : high
โโโโ l (series float) : low
โโโโ c (series float) : close
โโโโ barindex (series int) : bar_index
โโโโ bartime (series int) : time
โโโโ bartimeclose (series int) : time_close
โโโโ v (series float) : volume
regressionUtilitiesLibrary "regressionUtilities"
get_linear_regression(bar_index_array, prices_array, stdDev_mult)
โโ: Generates the linear regression channel for an array of values.
โโParameters:
โโโโ bar_index_array (array) : (array): Array with bar indexes
โโโโ prices_array (array) : (array): Array with prices
โโโโ stdDev_mult (float) : (float): Standard deviation multiple for the channels
โโReturns: : Returns x1, x2, y1_mid, y2_mid, y1_up, y2_up, y1_dn, y2_dn, m, b, R2, stdDev
get_optimal_linearRegression_channel(max_length, min_length, source, stdDev_mult, show_data_table, tableYpos, tableXpos, table_textSize, barsToRight, plot_labels, include_levels)
โโ: Gets the best fitting linear regression using optimum length
โโParameters:
โโโโ max_length (int) : (int): Maximum bar length
โโโโ min_length (int) : (int): Minimum bar length
โโโโ source (float) : (float): Source for the regression
โโโโ stdDev_mult (float) : (float): Array with prices
โโโโ show_data_table (bool) : (bool): Activates and shows the data table
โโโโ tableYpos (string)
โโโโ tableXpos (string)
โโโโ table_textSize (string)
โโโโ barsToRight (int)
โโโโ plot_labels (bool)
โโโโ include_levels (bool)
โโReturns: : Returns three line objects that conform the regression channel, plus the optimal length and maximum r2
get_regressionChannel_data(max_length, min_length, source, stdDev_mult, plot_linearRegression, plot_labels, include_levels, barsToRight)
โโ: Gets data for the linear regression channel
โโParameters:
โโโโ max_length (int) : (int): Maximum length for the linear regression.
โโโโ min_length (int) : (int): Minimum length for the linear regression.
โโโโ source (float) : (float): Source for the linear regression
โโโโ stdDev_mult (float) : (float): Multiple for the standar deviations for the linear regression channel.
โโโโ plot_linearRegression (bool)
โโโโ plot_labels (bool)
โโโโ include_levels (bool)
โโโโ barsToRight (int)
โโReturns: : Returns a maps with the regression levels, the direction flag and the datatable map.
get_regressionChannel_data_v2(max_length, min_length, source, stdDev_mult, plot_linearRegression, plot_labels, include_levels, barsToRight)
โโParameters:
โโโโ max_length (int)
โโโโ min_length (int)
โโโโ source (float)
โโโโ stdDev_mult (float)
โโโโ plot_linearRegression (bool)
โโโโ plot_labels (bool)
โโโโ include_levels (bool)
โโโโ barsToRight (int)
get_cuadratic_regression(x_array, y_array, bars_to_project, max_length)
โโ: Gets the best fitting linear regression using optimum length
โโParameters:
โโโโ x_array (array) : (array): Maximum bar length
โโโโ y_array (array) : (array): Minimum bar length
โโโโ bars_to_project (int) : (int): Array with prices
โโโโ max_length (int)
โโReturns: : Returns three line objects