name
stringlengths
1
64
url
stringlengths
44
135
author
stringlengths
3
30
author_url
stringlengths
34
61
likes_count
int64
0
33.2k
kind
stringclasses
3 values
pine_version
int64
1
5
license
stringclasses
3 values
source
stringlengths
177
279k
MathTransformsHartley
https://www.tradingview.com/script/mvkfPAqn-MathTransformsHartley/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
9
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description implementation of the Fast Discrete Hartley Transform(DHT). library(title='MathTransformsHartley') // reference: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/IntegralTransforms/ import RicardoSantos/MathConstants/1 as constants import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(21) // @function Generic naive transform for the (DHT). // @param samples float array, 1d data. // @returns float array. export naive(float[] samples) => //{ int _size = array.size(samples) if _size < 1 runtime.error('MathTransformHartley -> naive(): "samples" size does not match.') array.new_float() else float _w0 = constants.Pi2() / _size float[] _spectrum = array.new_float(_size) float _sqrt2 = constants.Sqrt2() float _pi_over4 = constants.PiOver4() for _i = 0 to _size-1 // float _wk = _w0 * _i float _sum = 0.0 for _n = 0 to _size - 1 float _w = _n * _wk _sum += array.get(samples, _n) * _sqrt2 * math.cos(_w - _pi_over4) array.set(_spectrum, _i, _sum) _spectrum //{ usage: A = array.from(0.25,0.3,0.7,1,5,3,5,9,5) B = naive(A) console.queue_one(__C, str.format('ori: {0}', str.tostring(A, '#.##'))) console.queue_one(__C, str.format('nai: {0}', str.tostring(B, '#.##'))) //{ remarks: //}}} // @function Fast Discrete Hartley Transform (DHT). // @param samples float array, data samples. // @returns float array. export fdht (float[] samples) => //{ int _size = array.size(samples) if _size < 1 runtime.error('MathTransformHartley -> fdht(): "samples" size does not match.') array.new_float() else float[] _frequencyspace = naive(samples) float _scaling_factor = math.sqrt(1.0 / _size) for _i = 0 to _size-1 float _yi = array.get(_frequencyspace, _i) array.set(_frequencyspace, _i, _yi * _scaling_factor) _frequencyspace //{ usage: C = fdht(A) console.queue_one(__C, str.format('fst: {0}', str.tostring(C, '#.##'))) //{ remarks: //}}} // @function Inverse Discrete Hartley Transform (DHT). // @param samples float array, data samples. // @param asymmetric_scaling bool, default=true, scaling option. // @returns float array. export idht (float[] frequencies, bool asymmetric_scaling=true) => //{ int _size = array.size(frequencies) if _size < 1 runtime.error('MathTransformHartley -> idht(): "frequencies" size does not match.') array.new_float() else float[] _timespace = naive(frequencies) float _scaling_factor = 1.0 / _size if asymmetric_scaling _scaling_factor := math.sqrt(nz(_scaling_factor)) for _i = 0 to _size-1 float _yi = array.get(_timespace, _i) array.set(_timespace, _i, _yi * _scaling_factor) _timespace //{ usage: D = idht(C, true) console.queue_one(__C, str.format('inv: {0}', str.tostring(D, '#.##'))) //{ remarks: //}}} //######################### console.update(__T, __C)//#
Library_All_In_One
https://www.tradingview.com/script/z9T9ctfe-Library-All-In-One/
Wilson-IV
https://www.tradingview.com/u/Wilson-IV/
10
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Wilson-IV //@version=5 // @description: Contains several functions of Pinescript all in one Library. This reduce your coding. It will expands during time. library(title = "Library_All_In_One", overlay = true) //=============================================================================== //=== Functions - Indicators === //=============================================================================== // @function : fnRSI -> Calculates the Relative Strength Index (RSI) // @param : source -> close, open, high, etc... // @param : length -> RSI length // @returns : float -> RSI export fnRSI(series float source, simple int length) => float up = ta.rma(math.max(ta.change(source), 0), length) float down = ta.rma(-math.min(ta.change(source), 0), length) float RSI = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) RSI // @function : fnTSI -> Calculates the True Strength Index (TSI) // @param : source -> close, open, high, etc... // @param : length -> TSI length // @returns : float -> TSI export fnTSI(series float source, simple int length_Fast, simple int length_Slow) => Momentum = source - source[1] TSI = 100 * (ta.ema(ta.ema(Momentum, length_Fast), length_Slow)/ta.ema(ta.ema(math.abs(Momentum), length_Fast), length_Slow)) TSI //=============================================================================== //=== Functions - General === //=============================================================================== // @function : IsMidnight -> Determines if it is midnight 0 O'clock // @param : timezone -> Timezone // @returns : bool -> True or False export IsMidnight(simple string timezone) => hour(time, timezone) == 0 and minute(time, timezone) == 0 ? true : false // @function : Bullets -> Position of the bullets: above or below the chart // @param : source -> Only low or high. Low if the position is below chart, high if the bullet is above the chart // @returns : float -> position above or below the chart export Bullets(series float source, simple float factor) => float atr = ta.atr(30) float Position = source == high ? source + (atr * factor) : source - (atr * factor)
ArrayGenerate
https://www.tradingview.com/script/9ATmt813-ArrayGenerate/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
20
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Functions to generate arrays. library(title='ArrayGenerate') // reference: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Generate.cs // imports: import RicardoSantos/MathConstants/1 as mc // mc.Pi2() // @function returns a sequence of int numbers. // @param start int, begining of sequence range. // @param end int, end of sequence range. // @param step int, step, default=1 . // @returns int[], array. export sequence_int(int start, int end, int step=1)=>//{ // usage: array_sequence_int(4, 10, 2) = [4, 6, 8, 10] int[] _output = array.new_int(size=0) for _i = start to end by step array.push(id=_output, value=_i) _output //} // @function returns a sequence of float numbers. // @param start float, begining of sequence range. // @param end float, end of sequence range. // @param step float, step, default=1.0 . // @returns float[], array. export sequence_float(float start, float end, float step=1.0)=>//{ // usage: array_sequence_float(0.4, 1.0, 0.2) = [0.4, 0.6, 0.8, 1.0] float[] _output = array.new_float(size=0) for _i = start to end by step array.push(id=_output, value=_i) _output //} // @function Creates a array from a series sample range. // @param src series, any kind. // @param length int, window period in bars to sample series. // @param shift int, window period in bars to shift backwards the data sample, default=0. // @param direction_forward bool, sample from start to end or end to start order, default=true. // @returns float array export sequence_from_series (float src, int length, int shift=0, bool direction_forward=true) => //{ _start = direction_forward ? length + shift : 0 + shift _end = direction_forward ? 0 + shift : length + shift _data = array.from(src) //defines type if length < 1 array.clear(_data) else if length > 1 array.clear(_data) if bar_index > (length + shift) for _i = _start to _end array.push(_data, src[_i]) _data // usage: // src = input(close) // window = input(3) // shift = input(0) // forward = sequence_from_series(src, window, shift, true) // backward = sequence_from_series(src, window, shift, false) // if barstate.islast // label.new(bar_index, 0.0, str.format('{0}\n{1}', forward, backward)) //} // @function Generate normal distribution random sample. // @param size int, size of array // @param mean float, mean of the sample, (default=0.0). // @param dev float, deviation of the sample from the mean, (default=1.0). // @returns float array. export normal_distribution (int size, float mean=0.0, float dev=1.0) => //{ if size < 1 runtime.error('ArrayGenerate -> normal_distribution() -> Parameter "size": must be a positive value > 0.') float[] _A = na else if dev <= 0.0 runtime.error('ArrayGenerate -> normal_distribution() -> Parameter "dev": must be a positive value > 0.0.') float[] _A = na else float[] _A = array.new_float(size) for _i = 0 to size-1 float _rng = math.random(-dev, +dev) array.set(_A, _i, mean + _rng) _A //{ usage: // int size = input.int(100), float mean = input.float(25.0), float dev = input.float(10.0) // var float[] A = normal_distribution(size, mean, dev) // plot(array.get(A, bar_index % array.size(A))) //{ remarks: //}}} // @function Generate a base 10 logarithmically spaced sample sequence. // @param length int, length of the sequence. // @param start_exp float, start exponent. // @param stop_exp float, stop exponent. // @returns float array. export log_spaced (int length, float start_exp, float stop_exp) => //{ if length < 1 runtime.error('ArrayGenerate -> log_spaced() -> Parameter "length": must be a positive value > 0.') float[] _A = na else if length == 1 array.new_float(1, math.pow(10.0, stop_exp)) else float _step = (stop_exp - start_exp) / (length - 1) var _A = array.new_float(length) for _i = 0 to length-2 array.set(_A, _i, math.pow(10.0, start_exp + _i * _step)) array.set(_A, length-1, math.pow(10.0, stop_exp)) _A //{ usage: // int length = input.int(100) // float start_exp = input.float(0.1) // float stop_exp = input.float(1.0) // var float[] A = log_spaced(length, start_exp, stop_exp) // plot(array.get(A, bar_index % length)) //{ remarks: // Equivalent to MATLAB logspace but with the length as first instead of last argument. //}}} // @function Generate a linearly spaced sample vector within the inclusive interval (start, stop) and step 1. // @param stop float, stop value. // @param start float, start value, (default=0.0). // @returns float array. export linear_range(float stop, float start=0.0) => //{ if start == stop array.new_float(1, start) else if start < stop float[] _A = array.new_float(int(stop - start + 1)) for _i = 0 to array.size(_A)-1 array.set(_A, _i, start + _i) _A else float[] _A = array.new_float(int(start - stop + 1)) for _i = 0 to array.size(_A)-1 array.set(_A, _i, start - _i) _A //{ usage: // var float[] A = linear_range(100) // var float[] B = linear_range(0, 100) // plot(array.get(A, bar_index % array.size(A))) // plot(array.get(B, bar_index % array.size(A))) //{ remarks: /// Equivalent to MATLAB colon operator (:). //}}} // @function Create a periodic wave. // @param length int, the number of samples to generate. // @param sampling_rate float, samples per time unit (Hz). Must be larger than twice the frequency to satisfy the Nyquist criterion. // @param frequency float, frequency in periods per time unit (Hz). // @param amplitude float, the length of the period when sampled at one sample per time unit. This is the interval of the periodic domain, a typical value is 1.0, or 2*Pi for angular functions. // @param phase float, optional phase offset. // @param delay int, optional delay, relative to the phase. // @returns float array. export periodic_wave (int length, float sampling_rate, float frequency, float amplitude = 1.0, float phase = 0.0, int delay = 0) => //{ if length < 1 runtime.error('ArrayGenerate -> periodic_wave() -> Parameter "length": must be a positive value > 0.') float[] _A = na else float _step = (frequency / sampling_rate * amplitude) float _phase = (((phase - delay * _step) % amplitude) + amplitude) % amplitude // _phase: https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Euclid.cs#L59 float[] _A = array.new_float(length) int _k = 0 for _i = 0 to length-1 float _x = _phase + _k * _step if _x >= amplitude _x %= amplitude _phase := _x _k := 0 array.set(_A, _i, _x) _k += 1 _A //{ usage: // int length = input.int(100), float sampling_rate = input.float(0.55), float frequency = input.float(0.65), float amplitude = input.float(1.0), float phase = input.float(0.0), int delay = input.int(0) // var float[] A = periodic_wave (length, sampling_rate, frequency, amplitude, phase, delay) // plot(array.get(A, bar_index%length)) //{ remarks: //}}} // @function Create a Sine wave. // @param length int, The number of samples to generate. // @param sampling_rate float, Samples per time unit (Hz). Must be larger than twice the frequency to satisfy the Nyquist criterion. // @param frequency float, Frequency in periods per time unit (Hz). // @param amplitude float, The maximal reached peak. // @param mean float, The mean, or DC part, of the signal. // @param phase float, Optional phase offset. // @param delay int, Optional delay, relative to the phase. // @returns float array. export sinusoidal (int length, float sampling_rate, float frequency, float amplitude, float mean = 0.0, float phase = 0.0, int delay = 0) => //{ if length < 1 runtime.error('ArrayGenerate -> sinusoidal() -> Parameter "length": must be a positive value > 0.') float[] _A = na else float _pi2 = mc.Pi2() float _step = frequency / sampling_rate * _pi2 float _phase = (phase - delay * _step) % _pi2 float[] _A = array.new_float(length) for _i = 0 to length-1 array.set(_A, _i, mean + amplitude * math.sin(_phase + _i * _step)) _A //{ usage: // int length = input.int(100), float sampling_rate = input.float(0.55), float frequency = input.float(0.65), float amplitude = input.float(1.0), float mean = input.float(0.0), float phase = input.float(0.0), int delay = input.int(0) // var float[] A = sinusoidal (length, sampling_rate, frequency, amplitude, mean, phase, delay) // plot(array.get(A, bar_index%length)) //{ remarks: //}}} // @function Create a periodic Kronecker Delta impulse sample array. // @param length int, The number of samples to generate. // @param period int, impulse sequence period. // @param amplitude float, The maximal reached peak. // @param delay int, Offset to the time axis. Zero or positive. // @returns float array. export periodic_impulse (int length, int period, float amplitude, int delay) => //{ if length < 1 runtime.error('ArrayGenerate -> periodic_impulse() -> Parameter "length": must be a positive value > 0.') float[] _A = na else float[] _A = array.new_float(length, 0.0) int _delay = ((delay % period) + period) % period // see: https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Euclid.cs#L48 while _delay < length array.set(_A, _delay, amplitude) _delay += period _A //{ usage: // int length = input.int(100), int period = input.int(5), float amplitude = input.float(1.0), int delay = input.int(0) // float[] A = periodic_impulse(length, period, amplitude, delay) // plot(array.get(A, bar_index%length)) //{ remarks: //}}}
MovingAverages
https://www.tradingview.com/script/L9Wzl765-MovingAverages/
Electrified
https://www.tradingview.com/u/Electrified/
12
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // @version=5 // @description Contains utilities for generating moving average values including getting a moving average by name and a function for generating a Volume-Adjusted WMA. library('MovingAverages', true) isLenInvalid(simple int len, simple string name = 'len') => if na(len) runtime.error("The '"+name+"' param cannot be NA.") true else if len < 0 runtime.error("The '"+name+"' param cannot be negative.") true else if len == 0 true else false //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // VAWMA = VWMA and WMA combined. // Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. // Uses triangular algorithm to taper off values in the past (same as WMA does). //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function VAWMA = VWMA and WMA combined. Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. Uses a triangular algorithm to taper off values in the past (same as WMA does). // @param len The number of bars to measure with. // @param src The series to measure from. Default is 'hlc3'. // @param volumeDefault The default value to use when a chart has no (N/A) volume. // @returns The volume adjusted triangular weighted moving average of the series. export vawma( simple int len, series float src = hlc3, simple float volumeDefault = na, simple int startingWeight = 1) => var float notAvailable = na if isLenInvalid(len) notAvailable else sum = 0.0 vol = 0.0 last = len - 1 for i = 0 to last s = src[i] v = volume[i] if na(v) and not na(volumeDefault) v := volumeDefault if not na(s) and not na(v) m = last - i + startingWeight v *= m vol += v sum += s * v vol == 0 ? na : sum/vol /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Coefficient Moving Avereage (CMA) is a variation of a moving average that can simulate SMA or WMA with the advantage of previous data. // @param n The number of bars to measure with. // @param D The series to measure from. Default is 'close'. // @param C The coefficient to use when averaging. 0 behaves like SMA, 1 behaves like WMA. // @param compound When true (default is false) will use a compounding method for weighting the average. export cma( simple int n, series float D = close, simple float C = 1, simple bool compound = false) => var float notAvailable = na if isLenInvalid(n, 'n') notAvailable else var float result = na sum = 0.0 weight = 1.0 weightTotal = 0.0 for m = 1 to n s = D[n - m] if not na(s) sum := sum + s * weight weightTotal += weight if compound weight *= 1 + C else weight += C prev = result[n] if na(prev) result := sum / weightTotal else result := (prev + sum) / (weightTotal + 1) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Same as ta.ema(src,len) but properly ignores NA values. // @param len The number of samples to derive the average from. // @param src The series to measure from. Default is 'close'. export ema( simple int len, series float src = close) => var float notAvailable = na if isLenInvalid(len) notAvailable else var float alpha = 2 / (len + 1) var float a1 = 1 - alpha var float s = na var float ema = na if not na(src) s := src ema := alpha * s + a1 * nz(ema) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Same as ta.wma(src,len) but properly ignores NA values. // @param len The number of samples to derive the average from. // @param src The series to measure from. Default is 'close'. // @param startingWeight The weight to begin with when calculating the average. Higher numbers will decrease the bias. export wma( simple int len, series float src = close, simple int startingWeight = 1) => var float notAvailable = na if isLenInvalid(len) notAvailable else sum = 0.0 total = 0 last = len - 1 for i = 0 to last s = src[i] if not na(s) m = last - i + startingWeight // triangular multiple total += m sum += s * m total == 0 ? na : sum/total /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Same as ta.vwma(src,len) but properly ignores NA values. // @param len The number of bars to measure with. // @param src The series to measure from. Default is 'hlc3'. // @param volumeDefault The default value to use when a chart has no (N/A) volume. export vwma( simple int len, series float src = hlc3, simple float volumeDefault = na) => var float notAvailable = na if isLenInvalid(len) notAvailable else var sum = 0.0 var vol = 0.0 float datum = na v = volume if na(v) and not na(volumeDefault) v := volumeDefault if not na(src) and not na(v) vol += v datum := src * v sum += datum else v := na vStart = v[len] dStart = datum[len] if not na(vStart) vol -= vStart if not na(dStart) sum -= dStart vol == 0 ? na : sum/vol /////////////////////////////////////////////////// type VWAP float sum float volume float value vwap(float sum, float vol, float ratio = 1) => VWAP.new(ratio * sum, ratio * vol, sum/vol) sum(VWAP a, VWAP b, float ratio = 1) => s = a.sum + b.sum v = a.volume + b.volume vwap(s, v, ratio) import Electrified/Time/7 /////////////////////////////////////////////////// // @function This is experimental moving average doesn't use a period/length but instead buffers the price per share and transfers that price per share at a given ratio per bar while also releasing the previous values at a decay ratio. // @param transferRatio The ratio at which buffered data is applied to the average. // @param releaseRatio The ratio at which data is released from the average. // @param useTime When true will tend to make the values consistent across timeframes. // @param src The series to measure from. Default is 'hlc3'. // @param vol The series to represent volume. The default is 'volume'. export rsvwma( simple float transferRatio, simple float releaseRatio, simple bool useTime, series float src = hlc3, float vol = volume) => var retainRatio = 1 - releaseRatio var minutesPerBar = Time.bar() / 1000 / 60 var m = useTime ? minutesPerBar : 1 var r = math.pow(1 - transferRatio, m) var active = VWAP.new(0, 0, 0) var surplus = VWAP.new(0, 0, 0) s = surplus.sum + nz(src * vol) v = surplus.volume + (na(src) ? 0 : nz(vol)) transfer = vwap(s, v, 1 - r) surplus := vwap(s, v, r) active := sum(active, transfer, math.pow(retainRatio, m)) active.value /////////////////////////////////////////////////// SMA = 'SMA', EMA = 'EMA', WMA = 'WMA', CMA = 'CMA', VWMA = 'VWMA', VAWMA = 'VAWMA' /////////////////////////////////////////////////// // @function Generates a moving average based upon a 'type'. // @param type The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param len The number of bars to measure with. // @param src The series to measure from. Default is 'close'. // @returns The moving average series requested. export get( simple string type, simple int len, series float src = close) => switch type WMA => wma(len, src) EMA => ema(len, src) VWMA => vwma(len, src) VAWMA => vawma(len, src) CMA => cma(len, src) SMA => ta.sma(src, len) => runtime.error("No matching MA type found.") ta.sma(src, len) /////////////////////////////////////////////////// getLevels(float[] values) => avg = math.abs(array.avg(values)) stdev = array.stdev(values) [avg + stdev, stdev] /////////////////////////////////////////////////// // @function The slope of the source (change over time) is measured over the mLen to determine what is considered 'normal'. A positive value less than 1 is considered within 1 standard deviation. A value less than 2 is within 2 standard deviations and so-on. This allows for the slope of a value to be standardized regardless of the symbol. // @param source The series (typically a moving average) to meaasue the slope. // @param mlen The number of bars to measure the standard deviation of the slope. // @param slopeLen The number of bars to measure the slope. A higher number will smooth out the curve. // @returns The nromalized value of the slope. normalizeSlope(series float source, simple int mLen = 400, simple int slopeLen = 1) => var pos = array.new_float() var neg = array.new_float() change = ta.change(source, slopeLen) if(change > 0) array.push(pos, change) if array.size(pos) > mLen array.shift(pos) if(change < 0) array.push(neg, change) if array.size(neg) > mLen array.shift(neg) [pos_level1, pos_stdev] = getLevels(pos) [neg_level1, neg_stdev] = getLevels(neg) if change > 0 if(change < pos_level1) change / pos_level1 else (change - pos_level1) / pos_stdev + 1 else if change < 0 if(change > -neg_level1) change / neg_level1 else (change + neg_level1) / neg_stdev - 1 else 0 /////////////////////////////////////////////////// // Demo plot(ema(20), 'ema(20)', color.red) plot(wma(20), 'wma(20)', color.yellow) plot(vwma(20), 'vwma(20)', color.blue) plot(vawma(20), 'vawma(20)', color.purple)
AnalysisInterpolationLoess
https://www.tradingview.com/script/1fOdjHkW-AnalysisInterpolationLoess/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
76
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos // Special apreciation to: @midtownSk8rguy, @kaigouthro //@version=5 // @description LOESS, local weighted Smoothing function. library(title='AnalysisInterpolationLoess') // reference: // https://commons.apache.org/proper/commons-math/javadocs/api-3.3/org/apache/commons/math3/analysis/interpolation/LoessInterpolator.html // @function Helper function. // @param value float, value. // @returns float. square (float value) => //{ math.pow(value, 2.0) //} // @function Helper function. // @param value float, value. // @returns float. cube (float value) => //{ math.pow(value, 3.0) //} // @function Helper function for the loess library // @param value float, value. // @returns float tricubic (float value) => //{ if value > 1.0 0.0 else cube(1.0 - cube(value)) //} // @function Helper function for the loess library // @param value float, value. // @param exponent float, exponent. // @returns float polyweight (float value, float exponent) => //{ if value > 1.0 0.0 else math.pow(1.0 - math.pow(value, exponent), exponent) //{ credit to @midtownSk8rguy //}} // @function Helper function for the loess library // @param value float, value. // @param exp float, exp. // @returns float nweight (float _i1, float _i, float _exp) => //{ math.exp(-(math.pow(_i1 - _i, _exp)/(math.pow(_exp,_exp)))) // credit to: @kaigouthro //} // @function LOESS, local weighted Smoothing function. // @param sample_x int array, x values. // @param sample_y float array, y values. // @param point_span int, local point interval span. // @returns float array with points y value. export loess (int[] sample_x, float[] sample_y, int point_span=2) => //{ int _size_x = array.size(id=sample_x)-1 int _size_y = array.size(id=sample_y)-1 // to improve performance there is: // no monotonic sequence check, no null checks. // Overflow checks: switch (_size_x < 1 or _size_y < 1) => runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have at the least 1 element.') (_size_x != _size_y) => runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have the same number of elements.') (point_span < 1) => runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be positive integer number over 0.') (2.0 * point_span > _size_x) => runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be smaller than sample size.') // float[] _yloess = array.new_float(size=1 + _size_x) for _i = 0 to _size_x int _xi = array.get(id=sample_x, index=_i) // define the index interval to pool the values int _start = math.max(0, _i - point_span) // by: kaigouthro int _end = math.min(_i + point_span, _size_x) // by: kaigouthro // grab the values for the interval span int[] _span_x = array.slice(id=sample_x, index_from=_start, index_to=_end) float[] _span_y = array.slice(id=sample_y, index_from=_start, index_to=_end) // calculate the distance, weights then perform local regression int _size_s = array.size(id=_span_x) - 1 float _sum_w = 0.0 float _sum_x = 0.0 float _sum_x2 = 0.0 float _sum_y = 0.0 float _sum_xy = 0.0 for _s = 0 to _size_s int _xs = array.get(id=_span_x, index=_s) float _ys = array.get(id=_span_y, index=_s) int _ds = math.abs(_xs-_xi) float _ws = tricubic(_ds / point_span) float _wxs = _ws * _xs _sum_w += _ws _sum_x += _wxs _sum_x2 += _wxs * _xs _sum_y += _ws * _ys _sum_xy += _wxs * _ys float _mean_x = _sum_x / _sum_w float _mean_y = _sum_y / _sum_w float _mean_xy = _sum_xy / _sum_w float _mean_x2 = _sum_x2 / _sum_w float _mx2xx = _mean_x2 - square(_mean_x) float _beta = 0.0 if math.sqrt(math.abs(_mx2xx)) < 1.0e-15 _beta := (_mean_xy - _mean_x * _mean_y) / _mx2xx float _alpha = _mean_y - _beta * _mean_x //update current y loess value at _i index array.set(id=_yloess, index=_i, value=_beta * _xi + _alpha) _yloess //{ usage: // length = input.int(50) // npoints= input.int(7) // f_l1(_x1, _y1, _x2, _y2) => line.new(_x1, _y1, _x2, _y2, color=#DDDD00, style=line.style_solid, width=1) // import RicardoSantos/ArrayExtension/2 as ae // a = bar_index < length ? array.from(0) : ae.to_int(ae.sequence_from_series(bar_index, length, 0, true), 'floor') // b = bar_index < length ? array.from(0.0) : ae.sequence_from_series(close, length, 0, true) // if barstate.islastconfirmedhistory // c = loess(a, b, npoints) // label.new(bar_index, 0.0, str.tostring(c, '#.###')) // for _i = 1 to array.size(a)-1 // _x1 = array.get(a, _i-1) // _x2 = array.get(a, _i ) // _by1 = array.get(c, _i-1) // _by2 = array.get(c, _i) // f_l1(_x1, _by1, _x2, _by2) // plot(close) //}} // @function aLOESS, adaptive local weighted Smoothing function. // @param sample_x int array, x values. // @param sample_y float array, y values. // @param point_span int, local point interval span. // @param span_exp float, local span exp factor, default=na, will run regular LOESS algorithm, adaptive otherwise. // @returns float array with points y value. export aloess (int[] sample_x, float[] sample_y, int point_span=2, float span_exponent=3.0) => //{ int _size_x = array.size(id=sample_x)-1 int _size_y = array.size(id=sample_y)-1 // to improve performance there is: // no monotonic sequence check, no null checks. // Overflow checks: switch (_size_x < 1 or _size_y < 1) => runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have at the least 1 element.') (_size_x != _size_y) => runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have the same number of elements.') (point_span < 1) => runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be positive integer number over 0.') (2.0 * point_span > _size_x) => runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be smaller than sample size.') // float[] _yloess = array.new_float(size=1 + _size_x) for _i = 0 to _size_x int _xi = array.get(id=sample_x, index=_i) // define the index interval to pool the values int _start = math.max(0, _i - point_span) // by: kaigouthro int _end = math.min(_i + point_span, _size_x) // by: kaigouthro // grab the values for the interval span int[] _span_x = array.slice(id=sample_x, index_from=_start, index_to=_end) float[] _span_y = array.slice(id=sample_y, index_from=_start, index_to=_end) // calculate the distance, weights then perform local regression int _size_s = array.size(id=_span_x)-1 float _sum_w = 0.0 float _sum_x = 0.0 float _sum_x2 = 0.0 float _sum_y = 0.0 float _sum_xy = 0.0 for _s = 0 to _size_s int _xs = array.get(id=_span_x, index=_s) float _ys = array.get(id=_span_y, index=_s) int _ds = math.abs(_xs - _xi) float _ws = polyweight(_ds / point_span, span_exponent) float _wxs = _ws * _xs _sum_w += _ws _sum_x += _wxs _sum_x2 += _wxs * _xs _sum_y += _ws * _ys _sum_xy += _wxs * _ys float _mean_x = _sum_x / _sum_w float _mean_y = _sum_y / _sum_w float _mean_xy = _sum_xy / _sum_w float _mean_x2 = _sum_x2 / _sum_w float _mx2xx = _mean_x2 - square(_mean_x) float _beta = 0.0 if math.sqrt(math.abs(_mx2xx)) < 1.0e-15 _beta := (_mean_xy - _mean_x * _mean_y) / _mx2xx float _alpha = _mean_y - _beta * _mean_x //update current y loess value at _i index array.set(id=_yloess, index=_i, value=_beta * _xi + _alpha) _yloess //{ usage: adaptive = input.bool(false) length = input.int(50) npoints = input.int(7) exp = input.float(3.0) f_l1(_x1, _y1, _x2, _y2) => line.new(_x1, _y1, _x2, _y2, color=#DDDD00, style=line.style_solid, width=1) import RicardoSantos/ArrayGenerate/1 as ag import RicardoSantos/ArrayExtension/1 as ae a = bar_index <= length ? array.from(0) : ae.to_int(ag.sequence_from_series(bar_index, length, 0, true), 'floor') b = bar_index <= length ? array.from(0.0) : ag.sequence_from_series(close, length, 0, true) if barstate.islastconfirmedhistory c = adaptive ? aloess(a, b, npoints, exp) : loess(a, b, npoints) // label.new(bar_index, 0.0, str.tostring(c, '#.###')) for _i = 1 to array.size(a)-1 _x1 = array.get(a, _i-1) _x2 = array.get(a, _i ) _by1 = array.get(c, _i-1) _by2 = array.get(c, _i) f_l1(_x1, _by1, _x2, _by2) plot(close) //}} // @function LOESS moving average. // @param source float, data source. // @param length int, data source sampling length. // @param point_span int, local point interval span. // @param span_exp float, local span exp factor, default=na, will run regular LOESS algorithm, adaptive otherwise. // @retuns float. // Note: this only pools the last value of the series so it will not produce the smoothed results as in the original. ma (float source, int length, int point_span=3, float span_exp=na) => //{ var int[] _x = array.new_int(length, bar_index) var float[] _y = array.new_float(length, source) array.pop(_x), array.unshift(_x, bar_index) array.pop(_y), array.unshift(_y, source) if na(span_exp) array.get(loess(_x, _y, point_span), 0) else array.get(aloess(_x, _y, point_span, span_exp), 0) //{ usage: plot(ma(close, length, npoints, adaptive?exp:na), color=color.red, linewidth=3) //}} // @function LOESS moving average by kaigouthro. // @param source float, data source. // @param len int, data source sampling length. // @param point_spaninput int, local point interval span. // @param exp float, local span exp factor, default=0.0, will run regular LOESS algorithm, adaptive otherwise. // @retuns float. loest (float src, int len=18, int point_spaninput=15, float exp=0.0) => //{ float[] _out_array = array.new_float() _length = len - (point_spaninput) point_span = math.max(2, math.min(math.abs(point_spaninput), math.floor(len/3))) tlen = math.min(_length, len-point_span) for _i = 0 to tlen by 1 _sum_w = 0., _sum_x = 0., _sum_x2 = 0., _sum_y = 0., _sum_xy = 0., _beta = 0. int _end = math.min(_i + point_span, len - 1) int _start = math.max(0, _end - point_span) int _xi = tlen - _i for _s = 0 to point_span -1 int _xs = tlen - (_i + _s) _ys = src[_i +_s] _ds = math.abs( _xs - _xi) * (point_span / _length) * math.pow(math.phi, math.phi) _ws = nweight(_ds, point_span, exp) _wxs = _ws * _xs * (exp * 1.5-((1 + _s)/point_span)) _sum_w += _ws _sum_x += _wxs , _sum_x2 += _wxs * _xs _sum_y += _ws * _ys , _sum_xy += _wxs * _ys float _mean_x = _sum_x / _sum_w float _mean_y = _sum_y / _sum_w float _mean_xy = _sum_xy / _sum_w float _mean_x2 = _sum_x2 / _sum_w float _mx2xx = _mean_x2 - _mean_x * _mean_x if math.sqrt(math.abs(_mx2xx)) < 1.0e-15 _beta := (_mean_xy - _mean_x * _mean_y) / _mx2xx float _alpha = _mean_y - _beta * _mean_x array.push(_out_array, math.round_to_mintick(_beta * _xi + _alpha)) array.avg(_out_array) // usage: oc = loest(close, length, npoints, adaptive?exp:0.0) plot(oc, 'loesst', oc>oc[1] ? color.green:color.orange,2) // credit to: @kaigouthro. //}
MathSpecialFunctionsTestFunctions
https://www.tradingview.com/script/odTXh1HE-MathSpecialFunctionsTestFunctions/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
6
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods for test functions. library(title='MathSpecialFunctionsTestFunctions') // reference: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/SpecialFunctions/TestFunctions.cs // imports: import RicardoSantos/DebugConsole/2 as console [__T, __C] = console.init(25) import RicardoSantos/MathConstants/1 as constants // constants.Pi2() -> ackley() // @function Valley-shaped Rosenbrock function for 2 dimensions: (x,y) -> (1-x)^2 + 100*(y-x^2)^2. // @param input_x float, common range within (-5.0, 10.0) or (-2.048, 2.048). // @param input_y float, common range within (-5.0, 10.0) or (-2.048, 2.048). // @returns float export rosenbrock (float input_x, float input_y) => //{ float _a = 1.0 - input_x float _b = input_y - math.pow(input_x, 2.0) math.pow(_a, 2.0) + 100 * math.pow(_b, 2.0) //{ usage: console.queue_one(__C, str.format('rosenbrock(2, 1): {0}', rosenbrock(2.0, 1.0))) //{ remarks: // This function has a global minimum at (1,1) with f(1,1) = 0. // Common range: [-5,10] or [-2.048,2.048]. // https://en.wikipedia.org/wiki/Rosenbrock_function // http://www.sfu.ca/~ssurjano/rosen.html // test: https://www.wolframalpha.com/input/?i=rosenbrock+function+%282%2C1%29 //}}} // @function Valley-shaped Rosenbrock function for 2 or more dimensions. // @param samples float array, common range within (-5.0, 10.0) or (-2.048, 2.048). // @returns float export rosenbrock_mdim (float[] samples) => //{ int _size = array.size(samples) if _size < 2 runtime.error('MathSpecialFunctionsTestFunctions -> ackley(): "samples" has wrong size.') float(na) else float _sum = 0.0 for _i = 1 to _size-1 float _xi = array.get(samples, _i) _sum += rosenbrock(array.get(samples, _i - 1), array.get(samples, _i)) _sum //{ usage: console.queue_one(__C, str.format('rosenbrock_mdim([2, 1, ,-1, -2]): {0}', rosenbrock_mdim(array.from(2.0, 1.0, -1.0, -2.0)))) //{ remarks: // This function have a global minimum of all ones and, for 8 > N > 3, a local minimum at (-1,1,...,1). // https://en.wikipedia.org/wiki/Rosenbrock_function // http://www.sfu.ca/~ssurjano/rosen.html //}}} // @function Himmelblau, a multi-modal function: (x,y) -> (x^2+y-11)^2 + (x+y^2-7)^2 // @param input_x float, common range within (-6.0, 6.0 ). // @param input_y float, common range within (-6.0, 6.0 ). // @returns float export himmelblau (float input_x, float input_y) => //{ float _a = math.pow(input_x, 2.0) + input_y - 11.0 float _b = input_x + math.pow(input_y, 2.0) - 7.0 math.pow(_a, 2.0) + math.pow(_b, 2.0) //{ usage: console.queue_one(__C, str.format('himmelblau(2, 1): {0}', himmelblau(2.0, 1.0))) //{ remarks: // This function has 4 global minima with f(x,y) = 0. // Common range: [-6,6]. // Named after David Mautner Himmelblau // https://en.wikipedia.org/wiki/Himmelblau%27s_function //}}} // @function Rastrigin, a highly multi-modal function with many local minima. // @param samples float array, common range within (-5.12, 5.12 ). // @returns float export rastrigin (float[] samples) => //{ int _size = array.size(samples) if _size < 1 runtime.error('MathSpecialFunctionsTestFunctions -> ackley(): "samples" has wrong size.') float(na) else float _pi2 = constants.Pi2() float _sx2 = 0.0 for _i = 0 to _size-1 float _xi = array.get(samples, _i) _sx2 += math.pow(_xi, 2.0) - 10.0 * math.cos(_pi2 * _xi) _sx2 += 10.0 * _size //{ usage: console.queue_one(__C, str.format('rastrigin([2, 1, ,-1, -2]): {0}', rastrigin(array.from(2.0, 1.0, -1.0, -2.0)))) //{ remarks: // Global minimum of all zeros with f(0) = 0. // Common range: [-5.12,5.12]. // https://en.wikipedia.org/wiki/Rastrigin_function // http://www.sfu.ca/~ssurjano/rastr.html //}}} // @function Drop-Wave, a multi-modal and highly complex function with many local minima. // @param input_x float, common range within (-5.12, 5.12 ). // @param input_y float, common range within (-5.12, 5.12 ). // @returns float export drop_wave (float input_x, float input_y) => //{ float _t = math.pow(input_x, 2.0) + math.pow(input_y, 2.0) -(1.0 + math.cos(12.0 * math.sqrt(_t))) / (0.5 * _t + 2.0) //{ usage: console.queue_one(__C, str.format('drop_wave(2, 1): {0}', drop_wave(2.0, 1.0))) //{ remarks: // Global minimum of all zeros with f(0) = -1. // Common range: [-5.12,5.12]. // http://www.sfu.ca/~ssurjano/drop.html //}}} // @function Ackley, a function with many local minima. It is nearly flat in outer regions but has a large hole at the center. // @param input_x float array, common range within (-32.768, 32.768 ). // @returns float export ackley (float[] samples) => //{ int _size = array.size(samples) if _size < 1 runtime.error('MathSpecialFunctionsTestFunctions -> ackley(): "samples" has wrong size.') float(na) else float _pi2 = constants.Pi2() float _u = 0.0 float _v = 0.0 for _i = 0 to _size-1 float _xi = array.get(samples, _i) _u += math.pow(_xi, 2.0) _v += math.cos(_pi2 * _xi) _u /= _size _v /= _size -20.0 * math.exp(-0.2 * math.sqrt(_u)) - math.exp(_v) + 20.0 + math.e //{ usage: console.queue_one(__C, str.format('ackley([2, 1, ,-1, -2]): {0}', ackley(array.from(2.0, 1.0, -1.0, -2.0)))) //{ remarks: // Global minimum of all zeros with f(0) = 0. // Common range: [-32.768, 32.768]. // http://www.sfu.ca/~ssurjano/ackley.html //}}} // @function Bowl-shaped first Bohachevsky function. // @param input_x float, common range within (-100.0, 100.0 ). // @param input_y float, common range within (-100.0, 100.0 ). // @returns float export bohachevsky1 (float input_x, float input_y) => //{ math.pow(input_x, 2.0) + 2.0 * math.pow(input_y, 2.0) - 0.3 * math.cos(3.0 * math.pi * input_x) - 0.4 * math.cos(4.0 * math.pi * input_y) //{ usage: console.queue_one(__C, str.format('bohachevsky1(2, 1): {0}', bohachevsky1(2.0, 1.0))) //{ remarks: // Global minimum of all zeros with f(0,0) = 0. // Common range: [-100, 100] // http://www.sfu.ca/~ssurjano/boha.html //}}} // @function Plate-shaped Matyas function. // @param input_x float, common range within (-10.0, 10.0 ). // @param input_y float, common range within (-10.0, 10.0 ). // @returns float export matyas (float input_x, float input_y) => //{ 0.26 * (math.pow(input_x, 2.0) + math.pow(input_y, 2.0)) - 0.48 * input_x * input_y //{ usage: console.queue_one(__C, str.format('matyas(2, 1): {0}', matyas(2.0, 1.0))) //{ remarks: // Global minimum of all zeros with f(0,0) = 0. // Common range: [-10, 10]. // http://www.sfu.ca/~ssurjano/matya.html //}}} // @function Valley-shaped six-hump camel back function. // @param input_x float, common range within (-3.0, 3.0 ). // @param input_y float, common range within (-2.0, 2.0 ). // @returns float export six_hump_camel (float input_x, float input_y) => //{ float _x2 = math.pow(input_x, 2) float _y2 = math.pow(input_y, 2) (4.0 - 2.1 * _x2 + math.pow(_x2, 2.0) / 3.0) * _x2 + input_x * input_y + (-4.0 + 4.0 * _y2) * _y2 //{ usage: console.queue_one(__C, str.format('six_hump_camel(2, 1): {0}', six_hump_camel(2.0, 1.0))) //{ remarks: // Two global minima and four local minima. Global minima with f(x) ) -1.0316 at (0.0898,-0.7126) and (-0.0898,0.7126). // Common range: x in [-3,3], y in [-2,2]. // http://www.sfu.ca/~ssurjano/camel6.html //}}} //############################################################################## console.update(__T, __C)
MathConstants
https://www.tradingview.com/script/0z8WYrjM-MathConstants/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
23
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Mathematical Constants library(title='MathConstants') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Constants.cs // A collection of frequently used mathematical constants. // Mathematical Constants { // @function The number e export E () => //{ 2.7182818284590452353602874713526624977572470937000 //} // @function The number log[2](e) export Log2E () => //{ 1.4426950408889634073599246810018921374266459541530 //} // @function The number log[10](e) export Log10E () => //{ 0.43429448190325182765112891891660508229439700580366 //} // @function The number log[e](2) export Ln2 () => //{ 0.69314718055994530941723212145817656807550013436026 //} // @function The number log[e](10) export Ln10 () => //{ 2.3025850929940456840179914546843642076011014886288 //} // @function The number log[e](pi) export LnPi () => //{ 1.1447298858494001741434273513530587116472948129153 //} // @function The number log[e](2*pi)/2 export Ln2PiOver2 () => //{ 0.91893853320467274178032973640561763986139747363780 //} // @function The number 1/e export InvE () => //{ 0.36787944117144232159552377016146086744581113103176 //} // @function The number sqrt(e) export SqrtE () => //{ 1.6487212707001281468486507878141635716537761007101 //} // @function The number sqrt(2) export Sqrt2 () => //{ 1.4142135623730950488016887242096980785696718753769 //} // @function The number sqrt(3) export Sqrt3 () => //{ 1.7320508075688772935274463415058723669428052538104 //} // @function The number sqrt(1/2) = 1/sqrt(2) = sqrt(2)/2 export Sqrt1Over2 () => //{ 0.70710678118654752440084436210484903928483593768845 //} // @function The number sqrt(3)/2 export HalfSqrt3 () => //{ 0.86602540378443864676372317075293618347140262690520 //} // @function The number pi export Pi () => //{ 3.1415926535897932384626433832795028841971693993751 //} // @function The number pi*2 export Pi2 () => //{ 6.2831853071795864769252867665590057683943387987502 //} // @function The number pi/2 export PiOver2 () => //{ 1.5707963267948966192313216916397514420985846996876 //} // @function The number pi*3/2 export Pi3Over2 () => //{ 4.71238898038468985769396507491925432629575409906266 //} // @function The number pi/4 export PiOver4 () => //{ 0.78539816339744830961566084581987572104929234984378 //} // @function The number sqrt(pi) export SqrtPi () => //{ 1.7724538509055160272981674833411451827975494561224 //} // @function The number sqrt(2pi) export Sqrt2Pi () => //{ 2.5066282746310005024157652848110452530069867406099 //} // @function The number sqrt(pi/2) export SqrtPiOver2 () => //{ 1.2533141373155002512078826424055226265034933703050 //} // @function The number sqrt(2*pi*e) export Sqrt2PiE () => //{ 4.1327313541224929384693918842998526494455219169913 //} // @function The number log(sqrt(2*pi)) export LogSqrt2Pi () => //{ 0.91893853320467274178032973640561763986139747363778 //} // @function The number log(sqrt(2*pi*e)) export LogSqrt2PiE () => //{ 1.4189385332046727417803297364056176398613974736378 //} // @function The number log(2 * sqrt(e / pi)) export LogTwoSqrtEOverPi () => //{ 0.6207822376352452223455184457816472122518527279025978 //} // @function The number 1/pi export InvPi () => //{ 0.31830988618379067153776752674502872406891929148091 //} // @function The number 2/pi export TwoInvPi () => //{ 0.63661977236758134307553505349005744813783858296182 //} // @function The number 1/sqrt(pi) export InvSqrtPi () => //{ 0.56418958354775628694807945156077258584405062932899 //} // @function The number 1/sqrt(2pi) export InvSqrt2Pi () => //{ 0.39894228040143267793994605993438186847585863116492 //} // @function The number 2/sqrt(pi) export TwoInvSqrtPi () => //{ 1.1283791670955125738961589031215451716881012586580 //} // @function The number 2 * sqrt(e / pi) export TwoSqrtEOverPi () => //{ 1.8603827342052657173362492472666631120594218414085755 //} // @function The number (pi)/180 - factor to convert from Degree (deg) to Radians (rad). export Degree () => //{ 0.017453292519943295769236907684886127134428718885417 //} // @function The number (pi)/200 - factor to convert from NewGrad (grad) to Radians (rad). export Grad () => //{ 0.015707963267948966192313216916397514420985846996876 //} // @function The number ln(10)/20 - factor to convert from Power Decibel (dB) to Neper (Np). Use this version when the Decibel represent a power gain but the compared values are not powers (e.g. amplitude, current, voltage). export PowerDecibel () => //{ 0.11512925464970228420089957273421821038005507443144 //} // @function The number ln(10)/10 - factor to convert from Neutral Decibel (dB) to Neper (Np). Use this version when either both or neither of the Decibel and the compared values represent powers. export NeutralDecibel () => //{ 0.23025850929940456840179914546843642076011014886288 //} // @function The Catalan constant // Sum(k=0 -> inf){ (-1)^k/(2*k + 1)2 } export Catalan () => //{ 0.9159655941772190150546035149323841107741493742816721342664981196217630197762547694794 //} // @function The Euler-Mascheroni constant // lim(n -> inf){ Sum(k=1 -> n) { 1/k - log(n) } } export EulerMascheroni () => //{ 0.5772156649015328606065120900824024310421593359399235988057672348849 //} // @function The number (1+sqrt(5))/2, also known as the golden ratio export GoldenRatio () => //{ 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072 //} // @function The Glaisher constant // e^(1/12 - Zeta(-1)) export Glaisher () => //{ 1.2824271291006226368753425688697917277676889273250011920637400217404063088588264611297 //} // @function The Khinchin constant // prod(k=1 -> inf){1+1/(k*(k+2))^log(k,2)} export Khinchin () => //{ 2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011 //} //}
SupportResitanceAndTrend
https://www.tradingview.com/script/p7CZyF5N-SupportResitanceAndTrend/
Electrified
https://www.tradingview.com/u/Electrified/
95
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // @version=5 // @description Contains utilities for finding key levels of support, resistance and direction of trend. library('SupportResitanceAndTrend', true) import Electrified/MovingAverages/10 as MA import Electrified/DataCleaner/5 as Data //////////////////////////////////////////////////////////////// // @type A high and low value pair. // @field hi The high value. // @field lo The low value. export type Boundary float hi float lo //////////////////////////////////////////////////////////////// // @type The state of the trend. // @field trend The integer representing the trend. // @field up The value boundary value when the trend is up. // @field dn The value boundary value when the trend is down. // @field hitCount The number of times the boundary has been tested but trend is still intact. // @field warning True if the active boundary has been hit. // @field reversal True if the trend has confirmed reversal. export type TrendState int trend float up float dn int hitCount bool warning bool reversal /////////////////////////////////////////////////// // @function Determines the local trend of a series that and persists the trend if the value is unchanged. // @param src The source series to derive from. // @return +1 when the trend is up; -1 when the trend is down; 0 if the trend is not yet established. export trend(series float src) => var s = 0 if src > src[1] s := +1 if src < src[1] s := -1 s /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Determines the local trend of each boundary level that and persists the trend if the value is unchanged. // @param src The source series to derive from. export trend(series Boundary src) => hi = trend(src.hi) lo = trend(src.lo) Boundary.new(hi, lo) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function A more flexible version of SuperTrend that allows for supplying the series used and sensitivity adjustment by confirming close bars. // @param multiple The multiple to apply to the average true range. // @param h The high values. // @param l The low values. // @param atr The average true range values. // @param closeBars The number of bars to confirm a change in trend. export superTrendPlus( simple float multiple, series float h, series float l, series float atr, simple int closeBars = 0) => up = l-(multiple*atr) up1 = nz(up[1], up) up := l[1] > up1 ? math.max(up, up1) : up dn = h+(multiple*atr) dn1 = nz(dn[1], dn) dn := h[1] < dn1 ? math.min(dn, dn1) : dn var lastU = up1 var lastD = dn1 var trend = 0 var confirmation = 0 var unconfirmed = 0 // cover gap cases if(trend != +1 and l > lastD) trend := +1 else if(trend != -1 and h < lastU) trend := -1 // confirmed cases else if(trend != +1 and h > lastD) unconfirmed += 1 if(confirmation<closeBars and close[1]>lastD) confirmation += 1 if(confirmation>=closeBars) trend := +1 else if(trend != -1 and l < lastU) unconfirmed += 1 if(confirmation<closeBars and close[1]<lastU) confirmation += 1 if(confirmation>=closeBars) trend := -1 if(trend[1]!=trend) lastU := up1 lastD := dn1 confirmation := 0 unconfirmed := 0 else lastU := trend==+1 ? math.max(lastU, up1) : up1 lastD := trend==-1 ? math.min(lastD, dn1) : dn1 // Trend is clearly continuing? Reset confirmation. if(trend==+1 and dn1>dn1[1] or trend==-1 and up1<up1[1]) confirmation := 0 unconfirmed := 0 TrendState.new(trend, lastU, lastD, unconfirmed, unconfirmed[1]==0 and unconfirmed > 0, trend != trend[1]) /////////////////////////////////////////////////// getATR(simple string mode, simple int period, simple float maxDeviation) => trCleaned = maxDeviation==0 ? ta.tr : Data.naOutliers(ta.tr, period, maxDeviation) MA.get(mode, period, trCleaned) //// /////////////////////////////////////////////////// // @function superTrendPlus with simplified parameters. // @param multiple The multiple to apply to the average true range. // @param period The number of bars to measure. // @param mode The type of moving average to use with the true range. // @param closeBars The number of bars to confirm a change in trend. export superTrend( simple float multiple, simple int period, simple string mode = 'WMA', simple int closeBars = 0, simple float maxDeviation = 0) => atr = getATR(mode, period, maxDeviation) superTrendPlus(multiple, high, low, atr, closeBars) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function superTrendPlus with default compensation for extreme volatility. // @param multiple The multiple to apply to the average true range. // @param period The number of bars to measure. // @param mode The type of moving average to use with the true range. // @param closeBars The number of bars to confirm a change in trend. // @param maxDeviation The optional standard deviation level to use when cleaning the series. The default is the value of the provided level. export superTrendCleaned( simple float multiple, simple int period, simple string mode = 'WMA', simple int closeBars = 0, simple float maxDeviation = 4) => atr = getATR(mode, period, maxDeviation) superTrendPlus(multiple, high, low, atr, closeBars) /////////////////////////////////////////////////// calcDev(series float source, simple int len, simple float multiple) => ta.wma(source, len) + ta.wma(ta.stdev(source, len * 2), len) * multiple /////////////////////////////////////////////////// // @function superTrendPlus with default compensation for extreme volatility. // @param multiple The multiple to apply to the average true range. // @param period The number of bars to measure. // @param mode The type of moving average to use with the true range. // @param closeBars The number of bars to confirm a change in trend. // @param maxDeviation The optional standard deviation level to use when cleaning the series. The default is the value of the provided level. export superTrendAuto( simple int volatilityLength, simple float deviationLevel, simple int deviationLength, simple int confirmBars = 2, simple float atrMultiple = 0.5, simple float maxAtrDeviation = 2.5) => atr = getATR("WMA", deviationLength, maxAtrDeviation) tolerance = atr * atrMultiple // Determine the range for the delta length upDev = calcDev(math.max(high - low[volatilityLength], 0), deviationLength, deviationLevel) dnDev = calcDev(math.max(high[volatilityLength] - low, 0), deviationLength, deviationLevel) // Trend UP = +1, DOWN = -1 var trend = 0 var upper = high var lower = low var brokenCount = 0 var wasTouched = false warn = false reversal = false upperWarning = close > upper lowerWarning = close < lower upperBroken = close[1] - tolerance > upper lowerBroken = close[1] + tolerance < lower if trend == UP // Touching the lower boundary resets the warning condition if upperWarning brokenCount := 0 wasTouched := false if lowerWarning wasTouched := true warn := true else if lowerBroken lower := low[1] if upperBroken brokenCount += 1 if trend == DOWN // Touching the upper boundary resets the warning condition if lowerWarning brokenCount := 0 wasTouched := false if upperWarning wasTouched := true warn := true else if upperBroken upper := high[1] if lowerBroken warn := true brokenCount += 1 if trend != UP // If the low exceeds the threshold then confirmation is not required. if brokenCount > confirmBars or low > upper + tolerance trend := UP upper := high[1] reversal := true else if trend != DOWN // If the high exceeds the threshold then confirmation is not required. if brokenCount > confirmBars or high < lower - tolerance trend := DOWN lower := low[1] reversal := true if reversal wasTouched := false brokenCount := 0 // Range adjustment if low[1] + tolerance < upper - dnDev upper := low[1] + dnDev if high[1] - tolerance > lower + upDev lower := high[1] - upDev TrendState.new(trend, lower, upper, brokenCount, warn, reversal) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Identifies support and resistance levels by when a stochastic RSI reverses. export stochSR( simple int smoothK, simple int smoothD, simple int lengthRSI, simple int lengthStoch, series float src = hlc3, simple float lowerBand = 20, simple float upperBand = 80, simple float lowerReversal = 20, simple float upperReversal = 80) => rsi1 = ta.rsi(src, lengthRSI) stoch = ta.stoch(rsi1, rsi1, rsi1, lengthStoch) k = ta.wma(stoch, smoothK) d = ta.sma(k, smoothD) k_c = ta.change(k) d_c = ta.change(d) kd = k - d var hi = high var lo = low var phi = high var plo = low var state = 0 if(d<lowerBand) phi := high if(d>upperBand) plo := low if(high>phi) phi := high if(low<plo) plo := low if(state!=-1 and d<lowerBand) state := -1 else if(state!=+1 and d>upperBand) state := +1 if(hi>phi and state==+1 and k<d and k<lowerReversal) hi := phi if(lo<plo and state==-1 and k>d and k>upperReversal) lo := plo if(high>hi) hi := high if(low<lo) lo := low Boundary.new(hi, lo) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Identifies anchored VWAP levels by when a stochastic RSI reverses. // @returns [active_HL, next_HL] export stochAVWAP( simple int smoothK, simple int smoothD, simple int lengthRSI, simple int lengthStoch, series float src = hlc3, simple float lowerBand = 20, simple float upperBand = 80, simple float lowerReversal = 20, simple float upperReversal = 80, simple bool useHiLow = false) => rsi1 = ta.rsi(src, lengthRSI) stoch = ta.stoch(rsi1, rsi1, rsi1, lengthStoch) k = ta.wma(stoch, smoothK) d = ta.sma(k, smoothD) k_c = ta.change(k) d_c = ta.change(d) kd = k - d var hi = high var lo = low var phi = high var plo = low var state = 0 var float hiAVWAP_s = 0 var float loAVWAP_s = 0 var float hiAVWAP_v = 0 var float loAVWAP_v = 0 var float hiAVWAP_s_next = 0 var float loAVWAP_s_next = 0 var float hiAVWAP_v_next = 0 var float loAVWAP_v_next = 0 if(d<lowerBand or high>phi) phi := high hiAVWAP_s_next := 0 hiAVWAP_v_next := 0 if(d>upperBand or low<plo) plo := low loAVWAP_s_next := 0 loAVWAP_v_next := 0 if(high>hi) hi := high hiAVWAP_s := 0 hiAVWAP_v := 0 if(low<lo) lo := low loAVWAP_s := 0 loAVWAP_v := 0 vwapHi = useHiLow ? high : hlc3 vwapLo = useHiLow ? low : hlc3 hiAVWAP_s += vwapHi * volume loAVWAP_s += vwapLo * volume hiAVWAP_v += volume loAVWAP_v += volume hiAVWAP_s_next += vwapHi * volume loAVWAP_s_next += vwapLo * volume hiAVWAP_v_next += volume loAVWAP_v_next += volume if(state!=-1 and d<lowerBand) state := -1 else if(state!=+1 and d>upperBand) state := +1 if(hi>phi and state==+1 and k<d and k<lowerReversal) hi := phi hiAVWAP_s := hiAVWAP_s_next hiAVWAP_v := hiAVWAP_v_next if(lo<plo and state==-1 and k>d and k>upperReversal) lo := plo loAVWAP_s := loAVWAP_s_next loAVWAP_v := loAVWAP_v_next avwap = Boundary.new(hiAVWAP_s / hiAVWAP_v, loAVWAP_s / loAVWAP_v) avwap_next = Boundary.new(hiAVWAP_s_next / hiAVWAP_v_next, loAVWAP_s_next / loAVWAP_v_next) [avwap, avwap_next] /////////////////////////////////////////////////// // Demo ATR = "Average True Range", CONFIRM = "Confirmation", DISPLAY = "Display" WMA = "WMA", EMA = "EMA", SMA = "SMA", VWMA = "VWMA", VAWMA = "VAWMA" mode = input.string(VAWMA, "Mode", options=[SMA,EMA,WMA,VWMA,VAWMA], group=ATR, tooltip="Selects which averaging function will be used to determine the ATR value.") atrPeriod = input.int(120, "Period", group=ATR, tooltip="The number of bars to use in calculating the ATR value.") atrM = input.float(3.0, title="Multiplier", step=0.5, group=ATR, tooltip="The multiplier used when defining the super trend limits.") closeBars = input.int(2, "Closed Bars", minval = 0, group=CONFIRM, tooltip="The number of closed bars that have to exceed the super-trend value before the trend reversal is confirmed.") st = superTrend(atrM, atrPeriod, mode=mode, closeBars=closeBars) plot(st.up) plot(st.dn) stc = superTrendCleaned(atrM, atrPeriod, mode=mode, closeBars=closeBars) plot(stc.up, color=color.green) plot(stc.dn, color=color.green) // [trendAuto, upAuto, dnAuto, unconfirmedAuto, warnAuto, reversalAuto] = // superTrendAuto(26, 2.5, 1000) // plot(upAuto, color=color.orange) // plot(dnAuto, color=color.orange)
ArrayExtension
https://www.tradingview.com/script/d9HTH42V-ArrayExtension/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
23
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Functions to extend Arrays. library(title='ArrayExtension') // imports: import RicardoSantos/ArrayGenerate/1 as gen // gen.sequence_int() import RicardoSantos/DebugConsole/1 as console [__T, __C] = console.init(35) // @function returns the flatened one dimension index of a two dimension array. // @param dimension_x int, dimension of X. // @param dimension_y int, dimension of Y. // @param index_x int, index of X. // @param index_y int, index of Y. // @returns int, index in 1 dimension export index_2d_to_1d (int dimension_x, int dimension_y, int index_x, int index_y) => //{ int _i = index_x * dimension_y + index_y if _i >= 0 and _i < (dimension_x * dimension_y) _i else runtime.error('ArrayExtension -> index_2d_to_1d(): index out of bounds.') int(na) //} // @function returns the flatened one dimension index of a three dimension array. // @param dimension_x int, dimension of X. // @param dimension_y int, dimension of Y. // @param dimension_z int, dimension of Z. // @param index_x int, index of X. // @param index_y int, index of Y. // @param index_z int, index of Z. // @returns int, index in 1 dimension export index_3d_to_1d (int dimension_x, int dimension_y, int dimension_z, int index_x, int index_y, int index_z) => //{ _i = index_x * dimension_y + index_y * dimension_z + index_z if _i >= 0 and _i < (dimension_x * dimension_y * dimension_z) _i else runtime.error('ArrayExtension -> index_3d_to_1d(): index out of bounds.') int(na) //} // @function Down samples a array to a specified size. // @param sample float array, array with source data. // @param new_size new size of down sampled array. // @returns float array with down sampled data. export down_sample (float[] sample, int new_size) => //{ int _size_old = array.size(id=sample) if new_size < 2 or new_size >= _size_old runtime.error('ArrayExtension -> down_sample(): "new_size" is out of bounds.') float[] _R = na else if _size_old < 1 runtime.error('ArrayExtension -> down_sample(): "sample" is empty') float[] _R = na else float[] _R = array.new_float(size=new_size, initial_value=array.get(id=sample, index=0)) int _step = math.floor(_size_old / new_size) for _i = 1 to new_size-2 _index_from = _i * _step _index_to = (_i + 1) * _step if _i < new_size-2 _s = array.slice(id=sample, index_from=_index_from, index_to=_index_to) _t = array.sum(id=_s)/array.size(id=_s) array.set(id=_R, index=_i, value=_t) else _s = array.slice(id=sample, index_from=_index_from, index_to=_size_old-2) _t = array.sum(id=_s)/array.size(id=_s) array.set(id=_R, index=_i, value=_t) array.set(id=_R, index=new_size-1, value=array.get(id=sample, index=_size_old-1)) _R // usage: // old_length = input(20) // new_length = input(10) // float[] price = array.new_float(0) // for _i = 0 to old_length-1 // array.push(id=price, value=_i) // float[] test = downsampling(price, new_length) // if barstate.ishistory[1] and (barstate.isrealtime or barstate.islast) // label.new(bar_index, 0.0, str.format('{0}: {1}\n{2}: {3}', array.size(price), price, array.size(test), test)) //} // @function Helper method for sort_indices() sort_indices_function (sample, string order='forward') => //{ int _size = array.size(id=sample) // switch (_size < 1) => runtime.error('ArrayExtension -> sort_indices_function(): "sample" is empty') // _ordered = array.copy(id=sample) int[] _indices = gen.sequence_int(start=0, end=_size-1) _tempv = array.get(_ordered, 0), int _tempi = na for _i = 0 to _size - 2 _ai = array.get(_ordered, _i), int _iai = array.get(_indices, _i) for _j = _i + 1 to _size - 1 _aj = array.get(_ordered, _j), int _iaj = array.get(_indices, _j) if _aj < _ai _tempv := _aj, _tempi := _iaj array.set(_ordered, _j, _ai), array.set(_indices, _j, _iai) array.set(_ordered, _i, _tempv), array.set(_indices, _i, _tempi) _ai := _tempv, _iai := _tempi if order == 'backward' array.reverse(id=_indices), array.reverse(id=_ordered) [_indices, _ordered] // // @function Sorts array and returns a extra array with sorting indices. // @param sample (float, int) array with values to be sorted. // @param order string, default='forward', options='forward', 'backward'. // @returns // _indices int array with indices. // _ordered float array with ordered values. export sort_indices (float[] sample, string order='forward') => sort_indices_function(sample, order) export sort_indices (int[] sample, string order='forward') => sort_indices_function(sample, order) // usage: var float[] values_float = array.from(55.0, 66, 44, 77, 80, 90, 1) var int[] values_int = array.from(55, 66, 44, 77, 80, 90, 1) if barstate.islast [indices_float, sorted_float] = sort_indices(values_float, 'backward') [indices_int, sorted_int] = sort_indices(values_int, 'backward') console.queue_one(__C, str.format('sort_indices():\n    float:  {0} -> {1} : {2}', values_float, sorted_float, indices_float)) console.queue_one(__C, str.format('    int:   {0} -> {1} : {2}\n', values_int, sorted_int, indices_int)) //} // @function Helper method for sort_from_indices() sort_from_indices_function (int[] indices, sample) => //{ int _size_i = array.size(id=indices) int _size_s = array.size(id=sample) // switch (_size_i < 1 or _size_s < 1) => runtime.error('ArrayExtension -> sort_bool_from_indices(): "indices" or "sample" is empty.') (_size_i != _size_s ) => runtime.error('ArrayExtension -> sort_bool_from_indices(): "indices" and "sample" size not match.') // _ordered = array.copy(sample) for _i = 0 to _size_i - 1 array.set(id=_ordered, index=_i, value=array.get(id=sample, index=array.get(id=indices, index=_i))) _ordered // // @function Sorts sample array using a array with indices. // @param indices int array with positional indices. // @param sample (bool, box, color, float, int, label, line, string, table) array with data sample to be sorted. // @returns table array export sort_from_indices (int[] indices, bool[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, box[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, color[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, float[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, int[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, label[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, line[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, string[] sample) => sort_from_indices_function (indices, sample) export sort_from_indices (int[] indices, table[] sample) => sort_from_indices_function (indices, sample) // usage: if barstate.islast [indices_float, sorted_float] = sort_indices(values_float, 'backward') console.queue_one(__C, str.format('sort_from_indices(): {0}', indices_float)) console.queue_one(__C, str.format('    bool:   {0}', sort_from_indices(indices_float, array.from(false, false, false, true, true, true, false)))) console.queue_one(__C, str.format('    box:    {0}', 'n/a')) console.queue_one(__C, str.format('    color:   {0}', 'n/a')) console.queue_one(__C, str.format('    float:   {0}', sort_from_indices(indices_float, array.from(5, 4, 6, 3, 2, 1, 7.0)))) console.queue_one(__C, str.format('    int:     {0}', sort_from_indices(indices_float, array.from(5, 4, 6, 3, 2, 1, 7)))) console.queue_one(__C, str.format('    label:   {0}', 'n/a')) console.queue_one(__C, str.format('    line:    {0}', 'n/a')) console.queue_one(__C, str.format('    string:  {0}', sort_from_indices(indices_float, array.from('5', '4', '6', '3', '2', '1', '7')))) console.queue_one(__C, str.format('    table:   {0}', 'n/a\n')) //} // @function Helper method for sort_inplace_from_indices(). sort_inplace_from_indices_function (int[] indices, sample) => //{ int _size_i = array.size(id=indices) int _size_s = array.size(id=sample) // switch (_size_i < 1 or _size_s < 1) => runtime.error('ArrayExtension -> sort_bool_inplace_from_indices(): "indices" or "sample" is empty.') (_size_i != _size_s) => runtime.error('ArrayExtension -> sort_bool_inplace_from_indices(): "indices" and "sample" size not match.') // _ordered = array.copy(id=sample) for _i = 0 to _size_i - 1 array.set(id=sample, index=_i, value=array.get(id=_ordered, index=array.get(id=indices, index=_i))) // @function Sorts sample array inplace using a array with indices. // @param indices int array with positional indices. // @param sample (bool, box, color, float, int, label, line, string, table) array with data sample to be sorted. // @returns void updates sample export sort_inplace_from_indices (int[] indices, bool[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, box[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, color[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, float[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, int[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, label[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, line[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, string[] sample) => sort_inplace_from_indices_function (indices, sample) export sort_inplace_from_indices (int[] indices, table[] sample) => sort_inplace_from_indices_function (indices, sample) // usage: if barstate.islast [_indices, _] = sort_indices(values_float, 'backward') bool[] _bool_sample = array.from(false, false, false, true, true, true, false), sort_inplace_from_indices(_indices, _bool_sample) float[] _float_sample = array.from(5, 4, 6, 3, 2, 1, 7.0), sort_inplace_from_indices(_indices, _float_sample) int[] _int_sample = array.from(5, 4, 6, 3, 2, 1, 7), sort_inplace_from_indices(_indices, _int_sample) string[] _string_sample = array.from('5', '4', '6', '3', '2', '1', '7'), sort_inplace_from_indices(_indices, _string_sample) console.queue_one(__C, str.format('sort_inplace_from_indices(): {0}', _indices)) console.queue_one(__C, str.format('    bool:   {0}', _bool_sample)) console.queue_one(__C, str.format('    box:    {0}', 'n/a')) console.queue_one(__C, str.format('    color:   {0}', 'n/a')) console.queue_one(__C, str.format('    float:   {0}', _float_sample)) console.queue_one(__C, str.format('    int:     {0}', _int_sample)) console.queue_one(__C, str.format('    label:   {0}', 'n/a')) console.queue_one(__C, str.format('    line:    {0}', 'n/a')) console.queue_one(__C, str.format('    string:  {0}', _string_sample)) console.queue_one(__C, str.format('    table:   {0}', 'n/a\n')) //} // @function to_float_method(). { to_float_method_numeric(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_float(): "sample" is empty.') // float[] _new = array.new_float(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=float(array.get(id=sample, index=_i))) _new //} to_float_method_string(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_float(): "sample" is empty.') // float[] _new = array.new_float(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=str.tonumber(array.get(id=sample, index=_i))) _new //} to_float_method_bool(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_float(): "sample" is empty.') // float[] _new = array.new_float(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=array.get(id=sample, index=_i) ? 1.0 : 0.0) _new //} // // @function Transform a array into a float array // @param sample array, sample data to transform. // @returns float array export to_float (int[] sample) => to_float_method_numeric(sample) export to_float (float[] sample) => to_float_method_numeric(sample) export to_float (string[] sample) => to_float_method_string(sample) export to_float (bool[] sample) => to_float_method_bool(sample) // { usage if barstate.islast console.queue_one(__C, str.format('to_float:   {0}', to_float(array.from('0', '1', '0.5')))) //}} // @function to_int_method(). { to_int_method_numeric(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_int(): "sample" is empty.') // int[] _new = array.new_int(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=int(array.get(id=sample, index=_i))) _new //} to_int_method_string(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_int(): "sample" is empty.') // int[] _new = array.new_int(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=int(str.tonumber(array.get(id=sample, index=_i)))) _new //} to_int_method_bool(sample) => //{ int _size = array.size(id=sample) switch (_size < 1) => runtime.error('ArrayExtension -> to_int(): "sample" is empty.') // int[] _new = array.new_int(size=_size) for _i=0 to _size-1 array.set(id=_new, index=_i, value=array.get(id=sample, index=_i) ? 1 : 0) _new //} // // @function Transform a array into a int array // @param sample array, sample data to transform. // @returns int array export to_int (int[] sample) => to_int_method_numeric(sample) export to_int (float[] sample) => to_int_method_numeric(sample) export to_int (string[] sample) => to_int_method_string(sample) export to_int (bool[] sample) => to_int_method_bool(sample) // { usage if barstate.islast console.queue_one(__C, str.format('to_int:   {0}', to_int(array.from('0', '1', '0.5')))) //}} console.update(__T, __C)
SignalProcessingClusteringKMeans
https://www.tradingview.com/script/7pJRwKai-SignalProcessingClusteringKMeans/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
84
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description K-Means Clustering Method. library(title='SignalProcessingClusteringKMeans') // reference: // C version : http://rosettacode.org/wiki/K-means%2B%2B_clustering // @function The Euclidean distance between 2 points. // specialized parameter signature to accomodate for processing. distance2 (float a_x, float a_y, float b_x, float b_y) => //{ math.pow(a_x - b_x, 2.0) + math.pow(a_y - b_y, 2.0) //} // @function finds the nearest center to a point and returns its distance and center index. // @param point_x float, x coordinate of point. // @param point_y float, y coordinate of point. // @param centers_x float array, x coordinates of cluster centers. // @param centers_y float array, y coordinates of cluster centers. // @ returns tuple of int, float. export nearest (float point_x, float point_y, float[] centers_x, float[] centers_y) => //{ int _size_x = array.size(centers_x) int _size_y = array.size(centers_y) int _idx = na, float _dist = 1.0e308 if _size_x < 1 runtime.error('SignalProcessingClusteringKMeans -> nearest(): "centers" have the wrong size.') [_idx, _dist] else if _size_x != _size_y runtime.error('SignalProcessingClusteringKMeans -> nearest(): "centers" x != y.') [_idx, _dist] else for _i = 0 to _size_x-1 float _cx = array.get(centers_x, _i) float _cy = array.get(centers_y, _i) float _d = distance2(_cx, _cy, point_x, point_y) if _d < _dist _dist := _d _idx := _i [_idx, _dist] //} // @function Bissection Search // @param samples float array, weights to compare. // @param value float array, weights to compare. // @returns int. export bisection_search (float[] samples, float value) => //{ int _size_x = array.size(samples) if _size_x < 1 0 else float _x0 = array.get(samples, 0) float _xn = array.get(samples, _size_x-1) // If value is less than samples(0) or greater than samples(n-1) if value < _x0 0 else if value > _xn _size_x - 1 else // bisection search int _il = 0 int _ir = _size_x - 1 _i = (_il + _ir) / 2 while _i != _il if array.get(samples, _i) <= value _il := _i else _ir := _i _i := (_il + _ir) / 2 if array.get(samples, _i) <= value _i := _ir _i // @function labels each point index with cluster index and distance. // @param points_x float array, x coordinates of points. // @param points_y float array, y coordinates of points. // @param centers_x float array, x coordinates of points. // @param centers_y float array, y coordinates of points. // @returns tuple with int array, float array. export label_points (float[] points_x, float[] points_y, float[] centers_x, float[] centers_y) => //{ int _size_px = array.size(points_x) int _size_py = array.size(points_y) int _size_cx = array.size(centers_x) int _size_cy = array.size(centers_y) if _size_px < 1 runtime.error('SignalProcessingClusteringKMeans -> label_cluster_index(): "points" have the wrong size.') [array.new_int(na), array.new_float(na)] else if _size_px != _size_py runtime.error('SignalProcessingClusteringKMeans -> label_cluster_index(): "points" x != y.') [array.new_int(na), array.new_float(na)] else if _size_cx < 1 runtime.error('SignalProcessingClusteringKMeans -> label_cluster_index(): "centers" have the wrong size.') [array.new_int(na), array.new_float(na)] else if _size_cx != _size_cy runtime.error('SignalProcessingClusteringKMeans -> label_cluster_index(): "centers" x != y.') [array.new_int(na), array.new_float(na)] else int[] _group = array.new_int(_size_px) float[] _distance = array.new_float(_size_px) // assign each point the index of its nearest cluster center for _j = 0 to _size_px - 1 [_idx, _d] = nearest(array.get(points_x, _j), array.get(points_y, _j), centers_x, centers_y) array.set(_group, _j, _idx) array.set(_distance, _j, _d) [_group, _distance] //} // @function K-Means++ Clustering adapted from Andy Allinger. // @param points_x float array, x coordinates of the points. // @param points_y float array, y coordinates of the points. // @param n_clusters int, number of clusters. // @returns tuple with 2 arrays, float array, int array. export kpp (float[] points_x, float[] points_y, int n_clusters=3) => //{ int _size_x = array.size(points_x) int _size_y = array.size(points_y) if _size_x < 1 runtime.error('SignalProcessingClusteringKMeans -> kpp_allinger(): "centers" have the wrong size.') [array.new_float(na), array.new_float(na)] else if _size_x != _size_y runtime.error('SignalProcessingClusteringKMeans -> kpp_allinger(): "centers" x != y.') [array.new_float(na), array.new_float(na)] else if n_clusters < 2 runtime.error('SignalProcessingClusteringKMeans -> kpp_allinger(): "n_clusters" must be a positive number > 1.') [array.new_float(na), array.new_float(na)] else float[] _shortest_distances = array.new_float(_size_x, 1.0e307) float[] _cumulative_distances = array.new_float(_size_x, 0.0) float[] _centers_x = array.new_float(n_clusters, 0.0) float[] _centers_y = array.new_float(n_clusters, 0.0) // pick the first centroid at random: int _selected_index = int(math.random() * (_size_x - 1)) array.set(_centers_x, 0, array.get(points_x, _selected_index)) array.set(_centers_y, 0, array.get(points_y, _selected_index)) // select centroid index for _cluster = 1 to n_clusters - 1 // for each point, find the its closest distance to any of the previous centers for _j = 0 to _size_x - 1 float _d = distance2(array.get(points_x, _j), array.get(points_y, _j), array.get(_centers_x, _cluster - 1), array.get(_centers_y, _cluster - 1)) float _sd = array.get(_shortest_distances, _j) if _d < _sd array.set(_shortest_distances, _j, _d) // create a array of cumulative distances float _sum = 0.0 for _j = 0 to _size_x - 1 float _sd = array.get(_shortest_distances, _j) _sum += _sd array.set(_cumulative_distances, _j, _sum) // select point as random, those with greater distances have higher probability of being selected int _rng = int(math.random() * (_size_x - 1)) _selected_index := bisection_search(_cumulative_distances, _rng) // assign selected point as center array.set(_centers_x, _cluster, array.get(points_x, _selected_index)) array.set(_centers_y, _cluster, array.get(points_y, _selected_index)) [_centers_x, _centers_y] //} size = input(20) data_x = array.new_float(size) data_y = array.new_float(size) for _i = 0 to size-1 array.set(data_x, _i, math.floor(math.random() * 500)) array.set(data_y, _i, math.random() * 500) flabel(_x, _y, _t='', _col=color.blue, _size=size.tiny)=>label.new(bar_index+int(_x), 0.0+_y, _t, color=color.new(_col, 20), style=label.style_circle, size=_size) fline(_x1, _y1, _x2, _y2, _col=color.blue)=> line.new(bar_index+int(_x1), 0.0+_y1, bar_index+int(_x2), 0.0+_y2, extend=extend.right, color=_col, style=line.style_dashed, width=2) line.new(bar_index+int(_x1), 0.0+_y1, bar_index+int(_x2), 0.0+_y2, extend=extend.none, color=_col, style=line.style_arrow_right, width=1) clusters = input(3) [kx, ky] = kpp(data_x, data_y, clusters) [kg, kd] = label_points(data_x, data_y, kx, ky) float centerx = array.avg(kx) float centery = array.avg(ky) f_c(_i)=>_a = _i*(255/clusters), color.rgb(255-_a, _a, _a * math.pi % 255, 0) if barstate.islastconfirmedhistory // data points for _i = 0 to size-1 flabel(array.get(data_x, _i), array.get(data_y, _i), _col=f_c(array.get(kg, _i))) // cluster centers for _k = 0 to clusters-1 float _kx = array.get(kx, _k) float _ky = array.get(ky, _k) color _c = f_c(_k) flabel(_kx, _ky, str.tostring(_k), _col=_c, _size=size.huge)
FunctionDatestring
https://www.tradingview.com/script/QdtSGg8b-FunctionDatestring/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
29
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods to stringify date/time, altho there is already builtin support for it. library(title='FunctionDatestring') import RicardoSantos/DebugConsole/1 as console [__T, __C] = console.init(20) // @function check if string has 1 digits and prefixes a "0" if true. prefixdigit (string str) => (str.length(str) == 1 ? '0' : '') + str // @function a stringified date stamp at specified unix time. // @param unixtime int unix timestamp. // @param format string, string format of the returned time, follows same convetions as str.format(), variables(0: year, 1:month, 2:day, 3:hour, 4:minutes, 5:seconds). // @returns string export datetime (int unixtime=timenow, string format='{0}, {1}, {2} - {3}:{4}:{5}') => //{ _year = str.tostring(year(unixtime)) _month = prefixdigit(str.tostring(month(unixtime))) _day = prefixdigit(str.tostring(dayofmonth(unixtime))) _hour = prefixdigit(str.tostring(hour(unixtime))) _min = prefixdigit(str.tostring(minute(unixtime))) _sec = prefixdigit(str.tostring(second(unixtime))) str.format(format, _year, _month, _day, _hour, _min, _sec) //} // @function a stringified date stamp at specified unix time. // @param unixtime int unix timestamp. // @param format string, string format of the returned time, follows same convetions as str.format(), variables(0: year, 1:month, 2:day). // @returns string export date_ (int unixtime=timenow, string format='{0}, {1}, {2}') => //{ _year = str.tostring(year(unixtime)) _month = prefixdigit(str.tostring(month(unixtime))) _day = prefixdigit(str.tostring(dayofmonth(unixtime))) str.format(format, _year, _month, _day) //} // @function a stringified date stamp at specified unix time. // @param unixtime int unix timestamp. // @param format string, string format of the returned time, follows same convetions as str.format(), variables (0:hour, 1:minutes, 2:seconds). // @returns string export time_ (int unixtime=timenow, string format='{0}:{1}:{2}') => //{ _hour = prefixdigit(str.tostring(hour(unixtime))) _min = prefixdigit(str.tostring(minute(unixtime))) _sec = prefixdigit(str.tostring(second(unixtime))) str.format(format, _hour, _min, _sec) //} if barstate.isnew console.queue(__C, str.format('{0} :::: {1}', datetime(time), '@')) if barstate.islastconfirmedhistory console.queue(__C, str.format('{0} :::: {1}', datetime(), 'current datetime!')) console.queue(__C, str.format('{0} :::: {1}', date_(), 'current date!')) console.queue(__C, str.format('{0} :::: {1}', time_(), 'current time!')) console.update(__T, __C)
ColorExtension
https://www.tradingview.com/script/eJkfSXwJ-ColorExtension/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
30
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Extra methods for Color manipulation and profiling. library(title='ColorExtension') // reference: // https://tallys.github.io/color-theory/ // https://www.canva.com/colors/color-wheel/ // https://webdesign.tutsplus.com/tutorials/creating-color-schemes-with-less-color-functions--cms-23668 // @function HSL color transform. // @param hue float, hue color component, hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue. // @param saturation float, saturation color component, saturation is a percentage value, 0 means a shade of gray and 100 is the full color. // @param lightness float, lightness color component, Lightness is also a percentage; 0 is black, 100 is white. // @param transparency float, transparency color component, transparency is also a percentage; 0 is opaque, 100 is transparent. // @returns color export hsl (float hue=0.0, float saturation=0.0, float lightness=0.0, float transparency=0.0) => //{ switch hue < 0.0 or hue > 360.0 => runtime.error(str.format('ColorExtension -> hsl(): "hue" parameter is out of range, expecting 0-360, received: {0}', hue)) saturation < 0.0 or saturation > 100.0 => runtime.error(str.format('ColorExtension -> hsl(): "saturation" parameter is out of range, expecting 0-100, received: {0}', saturation)) lightness < 0.0 or lightness > 100.0 => runtime.error(str.format('ColorExtension -> hsl(): "lightness" parameter is out of range, expecting 0-100, received: {0}', lightness)) transparency < 0.0 or transparency > 100.0 => runtime.error(str.format('ColorExtension -> hsl(): "transparency" parameter is out of range, expecting 0-100, received: {0}', transparency)) float _h_30 = hue / 30.0 float _l1 = lightness * 0.01 float _a = saturation * math.min(_l1, 1.0 - _l1) * 0.01 float _rk = _h_30 % 12.0 float _r = 255.0 * (_l1 - _a * math.max(math.min(_rk - 3.0, 9.0 - _rk, 1.0), -1.0)) float _gk = (8.0 + _h_30) % 12.0 float _g = 255.0 * (_l1 - _a * math.max(math.min(_gk - 3.0, 9.0 - _gk, 1.0), -1.0)) float _bk = (4.0 + _h_30) % 12.0 float _b = 255.0 * (_l1 - _a * math.max(math.min(_bk - 3.0, 9.0 - _bk, 1.0), -1.0)) color.rgb(_r, _g, _b, transparency) //{ usage: // h = input.int(defval=127)//, minval=0, maxval=360) // s = input.int(defval=50)//, minval=0, maxval=100) // l = input.int(defval=50)//, minval=0, maxval=100) // t = input.int(defval=0)//, minval=0, maxval=100) // if barstate.islast // line.new(bar_index, 0., bar_index[1], 0., extend=extend.both, color=hsl(h, s, l, t), width=20) //{ remarks: // https://stackoverflow.com/questions/36721830/convert-hsl-to-rgb-and-hex // Thanks to someguy for code review. //}}} // @function Convert RGB to HSL color values // @param red float, red color component. // @param green float, green color component. // @param blue float, blue color component. // @returns tuple with 3 float values, hue, saturation and lightness. export rgb_to_hsl (float red=0.0, float green=0.0, float blue=0.0) => //{ switch 0 > red or red > 255 => runtime.error(str.format('ColorExtension -> rgb_to_hsl(): "red" parameter is out of range, expecting 0-255, received: {0}', red)) 0 > green or green > 255 => runtime.error(str.format('ColorExtension -> rgb_to_hsl(): "green" parameter is out of range, expecting 0-255, received: {0}', green)) 0 > blue or blue > 255 => runtime.error(str.format('ColorExtension -> rgb_to_hsl(): "blue" parameter is out of range, expecting 0-255, received: {0}', blue)) float _r1 = red / 255.0 float _g1 = green / 255.0 float _b1 = blue / 255.0 float _max_color = math.max(_r1, _g1, _b1) float _min_color = math.min(_r1, _g1, _b1) float _diff = _max_color - _min_color float _H = 0.0 float _S = 0.0 float _L = (_max_color + _min_color) / 2.0 if _max_color != _min_color // saturation calculation: switch (_L <= 0.5) => _S := _diff / (_max_color + _min_color) => _S := _diff / (2.0 - _max_color - _min_color) // hue calculation: switch (_max_color) _r1 => _H := 60.0 * ((_g1 - _b1) / _diff) _g1 => _H := 60.0 * (2.0 + (_b1 - _r1) / _diff) => _H := 60.0 * (4.0 + (_r1 - _g1) / _diff) if _H < 0.0 _H += 360.0 [_H, _S * 100.0, _L * 100.0] //{ usage: // int r = input(0), int g = input(0), int b = input(0) // [th, ts, tl] = rgb_to_hsl(r, g, b) // if barstate.islast // label.new(bar_index, 10., str.format('rgb ({0}, {1}, {2})', r, g, b), color=color.rgb(r, g, b, 0)) // label.new(bar_index, 0., str.format('hsl ({0}, {1}, {2})', th, ts, tl), color=hsl(th, ts, tl, 0)) //{ remarks: // https://gmigdos.wordpress.com/2011/01/13/javascript-convert-rgb-values-to-hsl/ // https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/ //}}} // @function Convert the provided color into HSL values. // @param base color, base color. // @returns tuple with 3 floats. export color_to_hsl (color base) => //{ rgb_to_hsl(color.r(base), color.g(base), color.b(base)) // { usage: // { remarks: //}}} // @function Shift the hue/angle of the provided color. // @param base color, base color. // @param angle float, angle to shift the hue of the base color. // @returns color. export shift_hue (color base, float angle) => //{ [_h, _s, _l] = color_to_hsl(base) hsl((_h + angle) % 360, _s, _l, color.t(base)) // { usage: // color primary = input.color(color.red) // float angle = input.float(45.0) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=shift_hue(primary, angle)) // { remarks: // Thanks to Vlad for bringing it up. //}}} // @function Saturate the provided color by a rate of the difference to its maximum. // @param base color, base color. // @param rate float, default=0.5, rate to saturate the base color (the higher the saturation of the color the less the effect). // @returns color. export saturate (color base, float rate=0.5) => //{ if (rate > 1.0) or (rate < 0.0) runtime.error('ColorExtension -> saturate(): "rate" must be between 0.0 and 1.0') [_h, _s, _l] = color_to_hsl(base) hsl(_h, _s + (100-_s) * rate, _l, color.t(base)) // { usage: // color primary = input.color(color.red) // float rate = input.float(0.50) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=saturate(primary, rate)) // { remarks: //}}} // @function Desaturate the provided color by a rate of the difference to its minimum. // @param base color, base color. // @param rate float, default=0.5, rate to desaturate the base color (the lower the saturation of the color the less the effect). // @returns color. export desaturate (color base, float rate=0.5) => //{ if (rate > 1.0) or (rate < 0.0) runtime.error('ColorExtension -> saturate(): "rate" must be between 0.0 and 1.0') [_h, _s, _l] = color_to_hsl(base) hsl(_h, _s - _s * rate, _l, color.t(base)) // { usage: // color primary = input.color(color.red) // float rate = input.float(0.50) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=desaturate(primary, rate)) // { remarks: //}}} // @function lighten the provided color by a rate of the difference to its maximum. // @param base color, base color. // @param rate float, default=0.5, rate to lighten the base color (the higher the lightness of the color the less the effect). // @returns color. export lighten (color base, float rate=0.5) => //{ if (rate > 1.0) or (rate < 0.0) runtime.error('ColorExtension -> lighten(): "rate" must be between 0.0 and 1.0') [_h, _s, _l] = color_to_hsl(base) hsl(_h, _s, _l + (100.0 - _l) * rate, color.t(base)) // { usage: // color primary = input.color(color.red) // float rate = input.float(0.50) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=lighten(primary, rate)) // { remarks: //}}} // @function darken the provided color by a rate of the difference to its minimum. // @param base color, base color. // @param rate float, default=0.5, rate to darken the base color (the lower the lightness of the color the less the effect). // @returns color. export darken (color base, float rate=0.5) => //{ if (rate > 1.0) or (rate < 0.0) runtime.error('ColorExtension -> darken(): "rate" must be between 0.0 and 1.0') [_h, _s, _l] = color_to_hsl(base) hsl(_h, _s, _l - _l * rate, color.t(base)) // { usage: // color primary = input.color(color.red) // float rate = input.float(0.50) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=darken(primary, rate)) // { remarks: //}}} // @function Complementary of selected color // @param primary color, the primary // @returns color. export complement (color primary) => //{ shift_hue(primary, 180.0) //{ usage: // color primary = input.color(color.red) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=complement(primary)) //{ remarks: //}}} // @function Inverts selected color. // @param primary color, the primary. // @returns color. export invert (color primary) => //{ [_h, _s, _l] = color_to_hsl(primary) hsl((360 + _h + 180.0) % 360.0, 100.0 - _l, _s, color.t(primary)) //{ usage: // color primary = input.color(color.red) // if barstate.islastconfirmedhistory // label.new(bar_index, 10.0, '▆▆▆▆', color=primary, textcolor=complement(primary)) //{ remarks: //}}} // @function Color is cool or warm. // @param base color, the color to check. // @returns bool. export is_cool (color base) => //{ [_h, _, _] = color_to_hsl(base) _h > 120.0 and _h < 300.0 //{ usage: // color primary = input.color(color.red) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str.format('color is {0}.', is_cool(primary) ? 'cool' : 'warm'),color=primary, textcolor=complement(primary)) //{ remarks: //}}} // @function Color temperature. // @param base color, the color to check. // @returns bool. export temperature (color base) => //{ float _r = color.r(base) float _g = color.g(base) float _b = color.b(base) // // convert rgb to tristimulus values: // float _x = (-0.14282 * _r) + (1.54924 * _g) + (-0.95641 * _b) // float _y = (-0.32466 * _r) + (1.57837 * _g) + (-0.73191 * _b) // illuminance // float _z = (-0.68202 * _r) + (0.77073 * _g) + (0.56332 * _b) // float _xyz = _x + _y + _z // // calculate the normalized chromacity values: // float _u = _x / _xyz // float _v = _y / _xyz // // compute CCT value: // float _n = (_u - 0.3320) / (0.1858 - _v) // float _cct = 449.0 * math.pow(_n, 3.0) + 3525.0 * math.pow(_n, 2.0) + 6823.3 * _n + 5520.33 // faster compressed algorithm: float _n = ((0.23881) * _r + (0.25499) * _g + (-0.58291) * _b) / ((0.11109) * _r + (-0.85406) * _g + (0.52289) * _b) 449.0 * math.pow(_n, 3.0) + 3525 * math.pow(_n, 2.0) + 6823.3 * _n + 5520.33 //{ usage: // color primary = input.color(color.red) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str.format('color is {0}, {1}.', is_cool(primary) ? 'cool' : 'warm', temperature(primary)),color=primary, textcolor=complement(primary)) //{ remarks: // https://stackoverflow.com/questions/38876429/how-to-convert-from-rgb-values-to-color-temperature/38889696 // https://dsp.stackexchange.com/questions/8949/how-to-calculate-the-color-temperature-tint-of-the-colors-in-an-image //}}} // @function Color is high key (orange yellow green). // @param base color, the color to check. // @returns bool. export is_high_key (color base) => //{ [_h, _, _] = color_to_hsl(base) _h > 30.0 and _h < 140.0 //{ usage: // color primary = input.color(color.red) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str.format('color is {0}.', is_high_key(primary) ? 'high' : 'low'),color=primary, textcolor=complement(primary)) //{ remarks: //}}} // @function Mix two colors together. // @param base color, the base color. // @param mix color, the color to mix. // @param rate float, default=0.5, the rate of mixture, range within 0.0 and 1.0. // @returns color. export mix (color base, color mix, float rate=0.5) => //{ if rate <= 0.0 or rate >= 1.0 runtime.error('ColorExtension -> mix(): "rate" must be within 0.0 and 1.0') float _t0 = color.t(base) float _t1 = color.t(mix) [_h0, _s0, _l0] = color_to_hsl(base) [_h1, _s1, _l1] = color_to_hsl(mix) hsl(_h0 + (_h1 - _h0) * rate , _s0 + (_s1 - _s0) * rate, _l0 + (_l1 - _l0) * rate, _t0 + (_t1 - _t0) * rate) //{ usage: // color base = input.color(color.red) // color mix_col = input.color(color.red) // float rate = input.float(1.0) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, 'base color.', color=base) // label.new(bar_index+10, 0.0, 'mix color.', color=mix_col) // label.new(bar_index+20, 0.0, 'result.', color=mix(base, mix_col, rate)) //{ remarks: // https://stackoverflow.com/questions/14819058/mixing-two-colors-naturally-in-javascript //}}} // @function Selects 2 near spectrum colors (H +/- 45). // @param primary color, the base color. // @returns tuple with 2 colors. export analog (color primary) => //{ [shift_hue(primary, -45.0), shift_hue(primary, 45.0)] //{ usage: // color base = input.color(color.red) // [min, max] = analog(base) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, 'lower.', color=min) // label.new(bar_index+10, 0.0, 'primary.', color=base) // label.new(bar_index+20, 0.0, 'upper.', color=max) //{ remarks: //}}} // @function Selects 2 far spectrum colors (H +/- 120). // @param primary color, the base color. // @returns tuple with 2 colors. export triadic (color primary) => //{ [shift_hue(primary, -120.0), shift_hue(primary, 120.0)] //{ usage: // color base = input.color(color.red) // [min, max] = triadic(base) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, 'lower.', color=min) // label.new(bar_index+10, 0.0, 'primary.', color=base) // label.new(bar_index+20, 0.0, 'upper.', color=max) //{ remarks: //}}} // @function Uses primary and the complementary color, + 60º to form a rectangular pattern on the color wheel. // @param primary color, the base color. // @returns tuple with 3 colors. export tetradic (color primary) => //{ [shift_hue(primary, 60.0), shift_hue(primary, 180.0), shift_hue(primary, 240.0)] //{ usage: // color base = input.color(color.red) // [comp, min, max] = tetradic(base) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, 'lower.', color=min) // label.new(bar_index+10, 0.0, 'primary.', color=base) // label.new(bar_index+10, 10.0, 'complementary.', color=comp) // label.new(bar_index+20, 0.0, 'upper.', color=max) //{ remarks: //}}} // @function Uses primary and generate 3 equally spaced (90º) colors. // @param primary color, the base color. // @returns tuple with 3 colors. export square (color primary) => //{ [shift_hue(primary, 90.0), shift_hue(primary, 180.0), shift_hue(primary, 270.0)] //{ usage: // color base = input.color(color.red) // [comp, min, max] = square(base) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, 'lower.', color=min) // label.new(bar_index+10, 0.0, 'primary.', color=base) // label.new(bar_index+10, 10.0, 'complementary.', color=comp) // label.new(bar_index+20, 0.0, 'upper.', color=max) //{ remarks: //}}} // @function Pick color at value in a triangular gradient // @param value float, value to pick the color in the gradient. // @param mid_point float, percent at wich the triangular pattern peaks. // @param min_color color, lowest color in the gradient. // @param mid_color color, peak color in the gradient. // @param max_color color, highest color in the gradient. // @returns color gradient_triangular(float value=0.0, float mid_point=50.0, color min_color=color.black, color mid_color=color.white, color max_color=color.black) => //{ // @function: finds the color output of a triangular gradient color _col = na if value <= mid_point _col := color.from_gradient(value, 0.0, mid_point, min_color, mid_color) _col else _col := color.from_gradient(value, mid_point, 100.0, mid_color, max_color) _col _col //{ usage: // r1 = ta.rsi(close, 3) // c1 = gradient_triangular(r1, 20, color.red, color.yellow, color.lime) // c2 = gradient_triangular(r1, 50, color.red, color.yellow, color.lime) // c3 = gradient_triangular(r1, 80, color.red, color.yellow, color.lime) // plot(r1, color=c1, linewidth=15) // plot(r1, color=c2, linewidth=10) // plot(r1, color=c3, linewidth=5) //{ remarks: //}}}
HarmonicPattern
https://www.tradingview.com/script/12FErxAl-HarmonicPattern/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
75
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Functions to detect/check harmonic patterns from provided values. library("HarmonicPattern") // @function Compute the price rate of the line AB divided by the the line BC // @param point_c float, the price at point C. // @param point_b float, the price at point B. // @param point_a float, the price at point A. // @returns float export line_price_rate (float point_c, float point_b, float point_a) => //{ // C A // \ / // B (point_a - point_b) / (point_b - point_c) //} // @function Compute the time rate of the line AB divided by the the line BC // @param _c float, the time or bar_index at point C. // @param _b float, the time or bar_index at point B. // @param _a float, the time or bar_index at point A. // @returns float export line_time_rate (float point_c, float point_b, float point_a) => //{ // C A // \ / // B (0 - (point_a - point_b)) / (point_b - point_c) //} // @function Check if value is within min/max range of tolerance. // @param value float, value to check tolerance. // @param target float, min value to check range of tolerance. // @param target float, max value to check range of tolerance. // @param margin_of_error float, margin of error to validate range. // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is_inrange (float value, float min, float max, float margin_of_error=0.05, string calculation_type="additive") => //{ switch (calculation_type == 'additive') => (value <= (max + margin_of_error)) and (value >= (min - margin_of_error)) (calculation_type == 'multiplicative') => (value <= (max * (1.0 + margin_of_error))) and (value >= (min * (1.0 - margin_of_error))) => runtime.error('HarmonicPattern -> is_inrange(): undefined margin calcultion type.'), bool(na) //} //|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // rates are expected in a backwards manner and of negative value. || //|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // G E C A || // \ / \ / \ / || // F D B || //|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // @function Check if the rate(s) correspond to pattern ("Harmonic Triangle"). // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isHarmonicTriangle (float rate_cba, float margin_of_error=0.05, string calculation_type="additive") => //{ bool _return = false // return true if its rate is near a harmonic rate: // this is analogous with the fibonnaci sequence, but is capped at (-5 --> 12) to limit resource usage // 0.146, 0.236, 0.382, 0.618, 1, 1.618, 2.618, 4.236, 6.854, 11.089, 17.942, 29.03 for _i = 1 to 12 // calculate the derivative of phi sequence: float _phid = 0 - math.pow(math.phi, -5.0 + _i) if is_inrange(rate_cba, _phid, _phid, margin_of_error, calculation_type) _return := true break _return //} // @function Check if the rate(s) correspond to pattern ("2Tap", 'Double Top / Bottom'). // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is2Tap (float rate_cba, float margin_of_error=0.05, string calculation_type="additive") => //{ is_inrange(rate_cba, -1.000, -1.000, margin_of_error, calculation_type) //} // @function Check if the rate(s) correspond to pattern ("3Tap", "Triple Top / Bottom"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is3Tap (float rate_edc, float rate_cba, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -1.000, -1.000, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -1.000, -1.000, margin_of_error, calculation_type) _is_edc and _is_cba //} // @function Check if the rate(s) correspond to pattern ("4Tap", "Quadruple Top / Bottom"). // @param rate_gfe float, percent rate of the triangle GFE. expects a negative rate. // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is4Tap (float rate_gfe, float rate_edc, float rate_cba, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_gfe = is_inrange(rate_gfe, -1.000, -1.000, margin_of_error, calculation_type) _is_edc = is_inrange(rate_edc, -1.000, -1.000, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -1.000, -1.000, margin_of_error, calculation_type) _is_gfe and _is_edc and _is_cba //} // @function Check if the rate(s) correspond to pattern ("AB=CD"). // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isABCD (float rate_cba, float rate_dcb, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_cba = is_inrange(rate_cba, -1.618, -1.270, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.786, -0.618, margin_of_error, calculation_type) _is_cba and _is_dcb //} // @function Check if the rate(s) correspond to pattern ("Bat"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isBat (float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.500, -0.382, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.886, -0.382, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -2.618, -1.618, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -0.886, -0.886, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Butterfly"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isButterfly (float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.786, -0.786, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.886, -0.382, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -2.618, -1.618, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -1.618, -1.270, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Gartley"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isGartley (float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.618, -0.618, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.886, -0.382, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -2.618, -1.130, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -0.786, -0.786, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Crab"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isCrab (float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.886, -0.886, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.886, -0.382, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -3.618, -2.000, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -1.618, -1.618, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Shark"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isShark(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.886, -0.886, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -1.618, -1.130, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -2.240, -1.270, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -1.130, -0.886, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("5o"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is5o(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -1.618, -1.130, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -2.240, -1.618, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -0.500, -0.500, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -0.236, +0.236, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Wolfe"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isWolfe(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -1.618, -1.270, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -5.000, -0.000, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -1.618, -1.270, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -5.000, -0.000, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("3 Driver"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export is3Driver(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -1.618, -1.270, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -5.000, -0.000, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -1.618, -1.270, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -5.000, -0.000, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Contracting Triangle"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isConTria(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -0.886, -0.236, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -0.886, -0.236, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -0.886, -0.236, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -0.886, -0.236, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Expanding Triangle"). // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isExpTria(float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_edc = is_inrange(rate_edc, -2.618, -1.125, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -2.618, -1.125, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -2.618, -1.125, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -2.618, -1.125, margin_of_error, calculation_type) _is_edc and _is_dcb and _is_cba and _is_eda //} // @function Check if the rate(s) correspond to pattern ("Head and Shoulders"). // @param rate_fed float, percent rate of the triangle FED. expects a negative rate. // @param rate_feb float, percent rate of the triangle FEB. expects a negative rate. // @param rate_edc float, percent rate of the triangle EDC. expects a negative rate. // @param rate_dcb float, percent rate of the triangle DCB. expects a negative rate. // @param rate_cba float, percent rate of the triangle CBA. expects a negative rate. // @param rate_eda float, percent rate of the triangle EDA. expects a negative rate. // @param margin_of_error float, percent rate of expected error margin, default 0.05(5%). // @param calculation_type string, default='additive', options=['additive', 'multiplicative'], type of margin of error. // @returns bool export isHnS(float rate_fed, float rate_feb, float rate_edc, float rate_dcb, float rate_cba, float rate_eda, float margin_of_error=0.05, string calculation_type="additive") => //{ _is_fed = is_inrange(rate_fed, -0.618, -0.090, margin_of_error, calculation_type) _is_feb = is_inrange(rate_feb, -0.886, -0.090, margin_of_error, calculation_type) _is_edc = is_inrange(rate_edc, -9.999, -1.000, margin_of_error, calculation_type) _is_dcb = is_inrange(rate_dcb, -1.250, -0.750, margin_of_error, calculation_type) _is_cba = is_inrange(rate_cba, -0.886, -0.090, margin_of_error, calculation_type) _is_eda = is_inrange(rate_eda, -1.618, -0.090, margin_of_error, calculation_type) _is_fed and _is_feb and _is_edc and _is_eda and _is_dcb and _is_cba //} // @function Extract the available patterns from zigzag prices. // @returns string array. export extract (float price_g, float price_f, float price_e, float price_d, float price_c, float price_b, float price_a, float margin_of_error) => //{ // triangulate pivots into rates: // note: // • pattern rates should be negative // • if rate is positive center is inside the edges. float price_gfc = line_price_rate(price_g, price_f, price_c) float price_gfa = line_price_rate(price_g, price_f, price_a) float price_gdc = line_price_rate(price_g, price_d, price_c) float price_gda = line_price_rate(price_g, price_d, price_a) float price_gfe = line_price_rate(price_g, price_f, price_e) float price_gba = line_price_rate(price_g, price_b, price_a) float price_fed = line_price_rate(price_f, price_e, price_d) float price_feb = line_price_rate(price_f, price_e, price_b) float price_fcb = line_price_rate(price_f, price_c, price_b) float price_edc = line_price_rate(price_e, price_d, price_c) float price_eda = line_price_rate(price_e, price_d, price_a) float price_eba = line_price_rate(price_e, price_b, price_a) float price_dcb = line_price_rate(price_d, price_c, price_b) float price_cba = line_price_rate(price_c, price_b, price_a) bool _isvalid_gfa = price_fed >= -1 and price_feb >= -1 and price_cba <= -1 and price_eda <= -1 bool _isvalid_gda = price_fed <= -1 and price_gfe >= -1 and price_cba <= -1 and price_dcb >= -1 bool _isvalid_gba = price_feb <= -1 and price_gfe >= -1 and price_cba <= -1 and price_dcb <= -1 bool _isvalid_eba = price_cba <= -1 and price_dcb <= -1 bool _isvalid_eda = price_cba <= -1 and price_dcb >= -1 bool _isvalid_fcb = price_fed >= -1 and price_edc <= -1 bool _isvalid_feb = price_edc >= -1 and price_dcb <= -1 string[] _pattern_list = array.new_string(0) // Check if its a harmonic triangle: if isHarmonicTriangle(price_gfa, margin_of_error) and _isvalid_gfa array.push(_pattern_list, "• Harmonic Triangle(GFA) •") if isHarmonicTriangle(price_gda, margin_of_error) and _isvalid_gda array.push(_pattern_list, "• Harmonic Triangle(GDA) •") if isHarmonicTriangle(price_gba, margin_of_error) and _isvalid_gba array.push(_pattern_list, "• Harmonic Triangle(GBA) •") if isHarmonicTriangle(price_eba, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Harmonic Triangle(EBA) •") if isHarmonicTriangle(price_eda, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Harmonic Triangle(EDA) •") if isHarmonicTriangle(price_cba, margin_of_error) array.push(_pattern_list, "• Harmonic Triangle(CBA) •") // Check if its Double Tap if is2Tap(price_cba, margin_of_error) array.push(_pattern_list, "• Double Tap(CBA) •") if is2Tap(price_eba, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Double Tap(EBA) •") if is2Tap(price_eda, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Double Tap(EDA) •") // Check if its Triple Tap if is3Tap(price_edc, price_cba, margin_of_error) array.push(_pattern_list, "• Triple Tap(EDC, CBA) •") // Check if its Quadruple Tap if is4Tap(price_gfe, price_edc, price_cba, margin_of_error) array.push(_pattern_list, "• Quadruple Tap(GFE, EDC, CBA) •") // check if its AB=CD if isABCD(price_cba, price_dcb, margin_of_error) array.push(_pattern_list, "• AB=CD(CBA, DCB) •") if isABCD(price_cba, price_fcb, margin_of_error) and _isvalid_fcb array.push(_pattern_list, "• AB=CD(CBA, FCB) •") if isABCD(price_eba, price_feb, margin_of_error) and _isvalid_feb array.push(_pattern_list, "• AB=CD(EBA, FEB) •") if isABCD(price_eda, price_fed, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• AB=CD(EDA, FED) •") // check if its BAT: if isBat(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Bat(EDC, DCB, CBA, EDA) •") if isBat(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Bat(GFE, FEB, EBA, GFA) •") if isBat(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Bat(GFE, FED, EDA, GFA) •") // check if its BUTTERFLY if isButterfly(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Butterfly(EDC, DCB, CBA, EDA) •") if isButterfly(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Butterfly(GFE, FEB, EBA, GFA) •") if isButterfly(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Butterfly(GFE, FED, EDA, GFA) •") // check if its GARTLEY if isGartley(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Gartley(EDC, DCB, CBA, EDA) •") if isGartley(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Gartley(GFE, FEB, EBA, GFA) •") if isGartley(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Gartley(GFE, FED, EDA, GFA) •") // check if its CRAB if isCrab(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Crab(EDC, DCB, CBA, EDA) •") if isCrab(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Crab(GFE, FEB, EBA, GFA) •") if isCrab(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Crab(GFE, FED, EDA, GFA) •") // check if its SHARK if isShark(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Shark(EDC, DCB, CBA, EDA) •") if isShark(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Shark(GFE, FEB, EBA, GFA) •") if isShark(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Shark(GFE, FED, EDA, GFA) •") // check if its 5o if is5o(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• 5o(EDC, DCB, CBA, EDA) •") if is5o(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• 5o(GFE, FEB, EBA, GFA) •") if is5o(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• 5o(GFE, FED, EDA, GFA) •") // check if its WOLF if isWolfe(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Wolf(EDC, DCB, CBA, EDA) •") if isWolfe(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Wolf(GFE, FEB, EBA, GFA) •") if isWolfe(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Wolf(GFE, FED, EDA, GFA) •") // check if its Contracting Triangle if isConTria(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Contracting Triangle(EDC, DCB, CBA, EDA) •") if isConTria(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Contracting Triangle(GFE, FEB, EBA, GFA) •") if isConTria(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Contracting Triangle(GFE, FED, EDA, GFA) •") // check if its Expanding Triangle if isExpTria(price_edc, price_dcb, price_cba, price_eda, margin_of_error) array.push(_pattern_list, "• Expanding Triangle(EDC, DCB, CBA, EDA) •") if isExpTria(price_gfe, price_feb, price_eba, price_gfa, margin_of_error) and _isvalid_eba array.push(_pattern_list, "• Expanding Triangle(GFE, FEB, EBA, GFA) •") if isExpTria(price_gfe, price_fed, price_eda, price_gfa, margin_of_error) and _isvalid_eda array.push(_pattern_list, "• Expanding Triangle(GFE, FED, EDA, GFA) •") // check if its Head and Shoulders if isHnS(price_fed, price_feb, price_dcb, price_edc, price_eda, price_cba, margin_of_error) array.push(_pattern_list, "• Head and Shoulders(FED, FEB, DCB, EDC, EDA, CBA) •") _pattern_list //}
Vector2Operations
https://www.tradingview.com/script/F3Hvmt8h-Vector2Operations/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
53
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description functions to handle vector2 operations. library(title='Vector2Operations') // references: // https://docs.unity3d.com/ScriptReference/Vector2.html // https://gist.github.com/winduptoy/a1aa09c3499e09edbd33 // https://github.com/dogancoruh/Javascript-Vector2/blob/master/js/vector2.js // https://gist.github.com/Dalimil/3daf2a0c531d7d030deb37a7bfeff454 // https://gist.github.com/jeantimex/7fa22744e0c45e5df770b532f696af2d // https://gist.github.com/volkansalma/2972237 // Helper Methods:{-----------------------------------------------------------|| import RicardoSantos/DebugConsole/6 as console [__T, __C] = console.init(25) table.set_position(__T, position.bottom_left) table.cell_set_width(__T, 0, 0, 50) // @function computes the fractional part of the argument value. // @param _value float, value to compute. // @returns float, fractional part. export math_fractional (float _value) => //{<< _value - math.floor(_value) //} // @function Approximation to atan2 calculation, arc tangent of y/ x in the range [-pi,pi] radians. // @param _a vector2 in the form of a array [x, y]. // @returns float, value with angle in radians. (negative if quadrante 3 or 4) export atan2 (float[] _a) => //{<< float _x = array.get(id=_a, index=0), float _y = array.get(id=_a, index=1) float _one_qtr_pi = math.pi / 4.0 float _three_qtr_pi = 3.0 * _one_qtr_pi float _abs_y = math.abs(_y) + 1e-12 // kludge to void zero division float _r = 0.0, float _angle = 0.0 if _x < 0.0 _r := (_x + _abs_y) / (_abs_y - _x) _angle := _three_qtr_pi else _r := (_x - _abs_y) / (_x + _abs_y) _angle := _one_qtr_pi _angle := _angle + (0.1963 * _r * _r - 0.9817) * _r _y < 0.0 ? -_angle : _angle //} //|--------------------}-------------------------------------------------------|| //| Properties:{---------------------------------------------------------------|| // @function Set the x value of vector _a. // @param _a vector2 in the form of a array [x, y]. // @param _value value to replace x value of _a. // @returns void Modifies vector _a. export set_x (float[] _a, float _value) => //{<< array.set(id=_a, index=0, value=_value) //} // @function Set the y value of vector _a. // @param _a vector in the form of a array [x, y]. // @param _value value to replace y value of _a. // @returns void Modifies vector _a. export set_y (float[] _a, float _value)=>//{<< array.set(id=_a, index=1, value=_value) //} // @function Get the x value of vector _a. // @param _a vector in the form of a array [x, y]. // @returns float, x value of the vector _a. export get_x (float[] _a) => //{<< array.get(id=_a, index=0) //} // @function Get the y value of vector _a. // @param _a vector in the form of a array [x, y]. // @returns float, y value of the vector _a. export get_y(float[] _a)=>//{<< array.get(id=_a, index=1) //} // @function Return the tuple of vector _a in the form [x, y] // @param _a vector2 in the form of a array [x, y]. // @returns [float, float] export get_xy(float[] _a)=>//{<< [get_x(_a), get_y(_a)] //} // @function Length of vector _a in the form. [pow(_a, 2)], for comparing vectors this is computationaly lighter. // @param _a vector in the form of a array [x, y]. // @returns float, squared length of vector. export length_squared(float[] _a)=>//{<< float _x = get_x(_a) float _y = get_y(_a) (_x * _x) + (_y * _y) //} // @function Magnitude of vector _a in the form. [sqrt(pow(_a, 2))] // @param _a vector in the form of a array [x, y]. // @returns float, Squared length of vector. export length(float[] _a)=>//{<< math.sqrt(length_squared(_a)) //} // @function Lowest element of vector. // @param _a vector in the form of a array [x, y]. // @returns float export vmin(float[] _a)=>//{<< math.min(get_x(_a), get_y(_a)) //} // @function Highest element of vector. // @param _a vector in the form of a array [x, y]. // @returns float export vmax(float[] _a)=>//{<< math.max(get_x(_a), get_y(_a)) //} // //|----------------}-----------------------------------------------------------|| // //| Constructor {-------------------------------------------------------------|| // @function Assigns value to a new vector x,y elements. // @param _value x and y value of the vector. optional. // @returns float[x, y] vector. export from(float _value = 0.0)=>//{<< array.new_float(size=2, initial_value=_value) //} // @function Creates a prototype array to handle vectors. // @param _x float, x value of the vector. optional. // @param _y float, y number of the vector. optional. // @returns float[x, y] vector. export new(float _x = 0.0, float _y=0.0)=>//{<< float[] _vector = array.new_float(size=2, initial_value=0.0) set_x(_vector, _x) set_y(_vector, _y) _vector //} // @function Vector in the form [0, -1]. // @returns float[x, y] vector. export down()=>//{<< new(0.0, -1.0) //} // @function Vector in the form [-1, 0]. // @returns float[x, y] vector. export left()=>//{<< new(-1.0, 0.0) //} // @function Vector in the form [1, 1]. // @returns float[x, y] vector. export one()=>//{<< from(1.0) //} // @function Vector in the form [1, 0]. // @returns float[x, y] vector export right()=>//{<< new(1.0, 0.0) //} // @function Vector in the form [0, 1]. // @returns float[x, y] vector export up()=>//{<< new(0.0, 1.0) //} // @function Vector in the form [0, 0]. // @returns float[x, y] vector export zero()=>//{<< from(0.0) //} //|------------------}---------------------------------------------------------|| // //| Operator Methods {--------------------------------------------------------|| // @function Adds vector _b to _a, in the form // [_a.x + _b.x, _a.y + _b.y]. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns export add(float[] _a, float[] _b)=>//{<< new(get_x(_a) + get_x(_b), get_y(_a) + get_y(_b)) //} // @function Subtract vector _b from _a, in the form // [_a.x - _b.x, _a.y - _b.y]. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns export subtract(float[] _a, float[] _b)=>//{<< new(get_x(_a) - get_x(_b), get_y(_a) - get_y(_b)) //} // @function Multiply vector _a with _b, in the form // [(_a.x * _b.x), (_a.y * _b.y)] // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns export multiply(float[] _a, float[] _b)=>//{<< new(get_x(_a) * get_x(_b), get_y(_a) * get_y(_b)) //} // @function Divide vector _a with _b, in the form // [(_a.x / _b.x), (_a.y / _b.y)] // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns export divide(float[] _a, float[] _b)=>//{<< new(get_x(_a) / get_x(_b), get_y(_a) / get_y(_b)) //} // @function Negative of vector _a, in the form [-_a.x, -_a.y] // @param _a vector in the form of a array [x, y]. // @returns export negate(float[] _a)=>//{<< subtract(zero(), _a) //} // @function Perpendicular Vector of _a. // @param _a vector in the form of a array [x, y]. // @returns export perp(float[] _a)=>//{<< new(get_y(_a), -get_x(_a)) //} // @function Compute the floor of argument vector _a. // @param _a vector in the form of a array [x, y]. // @returns export vfloor(float[] _a)=>//{<< new(math.floor(get_x(_a)), math.floor(get_y(_a))) //} // @function Compute the fractional part of the elements from vector _a. // @param _a vector in the form of a array [x, y]. // @returns export fractional(float[] _a)=>//{<< new(math_fractional(get_x(_a)), math_fractional(get_y(_a))) //} // @function Compute the sine of argument vector _a. // @param _a vector in the form of a array [x, y]. // @returns export vsin(float[] _a)=>//{<< new(math.sin(get_x(_a)), math.sin(get_y(_a))) //} // @function Compares two vectors // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns boolean value representing the equality. export equals(float[] _a, float[] _b)=>//{<< get_x(_a) == get_x(_b) and get_y(_a) == get_y(_b) //} // @function Dot product of 2 vectors, in the form [_a.x * _b.x + _a.y * _b.y] // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float export dot(float[] _a, float[] _b)=>//{<< (get_x(_a) * get_x(_b)) + (get_y(_a) * get_y(_b)) //} // @function cross product of 2 vectors, in the form [_a.x * _b.y - _a.y * _b.x] // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float export cross_product(float[] _a, float[] _b)=>//{<< (get_x(_a) * get_y(_b)) - (get_y(_a) * get_x(_b)) //} // @function Multiply a vector by a scalar. // @param _a vector in the form of a array [x, y]. // @param _scalar value to multiply vector elements by. // @returns float[x, y] vector export scale(float[] _a, float _scalar)=>//{<< new(get_x(_a) * _scalar, get_y(_a) * _scalar) //} //|-----------------------}----------------------------------------------------|| // //| Methods {-----------------------------------------------------------------|| // @function Vector _a normalized with a magnitude of 1, in the form. [_a / length(_a)] // @param _a vector in the form of a array [x, y]. // @returns float[x, y] vector export normalize(float[] _a)=>//{<< float _length = length(_a) divide(_a, from(_length)) //} // @function Rescale a vector to a new Magnitude. // @param _a vector in the form of a array [x, y]. // @returns export rescale(float[] _a, float _length)=>//{<< float _scalar = _length / length(_a) scale(_a, _scalar) //} // @function Rotates vector _a by angle value // @param _a vector in the form of a array [x, y]. // @param _radians Angle value. // @returns export rotate(float[] _a, float _radians)=>//{<< [_x, _y] = get_xy(_a) float _cos = math.cos(_radians) float _sin = math.sin(_radians) new((_x * _cos) - (_y * _sin), (_x * _sin) + (_y * _cos)) //} // @function Rotates vector _a by angle value // @param _a vector in the form of a array [x, y]. // @param _degree Angle value. // @returns export rotate_degree(float[] _a, float _degree)=>//{<< rotate(_a, math.toradians(_degree)) //} // @function Rotates vector _target around _origin by angle value // @param _center vector in the form of a array [x, y]. // @param _target vector in the form of a array [x, y]. // @param _degree Angle value. // @returns export rotate_around(float[] _center, float[] _target, float _degree)=>//{<< add(_center, rotate(subtract(_target, _center), math.toradians(_degree))) //} // @function Ceils vector _a // @param _a vector in the form of a array [x, y]. // @param _digits digits to use as ceiling. // @returns export vceil(float[] _a, int _digits)=>//{<< float _places = math.pow(10, _digits) new(math.ceil(get_x(_a) * _places) / _places, math.ceil(get_y(_a) * _places) / _places) //} // @function Raise both vector elements by a exponent. // @param _a vector in the form of a array [x, y]. // @returns export vpow(float[] _a, float _exponent)=>//{<< new(math.pow(get_x(_a), _exponent), math.pow(get_y(_a), _exponent)) //} // @function vector distance between 2 vectors. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float, distance. export distance(float[] _a, float[] _b)=>//{<< length(subtract(_a, _b)) //} // @function Distance from point _a to line between _b and _c. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @param _c vector in the form of a array [x, y]. // @returns float export perpendicular_distance (float[] _a, float[] _b, float[] _c) => //{ float[] _d = subtract(_c, _b) math.abs(cross_product(_a, _d) + cross_product(_c, _b)) / length(_d) //} // @function Project a vector onto another. // @param _a vector in the form of a array [x, y]. // @param _axis float[x, y] vector2 // @returns float[x, y] vector export project(float[] _a, float[] _axis)=>//{<< float _t = dot(_a, _axis) / length_squared(_axis) multiply(new(_t, _t), _axis) //} // @function Project a vector onto a vector of unit length. // @param _a vector in the form of a array [x, y]. // @param _axis vector in the form of a array [x, y]. // @returns float[x, y] vector export projectN(float[] _a, float[] _axis)=>//{<< float _t = dot(_a, _axis) multiply(new(_t, _t), _axis) //} // @function Reflect a vector on another. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float[x, y] vector export reflect(float[] _a, float[] _axis)=>//{<< subtract(multiply(project(_a, _axis), new(2.0, 2.0)), _a) //} // @function Reflect a vector to a arbitrary axis. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float[x, y] vector export reflectN(float[] _a, float[] _axis)=>//{<< subtract(multiply(projectN(_a, _axis), new(2.0, 2.0)), _a) //} // @function Angle in radians of a vector. // @param _a vector in the form of a array [x, y]. // @returns float export angle(float[] _a)=>//{<< -atan2(new(-get_y(_a), get_x(_a))) //} // @function unsigned degree angle between 0 and +180 by given two vectors. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float export angle_unsigned(float[] _a, float[] _b)=>//{<< math.todegrees(math.acos(dot(normalize(_a), normalize(_b)))) //} // @function Signed degree angle between -180 and +180 by given two vectors. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float export angle_signed(float[] _a, float[] _b)=>//{<< float[] _na = normalize(_a) float[] _nb = normalize(_b) math.todegrees(math.acos(dot(_na, _nb))) * (cross_product(_na, _nb) >= 0 ? 1.0 : -1.0) //} // @function Degree angle between 0 and 360 by given two vectors // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @returns float export angle_360(float[] _a, float[] _b)=>//{<< float[] _na = normalize(_a) float[] _nb = normalize(_b) float _degree = math.todegrees(math.acos(dot(_na, _nb))) cross_product(_na, _nb) > 0.0 ? _degree : 360.0 - _degree //} // @function Restricts a vector between a min and max value. // @param _a vector in the form of a array [x, y]. // @param _vmin vector in the form of a array [x, y]. // @param _vmax vector in the form of a array [x, y]. // @returns float[x, y] vector export clamp(float[] _a, float[] _vmin, float[] _vmax)=>//{<< float _x = math.max(math.min(get_x(_a), get_x(_vmax)), get_x(_vmin)) float _y = math.max(math.min(get_y(_a), get_y(_vmax)), get_y(_vmin)) new(_x, _y) //} // @function Linearly interpolates between vectors a and b by _rate_of_move. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @param _rate_of_move float value between (a:-infinity -> b:1.0), negative values will move away from b. // @returns vector in the form of a array [x, y] export lerp(float[] _a, float[] _b, float _rate_of_move)=>//{<< float _t = math.min(_rate_of_move, 1.0) add(_a, scale(subtract(_b, _a), _t)) //} // @function Hermite curve interpolation between vectors a and b by _rate_of_move. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @param _rate_of_move float value between (a-infinity -> b1.0), negative values will move away from b. // @returns vector in the form of a array [x, y] export herp(float[] _a, float[] _b, float[] _rate_of_move)=>//{<< _t = clamp(divide(subtract(_rate_of_move, _a), subtract(_b, _a)), zero(), one()) multiply(multiply(_t, _t), subtract(from(3.0), multiply(from(2.0), _t))) //} // @function Find the area in a triangle of vectors. // @param _a vector in the form of a array [x, y]. // @param _b vector in the form of a array [x, y]. // @param _c vector in the form of a array [x, y]. // @returns float export area_triangle(float[] _a, float[] _b, float[] _c)=>//{<< math.abs(0.5 * ((get_x(_a) - get_x(_c)) * (get_y(_b) - get_y(_a)) - (get_x(_a) - get_x(_b)) * (get_y(_c) - get_y(_a)))) //} // @function Converts vector _a to a string format, in the form "(x, y)" // @param _a vector in the form of a array [x, y]. // @returns string in "(x, y)" format export to_string(float[] _a)=>//{<< '(' + str.tostring(get_x(_a)) + ', ' + str.tostring(get_y(_a)) + ')' //} // @function 2D random value // @param _max float[x, y] vector, vector upper bound // @returns vector in the form of a array [x, y] export vrandom(float[] _max)=>//{<< new(math.random(0.0, get_x(_max)), math.random(0.0, get_y(_max))) //} // @function 2D Noise based on Morgan McGuire @morgan3d // https://thebookofshaders.com/11/ // https://www.shadertoy.com/view/4dS3Wd // @param _a vector in the form of a array [x, y]. // @returns vector in the form of a array [x, y] export noise(float[] _v)=>//{<< _i = vfloor(_v) _f = fractional(_v) // compute the 4 cornes of a tile in 2D _a = vrandom(_i) _b = vrandom(add(_i, right())) _c = vrandom(add(_i, up())) _d = vrandom(add(_i, one())) // Smooth Interpolation // Cubic Hermine Curve. Same as SmoothStep() or vector2_herp() // _u = multiply(multiply(_f, _f), subtract(from(3.0), multiply(from(2.0), _f))) _u = herp(zero(), one(), _f) // Mix 4 coorners percentages // mix() same as vector2_lerp() //mix(a, b, u.x) + (c - a)* u.y * (1.0 - u.x) + (d - b) * u.x * u.y _ux = get_x(_u) _uy = get_y(_u) _mix0 = lerp(_a, _b, _ux) _mix1 = multiply(multiply(subtract(_c, _a), from(_uy)), subtract(one(), from(_ux))) _mix2 = multiply(subtract(_d, _b), _u)//multiply(from(_ux), from(_uy))) add(add(_mix0, _mix1), _mix2) //} //|----------}-----------------------------------------------------------------|| //| Array Methods: {-----------------------------------------------------------|| // @function Prototype to initialize a array of vectors. // @param _size size of the array. // @param _initial_vector vector to be used as default value, in the form of array [x, y]. // @returns _vector_array complex Array in the form of a array [0:x, 1:y, 2:x, 3:y,...] export array_new(int _size = 0, float[] _initial_vector) => //{<< [_init_x, _init_y] = get_xy(_initial_vector) float[] _vector_array = array.new_float(0) if _size > 0 for _i = 0 to _size-1 array.push(id=_vector_array, value=_init_x) array.push(id=_vector_array, value=_init_y) _vector_array //} // @function number of [x, y] vector elements in array. // @param _id ID of the array. // @returns int export array_size(float[] _id)=>//{<< math.round(array.size(_id) / 2) //} // @function Get the vector in a array, in the form of a array [x, y] // @param _id ID of the array. // @param _index Index of the vector. // @returns vector in the form of a array [x, y] export array_get(float[] _id, int _index)=>//{<< float[] _vector = array.new_float(size=2, initial_value=0.0) int _size = array_size(_id) int _index2 = _index * 2 if _index > -1 and _index < _size set_x(_vector, array.get(id=_id, index=_index2)) set_y(_vector, array.get(id=_id, index=_index2 + 1)) _vector //} // @function Sets the values vector in a array. // @param _id ID of the array. // @param _index Index of the vector. // @param _a vector, in the form [x, y]. // @returns Void, updates array _id. export array_set(float[] _id, int _index, float[] _a)=>//{<< float _a_x = get_x(_a) float _a_y = get_y(_a) int _size = array.size(id=_id)-1 int _index2 = _index * 2 if _index > -1 and _index2 < _size array.set(id=_id, index=_index2, value=_a_x) array.set(id=_id, index=_index2 + 1, value=_a_y) //} // @function inserts the vector at the end of array. // @param _id ID of the array. // @param _a vector, in the form [x, y]. // @returns Void, updates array _id. export array_push(float[] _id, float[] _a)=>//{<< array.push(id=_id, value=get_x(_a)) array.push(id=_id, value=get_y(_a)) //} // @function inserts the vector at the begining of array. // @param _id ID of the array. // @param _a vector, in the form [x, y]. // @returns Void, updates array _id. export array_unshift(float[] _id, float[] _a)=>//{<< array.unshift(id=_id, value=get_x(_a)) array.unshift(id=_id, value=get_y(_a)) //} // @function removes the last vector of array and returns it. // @param _id ID of the array. // @param _a vector, in the form [x, y]. // @returns vector2, updates array _id. export array_pop(float[] _id)=>//{<< float _y = array.pop(id=_id) float _x = array.pop(id=_id) new(_x, _y) //} // @function removes the first vector of array and returns it. // @param _id ID of the array. // @param _a vector, in the form [x, y]. // @returns vector2, updates array _id. export array_shift(float[] _id)=>//{<< float _x = array.shift(id=_id) float _y = array.shift(id=_id) new(_x, _y) //} // @function Total sum of all vectors. // @param _id ID of the array. // @returns vector in the form of a array [x, y] export array_sum(float[] _id)=>//{<< float[] _vector = zero() int _size = array_size(_id) if _size > 0 for _i = 0 to _size-1 _vector := add(_vector, array_get(_id, _i)) _vector //} // @function Finds the vector center of the array. // @param _id ID of the array. // @returns vector in the form of a array [x, y] export array_center(float[] _id)=>//{<< int _size = array_size(_id) divide(array_sum(_id), from(_size)) //} // @function Rotate Array vectors around origin vector by a angle. // @param _id ID of the array. // @returns rotated points array. export array_rotate_points(float[] _id, float[] _center, float _degree)=>//{<< float[] _vectors = array_new(0, from(0.0)) int _size = array_size(_id) for _i = 0 to _size-1 array_push(_vectors, rotate_around(_center, array_get(_id, _i), _degree)) _vectors //} // @function Scale Array vectors based on a origin vector perspective. // @param _id ID of the array. // @returns rotated points array. export array_scale_points(float[] _id, float[] _center, float _rate)=>//{<< float[] _vectors = array_new(0, from(0.0)) int _size = array_size(_id) for _i = 0 to _size-1 float[] _oldvector = array_get(_id, _i) float[] _newvector = add(_center, scale(subtract(_oldvector, _center), 1+_rate)) array_push(_vectors, _newvector) _vectors //} // @function Reads a array of vectors into a string, of the form "[ (x, y), ... ]"" // @param _id ID of the array. // @param _separator string separator for cell splitting. // @returns string Translated complex array into string. export array_tostring(float[] _id, string _separator = '')=>//{<< int _size = array_size(_id) string _str = '[ ' if _size > 0 for _i = 0 to _size-1 _str := _str + to_string(array_get(_id, _i)) if _i >= _size-1 _str := _str + ' ]' else _str := _str + (na(_separator) ? ', ' : _separator) _str //} //|----------------}-----------------------------------------------------------|| //| Line Methods {-----------------------------------------------------------------|| // @function 2 vector line in the form. [a.x, a.y, b.x, b.y] // @param _a vector, in the form [x, y]. // @param _b vector, in the form [x, y]. // @returns export line_new(float[] _a, float[] _b)=>//{<< float[] _line = array.new_float(size=0) array.push(id=_line, value=get_x(_a)) array.push(id=_line, value=get_y(_a)) array.push(id=_line, value=get_x(_b)) array.push(id=_line, value=get_y(_b)) _line //} // @function Start vector of a line. // @param _line vector4, in the form [a.x, a.y, b.x, b.y]. // @returns float[x, y] vector2 export line_get_a(float[] _line)=>//{<< float[] _vector = array.new_float(size=0) array.push(id=_vector, value=array.get(id=_line, index=0)) array.push(id=_vector, value=array.get(id=_line, index=1)) _vector //} // @function End vector of a line. // @param _line vector4, in the form [a.x, a.y, b.x, b.y]. // @returns float[x, y] vector2 export line_get_b(float[] _line)=>//{<< float[] _vector = array.new_float(size=0) array.push(id=_vector, value=array.get(id=_line, index=2)) array.push(id=_vector, value=array.get(id=_line, index=3)) _vector //} // @function Find the intersection vector of 2 lines. // @param _line1 line of 2 vectors in the form of a array [ax, ay, bx, by]. // @param _line2 line of 2 vectors in the form of a array [ax, ay, bx, by]. // @returns vector in the form of a array [x, y]. export line_intersect(float[] _line1, float[] _line2)=>//{<< float[] _l1a = line_get_a(_line1) float[] _l1b = line_get_b(_line1) float[] _l2a = line_get_a(_line2) float[] _l2b = line_get_b(_line2) float _l1ax = get_x(_l1a) float _l1ay = get_y(_l1a) float _l1bx = get_x(_l1b) float _l1by = get_y(_l1b) float _l2ax = get_x(_l2a) float _l2ay = get_y(_l2a) float _l2bx = get_x(_l2b) float _l2by = get_y(_l2b) float _a1 = _l1by - _l1ay float _b1 = _l1ax - _l1bx float _c1 = _a1 * _l1ax + _b1 * _l1ay float _a2 = _l2by - _l2ay float _b2 = _l2ax - _l2bx float _c2 = _a2 * _l2ax + _b2 * _l2ay float _delta = _a1 * _b2 - _a2 * _b1 new((_b2 * _c1 - _b1 * _c2) / _delta, (_a1 * _c2 - _a2 * _c1) / _delta) //} // @function Draws a line using line prototype. // @param _line vector4, in the form [a.x, a.y, b.x, b.y]. // @param _xloc string // @param _extend string // @param _color color // @param _style string // @param _width int // @returns draw line object export draw_line(float[] _line, string _xloc = 'bi', string _extend = 'n', color _color = #2196f3, string _style = 'sol', int _width = 1) => //{<< float[] _a = line_get_a(_line) float[] _b = line_get_b(_line) line.new(x1=int(get_x(_a)), y1=get_y(_a), x2=int(get_x(_b)), y2=get_y(_b), xloc=_xloc, extend=_extend, color=_color, style=_style, width=_width) //} // @function Draws a triangle using line prototype. // @param _v1 vector4, in the form [a.x, a.y, b.x, b.y]. // @param _v2 vector4, in the form [a.x, a.y, b.x, b.y]. // @param _v3 vector4, in the form [a.x, a.y, b.x, b.y]. // @param _xloc string // @param _color color // @param _style string // @param _width int // @returns tuple with 3 line objects. [line, line, line] export draw_triangle(float[] _v1, float[] _v2, float[] _v3, string _xloc = 'bi', color _color = #2196f3, string _style = 'sol', int _width = 1)=>//{<< float[] _a = line_new(_v1, _v2) float[] _b = line_new(_v2, _v3) float[] _c = line_new(_v3, _v1) [draw_line(_a, _xloc, extend.none, _color, _style, _width), draw_line(_b, _xloc, extend.none, _color, _style, _width), draw_line(_c, _xloc, extend.none, _color, _style, _width)] //} // @function Draws a square using vector2 line prototype. // @param _v1 vector4, in the form [a.x, a.y, b.x, b.y]. // @param _size float[x, y] // @param _angle float // @param _xloc string // @param _color color // @param _style string // @param _width int // @returns tuple with 3 line objects. [line, line, line] export draw_rect(float[] _v1, float[] _size, float _angle, string _xloc = 'bi', color _color = #2196f3, string _style = 'sol', int _width = 1)=>//{<< float _x = get_x(_v1) float _y = get_y(_v1) float _w = get_x(_size) float _h = get_y(_size) float[] _vectors = array_new(1, _v1) array_push(_vectors, new(_x, _y + _h)) array_push(_vectors, new(_x + _w, _y + _h)) array_push(_vectors, new(_x + _w, _y)) if _angle != 0.0 _vectors := array_rotate_points(_vectors, _v1, _angle) float[] _a = line_new(array_get(_vectors, 0), array_get(_vectors, 1)) float[] _b = line_new(array_get(_vectors, 1), array_get(_vectors, 2)) float[] _c = line_new(array_get(_vectors, 2), array_get(_vectors, 3)) float[] _d = line_new(array_get(_vectors, 3), array_get(_vectors, 0)) [draw_line(_a, _xloc, extend.none, _color, _style, _width), draw_line(_b, _xloc, extend.none, _color, _style, _width), draw_line(_c, _xloc, extend.none, _color, _style, _width), draw_line(_d, _xloc, extend.none, _color, _style, _width)] //} //|----------}-----------------------------------------------------------------|| //|----------------------------------------------------------------------------|| //|----------------------------------------------------------------------------|| //|----------------------------------------------------------------------------|| rotation = input(0) origin = input(0.0) triangle_scale = input(0.0) if barstate.ishistory[1] and (barstate.isrealtime or barstate.islast) float[] a = new(0.10, -0.25) float[] b = new(0.66, float(na)) float[] c = add(a, one()) float[] d = subtract(c, one()) float[] L = array_new(4, new(0, 0)) array_set(L, 0, a) array_set(L, 1, b) array_set(L, 2, c) array_set(L, 3, d) _text = '' _text := _text + 'Helper Methods:\n' _text := _text + 'atan2(a):' + str.tostring(atan2(a)) + '\n' _text := _text + '\n' _text := _text + 'Properties:\n' _text := _text + 'down:' + to_string(down()) + ', left:' + to_string(left()) + ', one:' + to_string(one()) + ', right:' + to_string(right()) + ', up:' + to_string(up()) + ', zero:' + to_string(zero()) + '\n' set_x(a, 0.25) set_y(a, 0.5) _text := _text + 'set a.x = 0.25, ' + 'set a.y = 0.5 ' + 'a:' + to_string(a) + '\n' _text := _text + 'a:' + to_string(a) + ', a.x:' + str.tostring(get_x(a)) + ', a.y:' + str.tostring(get_y(a)) + '\n' _text := _text + 'length(' + 'a:' + to_string(a) + ') = ' + str.tostring(length(a)) + '\n' _text := _text + 'length squared(' + 'a:' + to_string(a) + ') = ' + str.tostring(length_squared(a)) + '\n' _text := _text + 'normalize(' + 'a:' + to_string(a) + ') = ' + to_string(normalize(a)) + '\n' _text := _text + 'rescale(' + 'a:' + to_string(a) + ', 2) = ' + to_string(rescale(a, 2.0)) + '\n' _text := _text + 'vmin(' + 'a: ' + str.tostring(vmin(a)) + '), vmax(a: ' + str.tostring(vmax(a)) + ')\n' _text := _text + '\n' _text := _text + 'Operator Methods:\n' set_y(b, 0.33) _text := _text + 'add a:' + to_string(a) + ' + b:' + to_string(b) + ' = ' + to_string(add(a, b)) + '\n' _text := _text + 'subtract a:' + to_string(a) + ' - b:' + to_string(b) + ' = ' + to_string(subtract(a, b)) + '\n' _text := _text + 'multiply a:' + to_string(a) + ' * b:' + to_string(b) + ' = ' + to_string(multiply(a, b)) + '\n' _text := _text + 'divide a:' + to_string(a) + ' / b:' + to_string(b) + ' = ' + to_string(divide(a, b)) + '\n' _text := _text + 'negate -a:' + to_string(a) + ' = ' + to_string(negate(a)) + '\n' _text := _text + 'perpendicular a:' + to_string(a) + ' = ' + to_string(perp(a)) + '\n' _text := _text + 'equals a:' + to_string(a) + ' == b:' + to_string(b) + ' = ' + (equals(a, b)?'true':'false') + '\n' _text := _text + 'dot product a:' + to_string(a) + ' º b:' + to_string(b) + ' = ' + str.tostring(dot(a, b)) + '\n' _text := _text + 'cross_product product a:' + to_string(a) + ' x b:' + to_string(b) + ' = ' + str.tostring(cross_product(a, b)) + '\n' _text := _text + 'scale a by 2.0:' + str.tostring(scale(a, 2.0)) + '\n' _text := _text + '\n' _text := _text + 'Methods:\n' _text := _text + 'rotate by angle(radian) a: ' + to_string(a) + ' ∡:' + str.tostring(1.618) + ' = ' + to_string(rotate(a, 1.618)) + '\n' _text := _text + 'rotate by angle(degree) a: ' + to_string(a) + ' ∡:' + str.tostring(30) + ' = ' + to_string(rotate_degree(a, 30.0)) + '\n' _text := _text + 'ceil (0.1111, 0.11111):' + to_string(vceil(new(0.1111, 0.11111), 2)) + '\n' _text := _text + 'pow a:' + to_string(a) + ' = ' + to_string(vpow(a, 2)) + '\n' _text := _text + 'distance a -> b:' + str.tostring(distance(a, b)) + '\n' _text := _text + 'perpendicular distance a -> |b, c|:' + str.tostring(perpendicular_distance(a, b, c)) + '\n' _text := _text + 'project a <- b:' + to_string(project(a, b)) + '\n' _text := _text + 'projectN a <- b:' + to_string(projectN(a, b)) + '\n' _text := _text + 'reflect a <- b:' + to_string(reflect(a, b)) + '\n' _text := _text + 'reflectN a <- b:' + to_string(reflectN(a, b)) + '\n' _text := _text + 'angle a:' + str.tostring(angle(a)) + '\n' _text := _text + 'angle unsigned a-b:' + str.tostring(angle_unsigned(a, b)) + '\n' _text := _text + 'angle signed a-b:' + str.tostring(angle_signed(a, b)) + '\n' _text := _text + 'angle 360 a-b:' + str.tostring(angle_360(a, b)) + '\n' _text := _text + 'Move a to b by 25%:' + to_string(lerp(a, b, 0.25)) + '\n' _text := _text + 'Restrict a to (0.1, 0.1), (0.4, 0.4) :' + to_string(clamp(a, from(0.1), from(0.4))) + '\n' _text := _text + 'Area of triangle: (0.1, 0.1), (0.4, 0.4), (0.4, 0.1) :' + str.tostring(area_triangle(from(0.1), from(0.4), new(0.4, 0.1))) + '\n' _text := _text + '\n' _text := _text + 'Line Methods:\n' _text := _text + 'Intersect(((4,0),(6,10)), ((0,3),(10,7))):' + to_string(line_intersect(line_new(new(4.0, 0.0), new(6.0, 10.0)), line_new(new(0.0, 3.0), new(10.0, 7.0)))) + '\n' _text := _text + '\n' _text := _text + 'Array Methods:\n' _text := _text + 'array L: ' + array_tostring(L, string(na)) + '\n' _text := _text + 'center of L: ' + to_string(array_center(L)) + '\n' array_unshift(L, from(1.111)) array_push(L, from(2.222)) _text := _text + 'Sum of L: ' + to_string(array_sum(L)) + '\n' _text := _text + 'Top of L: ' + to_string(array_pop(L)) + '\n' _text := _text + 'Bottom of L: ' + to_string(array_shift(L)) + '\n' float[] _triangle = array_new(3, from(0.0)) array_set(_triangle, 1, from(bar_index/2)) array_set(_triangle, 2, new(bar_index/2, 0.0)) float[] _new_triangle = array_scale_points(_triangle, from(origin), triangle_scale) draw_triangle(array_get(_triangle, 0), array_get(_triangle, 1), array_get(_triangle, 2), xloc.bar_index, color.red, line.style_solid, 1) draw_triangle(array_get(_new_triangle, 0), array_get(_new_triangle, 1), array_get(_new_triangle, 2), xloc.bar_index, color.lime, line.style_dashed, 1) // label.new(x=bar_index, y=0.0, text=_text, style=label.style_label_left, textalign=text.align_left) console.queue_one(__C, _text) draw_line(line_new(from(0.0), from(bar_index)), xloc.bar_index, extend.none, color.aqua, line.style_dashed, 3) draw_rect(from(bar_index/3), from(bar_index/4), rotation, xloc.bar_index, color.red, line.style_solid, 1) draw_line(line_new(from(bar_index/2), rotate_around(from(bar_index/2), from(bar_index/3), rotation)), xloc.bar_index, extend.none, color.navy, line.style_arrow_right, 2) console.update(__T, __C)
ColorScheme
https://www.tradingview.com/script/fh7Tyfli-ColorScheme/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
37
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description A color scheme generator. library(title='ColorScheme') //#region -> Helpers: import RicardoSantos/ColorExtension/1 as colex // Constants: { // Color Model names: string __CMODEL1__ = 'monochromatic' string __CMODEL2__ = 'analog' string __CMODEL3__ = 'triadic' string __CMODEL4__ = 'tetradic' string __CMODEL5__ = 'square' // } // () { // @function Enumerate models available to profile colors. // @param index `int`: Index of color model. (1:'monochromatic', 2:'analog', 3:'triadic', 4:'tetradic', 5:'square', anything else:'monochromatic') // @returns // - `string`: Name of color model. // --- // Usage: // - `model(1)` export model (int index=0) => switch index 1 => __CMODEL1__ 2 => __CMODEL2__ 3 => __CMODEL3__ 4 => __CMODEL4__ 5 => __CMODEL5__ => __CMODEL1__ // } // model_index () { // @function Enumerate a model name to a index number. // @param model `string`: Name of the model // @returns // - `int`: Index of color model. // --- // Usage: // - `model_index("monochromatic")` export model_index (string model)=> switch model __CMODEL1__ => 1 __CMODEL2__ => 2 __CMODEL3__ => 3 __CMODEL4__ => 4 __CMODEL5__ => 5 => 1 // } //#endregion //#region -> Constructor: // @type Theme object holding a dictionary alike structure. // @field keys List of named keys. // @field colors List of colors. export type Theme array<string> keys array<color> colors // init () { // @function Initiate the array data registry that will hold the color profile. // @param this `Theme`: Theme object. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().init()` export method init (Theme this) => var string[] _keys = array.new_string(0) var color[] _colors = array.new_color(0) this.keys := _keys this.colors := _colors this // } // new () { // @function Generate and initiate the properties of a new theme object. // @returns // - New theme object. // --- // Usage: // - `theme = new()` export new () => Theme.new().init() // } //#endregion //#region -> Testing: // check_registry_integrity () { // @function Checks the integrity of the registers, it will produce a runtime error if check fails. // @param this `Theme`: Theme object. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().check_registry_integrity()` export method check_registry_integrity (Theme this) => int _size_k = array.size(this.keys) int _size_c = array.size(this.colors) if _size_k != _size_c runtime.error('ColorScheme -> check_registry_integrity(): registers size do not match.') this // } //#endregion //#region -> Properties: // add () { // @function Add new (key, color) entry to the registry. // @param this `Theme` : Theme object. // @param key `string`: Unique key to reference the value. // @param value `color` : Color value of the specified key. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme.new().add("Gray20", #333333)` export method add (Theme this, string key, color value) => check_registry_integrity(this) int is_key_in = array.indexof(this.keys, key) if is_key_in > -1 runtime.error('ColorScheme -> add(): key is already present in registry.') else array.push(this.keys, key) array.push(this.colors, value) this // } // () { // @function Get a (key, color) entry from the registry. // @param this `Theme` : Theme object. // @param key `string`: Unique key to reference the value. // @returns // - `color`: The color at referenced key. // --- // Usage: // - `theme = Theme.new().add("Gray20", #333333).get_color("Gray20")` export method get_color (Theme this, string key) => check_registry_integrity(this) int _key_index = array.indexof(this.keys, key) if _key_index < 0 runtime.error('ColorScheme -> delete(): key is not present in registry.') array.get(this.colors, _key_index) // } // () { // @function Edit a (key, color) entry in the registry. // @param this `Theme` : Theme object. // @param key `string`: Unique key to reference the value, key target to update. // @param new_key `string`: Unique key to reference the value. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().add("Gray20", #333333).edit_key("Gray20", "Gray")` export method edit_key (Theme this, string key, string new_key) => check_registry_integrity(this) int _key_index = array.indexof(this.keys, key) int _new_key_index = array.indexof(this.keys, new_key) switch _key_index < 0 => runtime.error('ColorScheme -> edit_key(): key is not present in registry.') _new_key_index > -1 => runtime.error('ColorScheme -> edit_key(): new key is already present in registry.') array.set(this.keys, _key_index, new_key) this // } // () { // @function Edit a (key, color) entry in the registry. // @param this `Theme` : Theme object. // @param key `string`: Unique key to reference the value. // @param new_value `color` : Color value of the specified key. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().add("Gray20", #333333).edit_color("Gray20", #222222)` export method edit_color (Theme this, string key, color new_value) => check_registry_integrity(this) int _key_index = array.indexof(this.keys, key) if _key_index < 0 runtime.error(str.format('ColorScheme -> edit_color({0}): key is not present in registry.', key)) else array.set(this.colors, _key_index, new_value) this // } // () { // @function Delete a (key, color) entry from the registry. // @param this `Theme` : Theme object. // @param key `string`: Unique key to reference the value. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().add("Gray20", #333333).delete("Gray20")` export method delete (Theme this, string key) => check_registry_integrity(this) int _key_index = array.indexof(this.keys, key) if _key_index < 0 runtime.error(str.format('ColorScheme -> delete({0}): key is not present in registry.', key)) color(na) else array.remove(this.keys, _key_index) array.remove(this.colors, _key_index) this // } // () { // @function Delete all (key, color) entrys from the registry. // @param this `Theme`: Theme object. // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().delete_all()` export method delete_all (Theme this) => array.clear(this.keys) array.clear(this.colors) this // } //#endregion //#region -> Model generation: // () { // @function Generate a multi color scheme. // @param this `Theme` : Theme object. // @param primary `color` : Origin color to base the profile. // @param model `string`: Color model selection, default='monochromatic', options=('monochromatic', 'triadic near', 'triadic far', 'tetradic') // @returns // - `this`: Self, Theme object. // --- // Usage: // - `theme = Theme.new().generate_scheme(#e3e3e3, "monochromatic")` export method generate_scheme(Theme this, color primary, string model='monochromatic') => check_registry_integrity(this) // delete_all(key_registry, color_registry) // possible implementation to clear registry conflicts? this.add('primary 0', primary) // primary color hsl properties: [_primary_hue, _primary_saturation, _primary_lightness] = colex.rgb_to_hsl(color.r(primary), color.g(primary), color.b(primary)) switch model __CMODEL1__ => // monochromatic generates 4 colors: primary + 3 shades to the most distant edge (dark, light) // generate shades to dark or light if _primary_lightness >= 50.0 this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.75, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.25, 0.0)) else float _inverse_range = 100.0 - _primary_lightness this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + _inverse_range * 0.25, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + _inverse_range * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + _inverse_range * 0.75, 0.0)) __CMODEL2__ => // analog generates 2 adjacent base colors and 3 shades to the most distant edge (dark, light) for each [_lower, _upper] = colex.analog(primary) [_lower_hue, _lower_saturation, _lower_lightness] = colex.rgb_to_hsl(color.r(_lower), color.g(_lower), color.b(_lower)) [_upper_hue, _upper_saturation, _upper_lightness] = colex.rgb_to_hsl(color.r(_upper), color.g(_upper), color.b(_upper)) // generate shades to dark or light if _primary_lightness >= 50.0 this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.75, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.25, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.75, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.25, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.75, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.25, 0.0)) else this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.25, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.75, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.25, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.75, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.25, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.75, 0.0)) __CMODEL3__ => // triadic generates 2 far spectrum base colors and 3 shades to the most distant edge (dark, light) for each [_lower, _upper] = colex.triadic(primary) [_lower_hue, _lower_saturation, _lower_lightness] = colex.rgb_to_hsl(color.r(_lower), color.g(_lower), color.b(_lower)) [_upper_hue, _upper_saturation, _upper_lightness] = colex.rgb_to_hsl(color.r(_upper), color.g(_upper), color.b(_upper)) // generate shades to dark or light if _primary_lightness >= 50.0 this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.75, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.25, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.75, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.25, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.75, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.25, 0.0)) else this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.25, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.75, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.25, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.75, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.25, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.75, 0.0)) __CMODEL4__ => // tetradic generates 3 complement colors in a rectangular shape and 3 shades for each. [_complement, _lower, _upper] = colex.tetradic(primary) [_complement_hue, _complement_saturation, _complement_lightness] = colex.rgb_to_hsl(color.r(_complement), color.g(_complement), color.b(_complement)) [_lower_hue, _lower_saturation, _lower_lightness] = colex.rgb_to_hsl(color.r(_lower), color.g(_lower), color.b(_lower)) [_upper_hue, _upper_saturation, _upper_lightness] = colex.rgb_to_hsl(color.r(_upper), color.g(_upper), color.b(_upper)) // generate shades to dark or light if _primary_lightness >= 50.0 this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.75, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.25, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.75, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.25, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.75, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.25, 0.0)) this.add('complement 0', _complement) this.add('complement 1', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.75, 0.0)) this.add('complement 2', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.50, 0.0)) this.add('complement 3', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.25, 0.0)) else this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.25, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.75, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.25, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.75, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.25, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.75, 0.0)) this.add('complement 0', _complement) this.add('complement 1', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.25, 0.0)) this.add('complement 2', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.50, 0.0)) this.add('complement 3', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.75, 0.0)) __CMODEL5__ => // tetradic generates 3 complement colors in a rectangular shape and 3 shades for each. [_complement, _lower, _upper] = colex.square(primary) [_complement_hue, _complement_saturation, _complement_lightness] = colex.rgb_to_hsl(color.r(_complement), color.g(_complement), color.b(_complement)) [_lower_hue, _lower_saturation, _lower_lightness] = colex.rgb_to_hsl(color.r(_lower), color.g(_lower), color.b(_lower)) [_upper_hue, _upper_saturation, _upper_lightness] = colex.rgb_to_hsl(color.r(_upper), color.g(_upper), color.b(_upper)) // generate shades to dark or light if _primary_lightness >= 50.0 this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.75, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness * 0.25, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.75, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness * 0.25, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.75, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness * 0.25, 0.0)) this.add('complement 0', _complement) this.add('complement 1', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.75, 0.0)) this.add('complement 2', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.50, 0.0)) this.add('complement 3', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness * 0.25, 0.0)) else this.add('primary 1', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.25, 0.0)) this.add('primary 2', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.50, 0.0)) this.add('primary 3', colex.hsl(_primary_hue, _primary_saturation, _primary_lightness + (100.0 - _primary_lightness) * 0.75, 0.0)) this.add('lower 0', _lower) this.add('lower 1', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.25, 0.0)) this.add('lower 2', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.50, 0.0)) this.add('lower 3', colex.hsl(_lower_hue, _lower_saturation, _lower_lightness + (100.0 - _lower_lightness) * 0.75, 0.0)) this.add('upper 0', _upper) this.add('upper 1', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.25, 0.0)) this.add('upper 2', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.50, 0.0)) this.add('upper 3', colex.hsl(_upper_hue, _upper_saturation, _upper_lightness + (100.0 - _upper_lightness) * 0.75, 0.0)) this.add('complement 0', _complement) this.add('complement 1', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.25, 0.0)) this.add('complement 2', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.50, 0.0)) this.add('complement 3', colex.hsl(_complement_hue, _complement_saturation, _complement_lightness + (100.0 - _complement_lightness) * 0.75, 0.0)) this // } //#endregion //#region -> Preview: color primary = input.color(#e3f650) // int imodel = input(1) string model = input.string(__CMODEL1__, options=[__CMODEL1__, __CMODEL2__, __CMODEL3__, __CMODEL4__, __CMODEL5__]) int imodel = model_index(model) Theme theme = new() if barstate.isfirst theme.generate_scheme(primary, model(imodel)) _T = table.new(position.bottom_right, 4, 4) _T.cell(0, 0, 'Primary', bgcolor=theme.get_color('primary 0')) if imodel > 0 _T.cell(1, 0, 'Primary 1', bgcolor=theme.get_color('primary 1')) _T.cell(2, 0, 'Primary 2', bgcolor=theme.get_color('primary 2')) _T.cell(3, 0, 'Primary 3', bgcolor=theme.get_color('primary 3')) if imodel > 1 _T.cell(0, 1, 'lower 0', bgcolor=theme.get_color('lower 0')) _T.cell(1, 1, 'lower 1', bgcolor=theme.get_color('lower 1')) _T.cell(2, 1, 'lower 2', bgcolor=theme.get_color('lower 2')) _T.cell(3, 1, 'lower 3', bgcolor=theme.get_color('lower 3')) _T.cell(0, 2, 'upper 0', bgcolor=theme.get_color('upper 0')) _T.cell(1, 2, 'upper 1', bgcolor=theme.get_color('upper 1')) _T.cell(2, 2, 'upper 2', bgcolor=theme.get_color('upper 2')) _T.cell(3, 2, 'upper 3', bgcolor=theme.get_color('upper 3')) if imodel > 3 _T.cell(0, 3, 'complement 0', bgcolor=theme.get_color('complement 0')) _T.cell(1, 3, 'complement 1', bgcolor=theme.get_color('complement 1')) _T.cell(2, 3, 'complement 2', bgcolor=theme.get_color('complement 2')) _T.cell(3, 3, 'complement 3', bgcolor=theme.get_color('complement 3')) //#endregion
DebugConsole
https://www.tradingview.com/script/GQf7WeMO-DebugConsole/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
120
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods for debuging/output into a table, console like style. library(title='DebugConsole') // StyleParameters { // @field position Table position in panel. // @field bgcolor Background color. // @field border_color Border color. // @field border_width border width. // @field frame_color Frame color. // @field frame_width Frame width. // @field width Console width. // @field height Console height. // @field text_color Text color. // @field text_halign Text horizontal alignment. // @field text_valign Text vertical alignment. // @field text_size Size of the text. export type StyleParameters // table style: string position = position.bottom_right color bgcolor = #000000 color frame_color = #787b86 int frame_width = 3 color border_color = #787b86 int border_width = 2 // cell style: int width = 95 int height = 95 color text_color = #b2b5be string text_halign = text.align_left string text_valign = text.align_bottom string text_size = size.normal // } // Parameters { // @type Parameters object. // @field size Number of string cells. // @field visible Is console visible? // @field intrabar Is intrabar persistance (`varip`) on? export type Parameters // basic initialization: int size = 20 bool visible = true bool intrabar = false StyleParameters style // } // Console { // @type Console object used to store log entries and table. // @field entries Message entry stream. // @field table Output table. export type Console array<string> entries table table // } // init () { // @function initializes the Console object. // @param this Console, Console object with entries array and table. // @param size int , Number of entries allowed in the console. // @param visible bool , Toggles the visibility of the table, (default=true). // @param intrabar_persistance bool , Toggles the entry message intrabar persistance into the console, (default=false). // @returns Console object, contains the entries console and output table. export method init ( Console this , int size = 20 , bool visible = true , bool intrabar_persistance = false ) => color _bg = #000000 // intrabar persistance: // configures console entries to accept intrabar persistance entries or not. switch intrabar_persistance true => varip string[] _console = array.new_string(size, '') , this.entries := _console false => var string[] _console = array.new_string(size, '') , this.entries := _console => runtime.error('DebugConsole -> init(): Undefined boolean clause for intrabar persistance.') // optional table visibility: if visible var table _table = table.new( position = position.bottom_left, columns = 1 , rows = 1 , bgcolor = _bg , frame_color = #787b86 , frame_width = 3 , border_color = #787b86 , border_width = 2 ) this.table := _table table.cell( table_id = this.table , column = 0 , row = 0 , text = '' , width = 100 , height = 95 , text_color = #b2b5be , text_halign = text.align_left , text_valign = text.align_bottom, text_size = size.normal , bgcolor = _bg ) else color _alpha100 = #00000000 var table _table = table.new( position = position.bottom_left, columns = 1 , rows = 1 , bgcolor = _alpha100 , frame_color = _alpha100 , frame_width = 3 , border_color = _alpha100 , border_width = 2 ) this.table := _table this // } // new () { // @function Create a new Console object and inittiate its basic parameters. // @param settings `Parameters` Parameters definitions (optional). // @returns `Console` A new console object. export new (Parameters settings) => con = Console.new().init(settings.size, settings.visible, settings.intrabar) // con.table.set_bgcolor( settings.style.bgcolor ) con.table.set_border_color( settings.style.border_color ) con.table.set_border_width( settings.style.border_width ) con.table.set_frame_color( settings.style.frame_color ) con.table.set_frame_width( settings.style.frame_width ) con.table.set_position( settings.style.position ) // con.table.cell_set_bgcolor( 0, 0, settings.style.bgcolor ) con.table.cell_set_width( 0, 0, settings.style.width ) con.table.cell_set_height( 0, 0, settings.style.height ) con.table.cell_set_text_color( 0, 0, settings.style.text_color ) con.table.cell_set_text_halign( 0, 0, settings.style.text_halign ) con.table.cell_set_text_valign( 0, 0, settings.style.text_valign ) con.table.cell_set_text_size( 0, 0, settings.style.text_size ) con // @function Create a new Console object and inittiate its basic parameters. // @returns `Console` A new console object. export new () => Parameters settings = Parameters.new(style = StyleParameters.new()) new(settings) // } // queue () { // @function Regular Queue, will be called once every bar its called. // @param console_id string array, console configuration array. // @param new_line string, with contents for new line. // @returns void. export method queue (Console this, string new_line) => array.shift(this.entries) array.push(this.entries, new_line) this // } // queue_one () { // @function Queue only one time, will not repeat itself. // @param console_id string array, console configuration array. // @param new_line string, with contents for new line. // @returns void. export method queue_one (Console this, string new_line) => var bool _repeat = true if _repeat array.shift(this.entries) array.push(this.entries, new_line) _repeat := false this // } // queue_one_intrabar () { // @function Queue only one time, will not repeat itself. // @param console_id string array, console configuration array. // @param new_line string, with contents for new line. // @returns void. export method queue_one_intrabar (Console this, string new_line) => varip bool _repeat = true if _repeat array.shift(this.entries) array.push(this.entries, new_line) _repeat := false this // } // update () { // @function Update method for the console screen. // @param table_id table, table to update console text. // @param console_id string array, console configuration array. // @returns void. export method update (Console this) => string _t = array.join(this.entries, '\n') table.cell_set_text( table_id = this.table, column = 0 , row = 0 , text = _t ) this // } // ┌────────────────┐ // Example Usage: // └────────────────┘ // initialize console configuration: bool is_visible = input.bool(true) bool is_intrabar = input.bool(false) // bool is_visible1 = input.bool(true) settings = Parameters.new(visible = is_visible, intrabar = is_intrabar, style = StyleParameters.new()) con = new(settings)//Console.new(), log.init(20, is_visible, is_intrabar) // init(Console.new(), 20, is_visible, is_intrabar) // NOTE: you may use multiple consoles in one script, but varip console is limited to one !! // var log1 = init(Console.new(), 20, is_visible1), table.set_position(log1.table, position.top_center), table.cell_set_width(log1.table, 0, 0, 50), log1.queue(str.tostring(time)), log1.update() // var log2 = init(Console.new(), 20, is_visible1), table.set_position(log2.table, position.top_left), table.cell_set_width(log2.table, 0, 0, 20), log2.queue(str.tostring(time)).update() // can use table.cell_"properties"() to adjust console style definitions: table.set_position(con.table, position.bottom_left) table.cell_set_width(con.table, 0, 0, 80) // usage: con.queue_one_intrabar(str.format('only one intrabar at: {0}', str.format('{0}-{1}-{2} {3}:{4}:{5}', year, month, dayofmonth, hour, minute, second))) con.queue_one('only one') con.queue_one('only one again') con.queue_one_intrabar(str.format('another only one intrabar at: {0}', str.format('{0}-{1}-{2} {3}:{4}:{5}', year, month, dayofmonth, hour, minute, second))) if barstate.islastconfirmedhistory con.queue('0: ....') con.queue('1: ....') con.queue('2: ....') con.queue_one_intrabar(str.format('another only one intrabar at the last confirmed history at: {0}', str.format('{0}-{1}-{2} {3}:{4}:{5}', year, month, dayofmonth, hour, minute, second))) if barstate.islast con.queue_one('only one last time') con.queue_one_intrabar(str.format('only one intrabar at the last bar: {0}', str.format('{0}-{1}-{2} {3}:{4}:{5}', year, month, dayofmonth, hour, minute, second))) con.queue_one_intrabar('only loads at the last bar after loading script into chart, disapears after') if is_intrabar con.queue(str.format('realtime intrabar: {0}', close)) // update console screen: // this may be called more than one time through the script. con.update() // @function Generate a independent single value output stream. // @param message string, the output message. // @param size int, number of messages to show. // @param text_size string, default=size.normal. // @param bg_color color, default=#000000. // @param text_color color, default=#ffffff. // @param border_color color, default=color.grey. // returns void // Originaly by Adolgov export log (string message, int size = 20, string text_size=size.normal, color bg_color=#000000, color text_color=#ffffff, color border_color=color.gray) => //{ var table _table = table.new( position=position.bottom_right, columns=1, rows=1, bgcolor=bg_color, frame_color=border_color, frame_width=3, border_color=border_color, border_width=2) var string[] _console = array.new<string>() array.push(_console, message) if array.size(_console) > size array.shift(_console) table.cell( table_id=_table, column=0, row=0, text=array.join(_console, '\n'), text_color=text_color, text_halign=text.align_left, text_valign=text.align_bottom, text_size=text_size, bgcolor=bg_color) // log(str.format("bar_index = {0}, close = {1}", bar_index, close)) //} // @function Generate a independent single value output stream supporting intrabar persistance. // @param message string, the output message. // @param size int, number of messages to show. // @param text_size string, default=size.normal. // @param bg_color color, default=#000000. // @param text_color color, default=#ffffff. // @param border_color color, default=color.grey. // returns void // Originaly by Adolgov export log_ip (string message, int size = 20, string text_size=size.normal, color bg_color=#000000, color text_color=#ffffff, color border_color=color.gray) => //{ var table _table = table.new( position=position.bottom_right, columns=1, rows=1, bgcolor=bg_color, frame_color=border_color, frame_width=3, border_color=border_color, border_width=2) varip string[] _console = array.new<string>() array.push(_console, message) if array.size(_console) > size array.shift(_console) table.cell( table_id=_table, column=0, row=0, text=array.join(_console, '\n'), text_color=text_color, text_halign=text.align_left, text_valign=text.align_bottom, text_size=text_size, bgcolor=bg_color) log_ip(str.format("bar_index = {0}, close = {1}", bar_index, close)) //}
MathSpecialFunctionsGamma
https://www.tradingview.com/script/kjfrsghw-MathSpecialFunctionsGamma/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
17
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Gamma Functions. library(title='MathSpecialFunctionsGamma') // reference: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/SpecialFunctions/Gamma.cs#L571 // https://mathworld.wolfram.com/GammaFunction.html // imports: import RicardoSantos/MathConstants/1 as mc // mc.LogTwoSqrtEOverPi(), mc.TwoSqrtEOverPi(), mc.Sqrt2() import RicardoSantos/MathExtension/1 as me // me.near_equal() import RicardoSantos/Probability/1 as pr // pr.ierf() // Constants: float EPSILON = 1.0e-15 float BIG_FLOAT = 4503599627370496.0 float BIG_FLOAT_INV = 2.22044604925031308085e-16 var float POSITIVE_INF = 1.0 / nz(0.0) var float NEGATIVE_INF = math.log(nz(0.0)) int GAMMA_N = 10 // The order of the "GammaLn" approximation. float GAMMA_R = 10.900511 // Auxiliary variable when evaluating the "GammaLn" function. // Polynomial coefficients for the "GammaLn" approximation. // float[] GammaDk = array.from(2.48574089138753565546e-5, 1.05142378581721974210, -3.45687097222016235469, 4.51227709466894823700, -2.98285225323576655721, // 1.05639711577126713077, -1.95428773191645869583e-1, 1.70970543404441224307e-2, -5.71926117404305781283e-4, 4.63399473359905636708e-6, -2.71994908488607703910e-9) // @function Enumeration of the polynomial coefficients for the "GammaLn" approximation. // @param index int, 0 => index => 10, index of coeficient. // @returns float export GammaQ (int index) => //{ switch index 0 => 2.48574089138753565546e-5 1 => 1.05142378581721974210 2 => -3.45687097222016235469 3 => 4.51227709466894823700 4 => -2.98285225323576655721 5 => 1.05639711577126713077 6 => -1.95428773191645869583e-1 7 => 1.70970543404441224307e-2 8 => -5.71926117404305781283e-4 9 => 4.63399473359905636708e-6 10 => -2.71994908488607703910e-9 => float(na) // plot(GammaQ(0)) //} // @function Computes the logarithm of the Gamma function. // @param z The argument of the gamma function. // @returns The logarithm of the gamma function. export GammaLn (float z) => //{ if z < 0.5 float _s = GammaQ(0) for _i = 1 to GAMMA_N _s += GammaQ(_i) / (_i - z) mc.LnPi() - math.log(math.sin(math.pi * z)) - math.log(_s) - mc.LogTwoSqrtEOverPi() - ((0.5 - z) * math.log((0.5 - z + GAMMA_R) / math.e)) else float _s = GammaQ(0) for _i = 1 to GAMMA_N _s += GammaQ(_i) / (z + _i - 1.0) math.log(_s) + mc.LogTwoSqrtEOverPi() + ((z - 0.5) * math.log((z - 0.5 + GAMMA_R) / math.e)) //{ usage: // plot(GammaLn(0.42)) //{ remarks: // This implementation of the computation of the gamma and logarithm of the gamma function follows the derivation in // "An Analysis Of The Lanczos Gamma Approximation", Glendon Ralph Pugh, 2004. // We use the implementation listed on p. 116 which achieves an accuracy of 16 floating point digits. Although 16 digit accuracy // should be sufficient for double values, improving accuracy is possible (see p. 126 in Pugh). // Our unit tests suggest that the accuracy of the Gamma function is correct up to 14 floating point digits. //}}} // @function Computes the Gamma function. // @param z The argument of the gamma function. // @returns float, The logarithm of the gamma function. export Gamma (float z) => //{ if z < 0.5 float _s = GammaQ(0) for _i = 1 to GAMMA_N _s += GammaQ(_i) / (_i - z) math.pi / (math.sin(math.pi * z) * _s * mc.TwoSqrtEOverPi() * math.pow((0.5 - z + GAMMA_R) / math.e, 0.5 - z)) else float _s = GammaQ(0) for _i = 1 to GAMMA_N _s += GammaQ(_i) / (z + _i - 1.0) _s * mc.TwoSqrtEOverPi() * math.pow((z - 0.5 + GAMMA_R) / math.e, z - 0.5) //{ usage: // plot(Gamma(math.sin(2.0 / (bar_index % 30)))) // plot(Gamma(-3 + (bar_index % 600)*0.01)) // test ok: https://reference.wolfram.com/language/ref/Gamma.html // plot(-3 + (bar_index % 600)*0.01) //{ remarks: // This implementation of the computation of the gamma and logarithm of the gamma function follows the derivation in // "An Analysis Of The Lanczos Gamma Approximation", Glendon Ralph Pugh, 2004. // We use the implementation listed on p. 116 which should achieve an accuracy of 16 floating point digits. Although 16 digit accuracy // should be sufficient for double values, improving accuracy is possible (see p. 126 in Pugh). // // Our unit tests suggest that the accuracy of the Gamma function is correct up to 13 floating point digits. //}}} // Returns the lower incomplete regularized gamma function // @param a float, The argument for the gamma function. // @param x float, The upper integral limit. // @returns float, The lower incomplete gamma function. export GammaLowerRegularized (float a, float x) => //{ if a < 0.0 runtime.error('MathSpecialFunctions -> GamaLowerRegularized(): Parameter "a" value must not be negative (zero is ok).') float(na) else if x < 0.0 runtime.error('MathSpecialFunctions -> GamaLowerRegularized(): Parameter "x" value must not be negative (zero is ok).') float(na) else if me.near_equal(a, 0.0, EPSILON, 0.0) // no need to check x near 0 as it exits anyway with same value..... // if me.near_equal(x, 0.0) //use right hand limit value because so that regularized upper/lower gamma definition holds. // return 1.0 //return 1.0 else if me.near_equal(x, 0.0, EPSILON, 0.0) //return 0.0 else float _ax = (a * math.log(x)) - x - GammaLn(a) if _ax < -709.78271289338399 //return a < x ? 1.0 : 0.0 else if x <= 1 or x <= a float _r2 = a float _c2 = 1 float _ans2 = 1 while (_c2 / _ans2) > EPSILON _r2 += 1 _c2 := _c2 * x / _r2 _ans2 += _c2 //return math.exp(_ax) * _ans2 / a else int _c = 0 float _y = 1.0 - a float _z = x + _y + 1.0 float _p3 = 1 float _q3 = x float _p2 = x + 1 float _q2 = _z * x float _ans = _p2 / _q2 float _error = 999999999999999 while _error > EPSILON _c += 1 _y += 1 _z += 2 float _yc = _y * _c float _p = (_p2 * _z) - (_p3 * _yc) float _q = (_q2 * _z) - (_q3 * _yc) if _q != 0 float _nextans = _p / _q _error := math.abs((_ans - _nextans) / _nextans) _ans := _nextans else // zero div, skip _error := 1 // shift _p3 := _p2 _p2 := _p _q3 := _q2 _q2 := _q // normalize fraction when the numerator becomes large if math.abs(_p) > BIG_FLOAT _p3 *= BIG_FLOAT_INV _p2 *= BIG_FLOAT_INV _q3 *= BIG_FLOAT_INV _q2 *= BIG_FLOAT_INV //return 1.0 - (math.exp(_ax) * _ans) //{ usage: // plot(GammaLowerRegularized(10.0, 14.0)) //0.89 // plot(GammaLowerRegularized(10.0, 100.0)) //1.0 // plot(GammaLowerRegularized(-25.0, -75.0)) //negative parameter error.. //{ remarks: // P(a,x) = 1/Gamma(a) * int(exp(-t)t^(a-1),t=0..x) for real a &gt; 0, x &gt; 0. //}}} // @function Returns the upper incomplete regularized gamma function // @param a float, The argument for the gamma function. // @param x float, The lower integral limit. // @returns float, The upper incomplete regularized gamma function. export GammaUpperRegularized (float a, float x) => //{ if x < 1.0 or x <= a 1.0 - GammaLowerRegularized(a, x) else float _ax = a * math.log(x) - x - GammaLn(a) if _ax < -709.78271289338399 a < x ? 0.0 : 1.0 else _ax := math.exp(_ax) float _t = 0.0 float _y = 1 - a float _z = x + _y + 1 float _c = 0 float _pkm2 = 1 float _qkm2 = x float _pkm1 = x + 1 float _qkm1 = _z * x float _ans = _pkm1 / _qkm1 while _t > EPSILON _c += 1.0 _y += 1.0 _z += 2.0 float _yc = _y * _c float _pk = _pkm1 * _z - _pkm2 * _yc float _qk = _qkm1 * _z - _qkm2 * _yc if _qk != 0 float _r = _pk / _qk _t := math.abs((_ans - _r) / _r) _ans := _r else _t := 1.0 _pkm2 := _pkm1 _pkm1 := _pk _qkm2 := _qkm1 _qkm1 := _qk if math.abs(_pk) > BIG_FLOAT _pkm2 *= BIG_FLOAT_INV _pkm1 *= BIG_FLOAT_INV _qkm2 *= BIG_FLOAT_INV _qkm1 *= BIG_FLOAT_INV _ans * _ax //{ usage: // plot(GammaUpperRegularized(0.25, 0.75)) //{ remarks: // Q(a,x) = 1/Gamma(a) * int(exp(-t)t^(a-1),t=0..x) for real a &gt; 0, x &gt; 0. //}}} // @function Returns the upper incomplete gamma function. // @param a float, The argument for the gamma function. // @param x float, The lower integral limit. // @returns float, The upper incomplete gamma function. export GammaUpperIncomplete (float a, float x) => //{ GammaUpperRegularized(a, x) * Gamma(a) //{ usage: // plot(GammaUpperIncomplete(10.0, 0.0)) // 362880 //{ remarks: // Gamma(a,x) = int(exp(-t)t^(a-1),t=0..x) for real a &gt; 0, x &gt; 0. //}}} // Returns the lower incomplete gamma function // @param a float, The argument for the gamma function. // @param x float, The upper integral limit. // @returns float, The lower incomplete gamma function. export GammaLowerIncomplete (float a, float x) => //{ GammaLowerRegularized(a, x) * Gamma(a) //{ usage: // plot(GammaUpperIncomplete(10.0, 14.0)) // 42950.63 // plot(GammaUpperIncomplete(10.0, 100.0)) // 0.0 //{ remarks: // gamma(a,x) = int(exp(-t)t^(a-1),t=0..x) for real a &gt; 0, x &gt; 0. //}}} // This is too heavy for current architecture... // function Returns the inverse P^(-1) of the regularized lower incomplete gamma function // param a float, The argument for the gamma function. // param x float, The upper integral limit. // returns float, The lower incomplete gamma function. // export GammaLowerRegularizedInv (float a, float y0) => //{ // float _threshold = 5.0 * EPSILON // float _return = float(na) // if na(a) or na(y0) // //return float.NaN; // float(na) // else if a < 0 or me.near_equal(a, 0.0, EPSILON, 0.0) // // throw new ArgumentOutOfRangeException(nameof(a)); // runtime.error('MathSpecialFunctions -> GammaLowerRegularizedInv(): Parameter "a" out of range.') // float(na) // else if y0 < 0.0 or y0 > 1.0 // // throw new ArgumentOutOfRangeException(nameof(y0)); // runtime.error('MathSpecialFunctions -> GammaLowerRegularizedInv(): Parameter "y0" out of range.') // float(na) // else if me.near_equal(y0, 0.0, EPSILON, 0.0) // // return 0 // _return := 0.0 // if me.near_equal(y0, 1.0, EPSILON, 0.0) // // return float.PositiveInfinity; // _return := 1e308//POSITIVE_INF // else // float _y0 = 1 - y0 // float _xUpper = BIG_FLOAT // float _xLower = 0.0 // float _yUpper = 1.0 // float _yLower = 0.0 // // Initial Guess // float _d = 1.0 / (9.0 * a) // float _y = 1.0 - _d - (0.98 * mc.Sqrt2() * pr.ierf((2.0 * _y0) - 1.0) * math.sqrt(_d)) // float _x = a * math.pow(_y, 3) // float _lgm = GammaLn(a) // for _i = 0 to 19 // if _x < _xLower or _x > _xUpper // _d := 0.0625 // break // _y := 1.0 - GammaLowerRegularized(a, _x) // negative x error! // if _y < _yLower or _y > _yUpper // _d := 0.0625 // break // if _y < _y0 // _xUpper := _x // _yLower := _y // else // _xLower := _x // _yUpper := _y // _d := ((a - 1.0) * math.log(_x)) - _x - _lgm // if _d < -709.78271289338399 // _d := 0.0625 // break // _d := -math.exp(_d) // _d := (_y - _y0) / _d // if math.abs(_d / _x) < EPSILON // // return x; // _return := _x // break // if (_d > (_x / 4.0)) and (_y0 < 0.05) // // Naive heuristics for cases near the singularity // _d := _x / 10.0 // _x -= _d // if _xUpper == BIG_FLOAT // if _x <= 0 // _x := 1.0 // while _xUpper == BIG_FLOAT // _x := (1.0 + _d) * _x // _y := 1.0 - GammaLowerRegularized(a, _x) // if _y < _y0 // _xUpper := _x // _yLower := _y // break // _d += _d // int _dir = 0 // _d := 0.5 // for _i = 0 to 399 // _x := _xLower + (_d * (_xUpper - _xLower)) // _y := 1.0 - GammaLowerRegularized(a, _x) // _lgm := (_xUpper - _xLower) / (_xLower + _xUpper) // if math.abs(_lgm) < _threshold // _return := _x // break // _lgm := (_y - _y0) / _y0 // if math.abs(_lgm) < _threshold // _return := _x // break // if _x <= 0.0 // _return := 0.0 // break // if _y >= _y0 // _xLower := _x // _yUpper := _y // if _dir < 0 // _dir := 0 // _d := 0.5 // else if _dir > 1 // _d := (0.5 * _d) + 0.5 // else // _d := (_y0 - _yLower) / (_yUpper - _yLower) // _dir += 1 // else // _xUpper := _x // _yLower := _y // if _dir > 0 // _dir := 0 // _d := 0.5 // else if _dir < -1 // _d *= 0.5 // else // _d := (_y0 - _yLower) / (_yUpper - _yLower) // _dir -= 1 // _return := _x // _return //{ usage: // plot(GammaLowerRegularizedInv(2.0, 0.55)) // 1.52347 // https://reference.wolfram.com/language/ref/InverseGammaRegularized.html // plot(GammaLowerRegularizedInv(2.0, (bar_index % 99) * 0.01)) // plot(GammaLowerRegularizedInv(10, 100)) //{ remarks: // P(a,x) = 1/Gamma(a) * int(exp(-t)t^(a-1),t=0..x) for real a &gt; 0, x &gt; 0, // such that P^(-1)(a,P(a,x)) == x. //}}} // This is too heavy for current architecture... // function Computes the Digamma function which is mathematically defined as the derivative of the logarithm of the gamma function. // param x float, The argument of the digamma function. // returns float, The value of the DiGamma function at "x". // export DiGamma (float x) => //{ // float _c = 12.0 // float _d1 = -0.57721566490153286 // float _d2 = 1.6449340668482264365 // float _s = 1e-6 // float _s3 = 1.0 / 12.0 // float _s4 = 1.0 / 120.0 // float _s5 = 1.0 / 252.0 // float _s6 = 1.0 / 240.0 // float _s7 = 1.0 / 132.0 // float _return = float(na) // float _x = x // bool _recursive = false // bool _loop = true // while _loop // if na(x) // //(float.IsNegativeInfinity(x) || float.IsNaN(x)) // _return := float(na) // break // else if (x <= 0.0) and (math.floor(x) == x) // Handle special cases. // _return := -1.0e308//float.NegativeInfinity // break // else if x < 0.0 // Use inversion formula for negative numbers. // // _return := float(na)//DiGamma(1.0 - x) + (math.pi / math.tan(-math.pi * x)) // recursive call!! // _x := 1 - x // _recursive := true // continue // else if x <= _s // float _result = _d1 - (1 / x) + (_d2 * x) // if _recursive // _return := _result + (math.pi / math.tan(-math.pi * x)) // break // else // _return := _result // break // else // float _result = 0.0 // while _x < _c // _result -= 1 / _x // _x += 1 // if _x >= _c // float _r = 1 / _x // _result += math.log(_x) - (0.5 * _r) // _r *= _r // _result -= _r * (_s3 - (_r * (_s4 - (_r * (_s5 - (_r * (_s6 - (_r * _s7)))))))) // if _recursive // _return := _result + (math.pi / math.tan(-math.pi * x)) // break // else // _return := _result // break // _return // { usage: // plot(DiGamma(-5 + (bar_index % 1000) * 0.01)) // https://mathworld.wolfram.com/DigammaFunction.html //{ remarks: // This implementation is based on // Jose Bernardo // Algorithm AS 103: // Psi ( Digamma ) Function, // Applied Statistics, // Volume 25, Number 3, 1976, pages 315-317. // Using the modifications as in Tom Minka's lightspeed toolbox. //}}} // This is too heavy for current architecture... // function Computes the inverse Digamma function: this is the inverse of the logarithm of the gamma function. This function will // only return solutions that are positive. // param p float, The argument of the inverse digamma function. // returns float, The positive solution to the inverse DiGamma function at <paramref name="p"/>. // export DiGammaInv (float p) => //{ // if na(p)//(float.IsNaN(p)) // float(na)//return float.NaN; // else if p < -1.0e308//(float.IsNegativeInfinity(p)) // 0.0 // else if p > 1.0e308//(float.IsPositiveInfinity(p)) // 1.0e308//return float.PositiveInfinity; // else // float _x = math.exp(p) // float _d = 1.0 // while _d > 1.0e-15 // _x += _d * math.sign(p - DiGamma(_x)) // _d /= 2.0 // _x //{ usage: //{ remarks: // This implementation is based on the bisection method. //}}}
Matrix_Functions_Lib_JD
https://www.tradingview.com/script/MzXk9K0k-Matrix-Functions-Lib-JD/
Duyck
https://www.tradingview.com/u/Duyck/
23
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jorisduyck //@version=5 library("Matrix_Functions_Lib_JD") //@description This library converts 1D Pine arrays into 2D matrices and provides matrix manupulation and calculation functions. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The arrays provided in Pinescript are linear 1D strucures that can be seen either as a large vertical stack or // a horizontal row containing a list of values, colors, bools,.. // // With the FUNCTIONS in this script the 1D ARRAY LIST can be CONVERTED INTO A 2D MATRIX form // // /////////////////////////////////////////// /// BASIC INFO ON THE MATRIX STRUCTURE: /// /////////////////////////////////////////// // // The matrix is set up as an 2D structure and is devided in ROWS and COLUMNS. // following the standard mathematical notation: // // a 3 x 4 matrix = 4 columns // 0 1 2 3 column index // 0 [a b c d] // 3 rows 1 [e f g h] // 2 [i j k l] // row // index // // With the use of some purpose-built functions, values can be placed or retrieved in a specific column of a certain row // this can be done by intuitively using row_nr and column_nr coördinates, // without having to worry on what exact index of the Pine array this value is located (the functions do these conversions for you) // // // the syntax I propose for the 2D Matrix array has the following structure: // // - the array starts with 2 VALUES describing the DIMENSION INFORMATION, (rows, columns) // these are ignored in the actual calculations and serve as a metadata header (similar to the "location, time,... etc." data that is stored in photo files) // so the array always carries it's own info about the nr. of rows and columns and doesn't need is seperate "info" file! // // To stay consistent with the standard Pinescript (array and [lookback]) indexing: // - indexes for sheets and columns start from 0 (first) and run up to the (total nr of sheets or columns) - 1 // - indexes for rows also start from 0 (most recent, cfr.[lookback]) and run up to the (total nr of rows) - 1 // // - this 2 value metadata header is followed by the actual df data // the actual data array can consist of (100,000 - 2) usable items, // // In a theoretical example, you can have a matrix with almost 20,000 rows with each 5 columns of data (eg. open, high, low, close, volume) in it!!! // /////////////////////////////////// /// SCHEMATIC OF THE STRUCTURE: /// /////////////////////////////////// // ////// (metadata header with dimensions info) // // (0) (1) (array index) // [nr_of_rows/records, nr_of_columns, // // ////// (actual matrix array data) // // 0 1 2 3 column_index // // (2) (3) (4) (5) (array index) // 0 record0_val0, record0_val1, record0_val2, record0_val3, ..., // // (6) (7) (8) (9) (array index) // 1 record1_val0, record1_val1, record1_val2, record1_val3, ..., // // (10) (11) (12) (13) (array index) // 2 record2_val0, record2_val1, record2_val2, record2_val3, ..., // // 3 ... // // row_index // //////////////////////////////////// /// DATA MANIPULATION FUNCTIONS: /// //////////////////////////////////// // // A set of functions are implemented to write info to and retrieve info from the dataframe. // Of course the possibilities are not limited to the functions here, these were written because they were needed for the script! // A whole list of other functions can be easily written for other manipulation purposes. // The ones written in the script are 2D versions of most of the functions that are provided for normal 1D arrays. // // Feel free to use the functions library below in your scripts! A little shoutout would be nice, of course!! // // /////////////////////////////////////////////////////////////////////// /// LIST OF FUNCTIONS contained in this script: /// /// (many other can of course be written, using the same structure) /// /////////////////////////////////////////////////////////////////////// // // - INFO functions // * get the number of COLUMNS // * get the number of ROWS // * get the total SIZE (number of columns, number of rows) // // - INITIALISATION and SET functions (commands to build the 2D matrix) // * MATRIX INITIALISATION function, builds 2D matrix with dimensional metadata/size in first 2 values // // a new matrix array is built (cfr. the conventions I propose above) containing a certain nr of rows and columns // * function to SET a single value in a certain row/lookback period and column // // - GET functions (to retrieve info from the 2D matrix) // * function to GET/retrieve a single VALUE from a certain row/lookback period and column // * function to cut of the metadata header and return the array body (as an array) // * function to GET/retrieve the values from a ROW/RECORD from a certain row/lookback period, the values are returned as an array // // - 1D - 2D COORDINATE CONVERSION FUNCTIONS (handy with for loop indexes) /// // * function to get the ROW INDEX in a 2D matrix from the 1D array index // * function to get the COLUMN INDEX in a 2D matrix from the 1D array index // * function to get (row, column) coordinates in a 2D matrix from the 1D array index // * function to get the 1D array index from (row, column) coordinates in a 2D matrix // // - Matrix MANIPULATION functions // * function to ADD a ROW/RECORD on the TOP of the array, shift the whole list one down and REMOVE the OLDEST row/record // (2D version of "unshift" + "pop" but with a whole row at once) // * function to REMOVE one or more ROWS/RECORDS from a 2D matrix // (if from_row == to_row, only this row is removed) // * function to REMOVE one or more COLUMNS from a 2D matrix // (if from_column == to_column, only this column is removed) // * function to INSERT an ARRAY of ROWS/RECORDS at a certain row number in a 2D matrix // * function to INSERT an ARRAY of COLUMNS at a certain column number in a 2D matrix // * function to APPEND/ADD an ARRAY of ROWS/RECORDS to the BOTTOM of a 2D matrix // * function to APPEND/ADD an ARRAY of COLUMNS to the SIDE of a 2D matrix // * function to POP/REMOVE and return the last ROW/RECORD from the BOTTOM of a 2D matrix // * function to POP/REMOVE and return the last column from the SIDE of a 2D matrix // // - function to print a matrix // This function is mainly used for debugging purposes and displays the array as a 2D matrix notation // // // Enjoy! // JD. // // #NotTradingAdvice #DYOR // // Disclaimer. // I AM NOT A FINANCIAL ADVISOR. // THESE IDEAS ARE NOT ADVICE AND ARE FOR EDUCATION PURPOSES ONLY. // ALWAYS DO YOUR OWN RESEARCH! //} // Function declarations // //{ ///////////////////////////////////////////////////////////////////////////////// /// Matrix Functions /// ///////////////////////////////////////////////////////////////////////////////// //{ /// MATRIX INFO FUNCTIONS /// //{ // @function Returns the number of rows from a 2D matrix export get_nr_of_rows(float[] m) => //{ _rows = int(array.get(m, 0)) _rows //} // @function Returns the number of columns from a 2D matrix export get_nr_of_columns(float[] m) => //{ _columns = int(array.get(m, 1)) _columns //} // @function Returns a tuple with the total number of rows and columns from a 2D matrix export get_size(float[] m) => //{ _rows = int(array.get(m, 0)) _columns = int(array.get(m, 1)) [_rows, _columns] //} //} /// INITIALISATION AND SET FUNCTIONS /// //{ // @function 2D matrix init function, builds a 2D matrix with dimensional metadata in first two values and fills it with a default value, the body of the actual matrix data starts at index 2. export init(int nr_of_rows, int nr_of_columns, float fill = 0) => //{ size = int(nr_of_rows * nr_of_columns) m = array.new_float(size + 2, fill) array.set(m, 0, nr_of_rows), array.set(m, 1, nr_of_columns) m //} // @function 2D matrix init function, builds a 2D matrix from an existing array by adding dimensional metadata in first two values, the body of the actual matrix data consists of the data of the source array and starts at index 2. export from_list(int nr_of_rows, int nr_of_columns, float[] list) => //{ size = int(nr_of_rows * nr_of_columns) m = array.new_float(size + 2, 0) array.set(m, 0, nr_of_rows), array.set(m, 1, nr_of_columns) if array.size(list) <= array.size(m) - 2 for i = 0 to array.size(list) - 1 array.set(m, i + 2, array.get(list, i)) m //} // @function Sets values in 2D matrix with (row index, column index) (index for rows and columns both starts at 0 !!) export set(float[] m, int row_index = 0, int column_index = 0, float val = 0) => //{ _columns = get_nr_of_columns(m) array.set(m, 2 + int((row_index * _columns) + column_index), val) //} // @function Fills all elements in a 2D matrix with a value export fill_val(float[] m, float val = 0) => //{ array.fill(m, val, 2) //} // @function Fills a 2D matrix with random values// export randomize(float[] m, float min_range = 0, float max_range = 1) => //{ [_rows, _columns] = get_size(m) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _rnd_value = math.random(min_range, max_range) set(m, i, j, _rnd_value) m //} //} /// GET FUNCTIONS /// //{ // @function Gets values from 2D matrix with (row index, column index) (index for rows and columns both starts at 0 !!) export get(float[] m, int row_index = 0, int column_index = 0) => //{ _columns = get_nr_of_columns(m) val = array.get(m, 2 + int((row_index * _columns) + column_index)) val //} // @function Cuts off the metadata header and returns the array body, WITHOUT THE DIMENSIONAL METADATA!! // do_slice This variable should be set as: - 'false' to only make a copy, changes to the new array copy will NOT ALTER the ORIGINAL - 'true' to make a slice, changes to the new array slice WILL(!) ALTER the ORIGINAL export copy_slice_body(float[] m, bool do_slice = false) => //{ 'do_slice' variable should be set as: // - 'false' to only make a copy, // changes to the new array copy will NOT ALTER the ORIGINAL // - 'true' to make a slice // changes to the new array slice WILL(!) ALTER the ORIGINAL _matrix_slice = array.slice(m, 2, array.size(m)) _matrix_body = do_slice ? _matrix_slice : array.copy(_matrix_slice) _matrix_body //} // @function Gets /retrieve the values from a ROW/RECORD from a certain row/lookback period, the values are returned as an array export get_record(float[] m, int row_index = 0) => //{ nr_of_columns = get_nr_of_columns(m) _start_index = int(2 + row_index * nr_of_columns) _row_slice = array.slice(m, _start_index , _start_index + nr_of_columns) _record = array.copy(_row_slice) _record //} //} /// 1D - 2D COORDINATE CONVERSION FUNCTIONS (handy with for loop indexes) /// //{ // @function Gets the row nr. in a 2D matrix from 1D index (index for rows and columns both starts at 0 !!) export get_row_index(float[] m, int array_index = 0) => //{ _columns = get_nr_of_columns(m) row_index = int(math.floor(array_index / _columns)) row_index //} // @function Gets the column nr. in a 2D matrix from 1D index (index for rows and columns both starts at 0 !!) export get_column_index(float[] m, int array_index = 0) => //{ _columns = get_nr_of_columns(m) column_index = int(array_index % _columns) column_index //} // @function Gets a tuple with the (row, column) coordinates in 2D matrix from 1D index (index starts at 0 and does not include the header!!) export get_row_column_index(float[] m, int array_index = 0) => //{ _columns = get_nr_of_columns(m) _row = int(math.floor(array_index / _columns)) _column = int( array_index % _columns) [_row, _column] //} // @function Gets the 1D index from (row, column) coordinates in 2D matrix (index for row and column both starts at 0 !! Index starts at 0 and does not include the header!!) export get_array_index(float[] m, int row_index = 0, int column_index = 0) => //{ _columns = get_nr_of_columns(m) array_index = int(row_index * _columns + column_index) array_index //} //} /// MANIPULATION FUNCTIONS /// //{ // @function Removes one or more rows/records from a 2D matrix (if from_row = to_row, only this row is removed) export remove_rows(float[] m, int from_row = 0, int to_row = 0) => //{ [_rows, _columns] = get_size(m) if not(from_row == 0 and to_row == _rows - 1) and not(to_row < from_row) _start_remove_index = 2 + from_row * _columns for i = 1 to (math.min(_rows - 1, to_row) - from_row + 1) * _columns array.remove(m, math.max(_start_remove_index, 2)) array.set(m, 0, _rows - (math.min(_rows - 1, to_row) - from_row) - 1) m //} // @function Remove one or more columns from a 2D matrix (if from_column = to_column, only this column is removed) export remove_columns(float[] m, int from_column = 0, int to_column = 0) => //{ [_rows, _columns] = get_size(m) if not(from_column == 0 and to_column == _columns - 1) and not(to_column < from_column) for _row_nr = (_rows - 1) to 0 _start_remove_index = 2 + _row_nr * _columns + from_column for i = from_column to to_column array.remove(m, math.max(_start_remove_index, 2)) array.set(m, 1, _columns - (math.min(_columns, to_column) - from_column) - 1) m //} // @function Insert an array of rows/records at a certain row number in a 2D matrix export insert_array_of_rows(float[] m, float[] insert_array, int from_row = 0) => //{ [_rows, _columns] = get_size(m) [_rows_insert_array, _columns_insert_array] = get_size(insert_array) _size_insert_array = _columns_insert_array * _rows_insert_array if _columns == _columns_insert_array _insert_array_body = copy_slice_body(insert_array, false) _start_insert_index = 2 + math.min(_rows, from_row) * _columns for index = (_size_insert_array - 1) to 0 array.insert(m, _start_insert_index, array.get(_insert_array_body, index)) array.set(m, 0, _rows + _rows_insert_array) m //} // @function ADDS a ROW/RECORD on the TOP of a sheet, shift the whole list one down and gives the option to REMOVE the OLDEST row/record. (2D version of "unshift" + "pop" but with a whole row at once) export add_row(float[] m, float[] insert_array, bool remove_oldest = true) => //{ insert_array_of_rows(m, insert_array, 0) [_rows, _columns] = get_size(m) if remove_oldest remove_rows(m, _rows - 1, _rows - 1) //} // @function Insert an array of columns at a certain column number in a 2D matrix export insert_array_of_columns(float[] m, float[] insert_array, int from_column = 0) => //{ [_rows, _columns] = get_size(m) [_rows_insert_array, _columns_insert_array] = get_size(insert_array) _size_insert_array = _columns_insert_array * _rows_insert_array if _rows == _rows_insert_array for _row_nr = (_rows - 1) to 0 _start_insert_index = 2 + _row_nr * _columns + math.min(_columns - 1, from_column) for index = 0 to (_columns_insert_array - 1) array.insert(m, math.max(_start_insert_index, 2), array.get(insert_array, int(2 + (_size_insert_array - 1) - index - ((_rows_insert_array - 1) - _row_nr) * _columns_insert_array))) array.set(m, 1, _columns + _columns_insert_array) m //} // @function Appends/adds an array of rows/records to the bottom of a 2D matrix export append_array_of_rows(float[] m, float[] append_array) => //{ [_rows, _columns] = get_size(m) [_rows_append_array, _columns_append_array] = get_size(append_array) if _columns == _columns_append_array _append_array_body = copy_slice_body(append_array, false) array.concat(m, _append_array_body) array.set(m, 0, _rows + _rows_append_array) m //} // @function Appends/adds an array of columns to the right side of a 2D matrix export append_array_of_columns(float[] m, float[] append_array) => //{ [_rows, _columns] = get_size(m) [_rows_append_array, _columns_append_array] = get_size(append_array) _size_append_array = _columns_append_array * _rows_append_array if _rows == _rows_append_array for _row_nr = (_rows - 1) to 0 _start_append_index = 2 + _row_nr * _columns + _columns for index = 0 to (_columns_append_array - 1) array.insert(m, math.max(_start_append_index, 2), array.get(append_array, int(2 + (_size_append_array - 1) - index - ((_rows_append_array - 1) - _row_nr) * _columns_append_array))) array.set(m, 1, _columns + _columns_append_array) m //} // @function Removes / pops and returns the last row/record from a 2D matrix. export pop_row(float[] m) => //{ [_rows, _columns] = get_size(m) _return_array = array.new_float() _start_remove_index = 2 + (_rows - 1) * _columns for i = 1 to _columns array.push(_return_array, array.get(m, math.max(_start_remove_index, 2))) array.remove(m, math.max(_start_remove_index, 2)) array.set(m, 0, _rows - 1) _return_array //} // @function Removes / pops and returns the last (most right) column from a 2D matrix. export pop_column(float[] m) => //{ [_rows, _columns] = get_size(m) _return_array = array.new_float() for _row_nr = (_rows - 1) to 0 _start_remove_index = 2 + _row_nr * _columns + (_columns - 1) array.insert(_return_array, 0, array.get(m, math.max(_start_remove_index, 2))) array.remove(m, math.max(_start_remove_index, 2)) array.set(m, 1, _columns - 1) _return_array //} //} /// CALCULATION FUNCTIONS /// //{ export replace(float[] m, float[] add_m) => //{ [ _rows, _columns] = get_size(m) [_add_rows, _add_columns] = get_size(add_m) if _rows == _add_rows and _columns == _add_columns for i = 0 to _rows - 1 for j = 0 to _columns - 1 add_value = get(add_m, i, j) set(m, i, j, add_value) m //} export abs(float[] m) => //{ [ _rows, _columns] = get_size(m) _abs_m = array.copy(m) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get(_abs_m, i, j) set(_abs_m, i, j, math.abs(_value)) _abs_m //} // @function Returns a new matrix with the same value added to all the elements of the source matrix. export add_value(float[] m, float add_val = 0) => //{ [_rows, _columns] = get_size(m) _return_array = init(_rows, _columns, 0) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get(m, i, j) set(_return_array, i, j, _value + add_val) _return_array //} // @function Returns a new matrix with the of the elements of one 2D matrix added to every corresponding element of a source 2D matrix. export addition(float[] m, float[] add_m) => //{ [ _rows, _columns] = get_size(m) [_add_rows, _add_columns] = get_size(add_m) _return_array = init(_rows, _columns, 0) if _rows == _add_rows and _columns == _add_columns for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get( m, i, j) add_val = get(add_m, i, j) set(_return_array, i, j, _value + add_val) _return_array //} // @function Returns a new matrix with the same value subtracted from every element of a 2D matrix export subtract_value(float[] m, float subtract_val = 0) => //{ [_rows, _columns] = get_size(m) _return_array = init(_rows, _columns, 0) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get(m, i, j) set(_return_array, i, j, _value - subtract_val) _return_array //} // @function Returns a new matrix with the values of the elements of one 2D matrix subtracted from every corresponding element of a source 2D matrix. export subtraction(float[] m, float[] subtract_m) => //{ [ _rows, _columns] = get_size(m) [_subtract_rows, _subtract_columns] = get_size(subtract_m) _return_array = init(_rows, _columns, 0) if _rows == _subtract_rows and _columns == _subtract_columns for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get( m, i, j) subtract_val = get(subtract_m, i, j) set(_return_array, i, j, _value - subtract_val) _return_array //} // @function Returns a new matrix with all the elements of the source matrix scaled/multiplied by a scalar value. export scalar_multipy(float[] m, float scalar = 1) => //{ [_rows, _columns] = get_size(m) _return_array = init(_rows, _columns, 0) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get(m, i, j) set(_return_array, i, j, _value * scalar) _return_array //} // @function Returns a new matrix with the elements of the source matrix transposed. export transpose(float[] m) => //{ [_rows, _columns] = get_size(m) _return_array = init(_columns, _rows, 0) for i = 0 to _rows - 1 for j = 0 to _columns - 1 _value = get(m, i, j) set(_return_array, j, i, _value) _return_array //} // @function Performs ELEMENT WISE MULTIPLICATION of 2D matrices, returns a new matrix c. export multiply_elem(float[] a, float[] b) => //{ [_rows_a, _columns_a] = get_size(a) [_rows_b, _columns_b] = get_size(b) _return_array = init(_rows_a, _columns_a, 0) if _rows_a == _rows_b and _columns_a == _columns_b for i = 0 to _rows_a - 1 for j = 0 to _columns_a - 1 _value_a = get( a, i, j) _value_b = get( b, i, j) set(_return_array, i, j, _value_a * + _value_b) _return_array //} // @function Performs DOT PROCUCT MULTIPLICATION of 2D matrices, returns a new matrix c. export multiply(float[] a, float[] b) => //{ // get matrix metadata // [_a_row, _a_col] = get_size(a), _a_size = _a_row * _a_col [_b_row, _b_col] = get_size(b), _b_size = _b_row * _b_col _c_row = _a_row, _c_col = _b_col , _c_size = _a_row * _b_col _c = init(_a_row, _b_col, 0) // error check // if _a_col != _b_row array.fill(_c, 0) // multiplication // else _a_row_nr = 0, _a_col_nr = 0 _b_row_nr = 0, _b_col_nr = 0 _c_row_nr = 0, _c_col_nr = 0 for i = 0 to (_c_size -1) i_val = 0.0 _c_row_nr := math.floor(i / _b_col) // row_nr := row_nr + ((i % _b_x) == 0 ? 1 : 0) _c_col_nr := i % _b_col for j = 0 to (_a_col - 1) _a_row_nr := _c_row_nr , _a_col_nr := j % _a_col _b_row_nr := j % _a_col , _b_col_nr := _c_col_nr i_val := i_val + get(a, _a_row_nr, _a_col_nr) * get(b, _b_row_nr, _b_col_nr) array.set(_c, 2 + i, i_val) // return // _c //} // Matrix Determinants // //{ // @function Calculates the determinant of 2x2 matrices. export determinant_2x2(float[] m) => //{ [_rows, _columns] = get_size(m) var float _determinant = na // error check // if _rows == _columns and _rows == 2 // matrix form: // |a b| // det: | | = a * d - c * b // |c d| a = get(m, 0, 0), b = get(m, 0, 1) _c = get(m, 1, 0), _d = get(m, 1, 1) _determinant := a * _d - _c * b _determinant // @function Calculates the determinant of 3x3 matrices. export determinant_3x3(float[] m) => //{ [_rows, _columns] = get_size(m) var float _determinant = na // error check // if _rows == _columns and _rows == 3 // matrix form: // |a b c| // det: |d e f| = a * e * i + b * f * g + c * d * h - g * e * c - d * b * i - a * h * f // |g h i| _determinant := 0.0 for i = 0 to _columns - 1 _cofactor_matrix = array.copy(m) remove_rows( _cofactor_matrix, 0, 0) remove_columns(_cofactor_matrix, i, i) _determinant := _determinant + math.pow(-1, i + 1) * get(m, 0, i) * determinant_2x2(_cofactor_matrix) _determinant //} //} // @function Calculates the determinant of 4x4 matrices. export determinant_4x4(float[] m) => //{ [_rows, _columns] = get_size(m) var float _determinant = na // error check // if _rows == _columns and _rows == 4 _determinant := 0.0 for i = 0 to _columns - 1 _cofactor_matrix = array.copy(m) remove_rows( _cofactor_matrix, 0, 0) remove_columns(_cofactor_matrix, i, i) _determinant := _determinant + math.pow(-1, i + 1) * get(m, 0, i) * determinant_3x3(_cofactor_matrix) _determinant //} //} //} // @function displays a 2D matrix in a table layout. export print(float[] m, int rows = na, int columns = na, string pos = "top_right", color bg_color = color.teal, color text_color = color.black, string str_format = "##,###.##", string text_size = size.normal, string title = "matrix") => //{ [_rows, _columns] = get_size(m) if not na(rows) _rows := rows _columns := columns var matrix_print = table.new(pos, _columns + 4, _rows + 2, bgcolor = bg_color) table.cell(matrix_print, 0, 0, text = title, text_size = text_size) table.cell(matrix_print, _columns + 3, 1, " ", text_size = text_size) for i = 1 to _rows table.cell(matrix_print, 1, i, "[", text_size = text_size) table.cell(matrix_print, _columns + 2, i, "]", text_size = text_size) if i > 0 and i < _rows + 1 for j = 0 to _columns - 1 table.cell(matrix_print, j + 2, i, (not na(rows) ? str.tostring(array.get(m, (i - 1) * _columns + j), str_format) : str.tostring(get(m, i - 1, j), str_format)), text_size = text_size) table.cell_set_text_color(matrix_print, j + 1, i + 1, text_color) //} //} //} /// test section /// // set test matrices //{ a = from_list(3, 4, array.from( 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34)) b = array.copy(a) // array to test add row functions insert_row = from_list( 1, 4, array.from( 10, 20, 30, 40)) // array to test insert/append row functions insert_row_array = from_list(2, 4, array.from( 10, 20 ,30, 40, 50, 60, 70, 80)) // array to test add column functions insert_column = from_list(3, 1, array.from( 10, 20, 30, 40)) // array to test insert/append column functions insert_column_array = from_list(3, 2, array.from( 10, 20, 30, 40, 50, 60)) // array to test element wise multiplication function elem_multiplication_array = from_list(3, 4, array.from( 10, 20 ,30, 40, 20, 30, 40, 50, 30, 40, 50, 60)) // array to test multiplication function multiplication_array = from_list(4, 2, array.from( 2, 3, 2, 3, 2, 3, 2, 3)) // array to test determinant function determinant_array = from_list(4, 4, array.from( 4, 3, 2, 2, 0, 1,-3, 3, 0,-1, 3, 3, 0, 3, 1, 1)) //} // parameters to check behavior of functions //{ x = input.int(0, title="from") y = input.int(0, title="to (to chose only 1 row or column, set the same value for 'from' and 'to')") c_type = input.string("none", title = "result matrix", options = ["none", "add rows to top and shift list", "get row/record from list", "remove array of rows", "remove array of columns", "insert array of rows", "insert array of columns", "append array of rows", "append array of columns", "pop last row" , "pop last column", "element multiplication", "matrix multiplication", "matrix transposition", "matrix determinant"]) //} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// test function calls /// // /////////////////////////// // // // almost all functions can be called with or without a return array // // // for example, both notations below can be used: // // // // c = append_array_of_rows(a, append_array) -> returns the appended matrix as array "c" // // // // append_array_of_rows(a, append_array) -> just runs the function without creating a new array "c" // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// manipulation_array = c_type == "add rows to top and shift list" ? insert_row : c_type == "remove array of rows" ? insert_row_array : c_type == "remove array of columns" ? insert_column_array : c_type == "insert array of rows" ? insert_row_array : c_type == "insert array of columns" ? insert_column_array : c_type == "append array of rows" ? insert_row_array : c_type == "append array of columns" ? insert_column_array : c_type == "element multiplication" ? elem_multiplication_array : c_type == "matrix multiplication" ? multiplication_array : insert_row c = c_type == "add rows to top and shift list" ? add_row(a, manipulation_array) : c_type == "remove array of rows" ? remove_rows(a, x, y) : c_type == "remove array of columns" ? remove_columns(a, x, y) : c_type == "insert array of rows" ? insert_array_of_rows(a, manipulation_array, x) : c_type == "insert array of columns" ? insert_array_of_columns(a, manipulation_array, x) : c_type == "append array of rows" ? append_array_of_rows(a, manipulation_array) : c_type == "append array of columns" ? append_array_of_columns(a, manipulation_array) : c_type == "element multiplication" ? multiply_elem(a, manipulation_array) : c_type == "matrix multiplication" ? multiply(a, manipulation_array) : c_type == "matrix transposition" ? transpose(a) : c_type == "matrix determinant" ? determinant_array : array.copy(a) e = c_type == "get row/record from list" ? get_record(a, x) : c_type == "pop last row" ? pop_row(a) : c_type == "pop last column" ? pop_column(a) : array.copy(a) // plot matrices //{ // copy of original matrix before "manipulation" if c_type != "matrix determinant" if barstate.isfirst print(b, pos = "middle_left", bg_color = color.teal, text_color = color.black, str_format = "#,###.##", text_size = size.normal, title = "original") // "manipulation" matrix if c_type != "remove array of rows" and c_type != "remove array of columns" and c_type != "get row/record from list" and c_type != "pop last row" and c_type != "pop last column" and c_type != "matrix transposition" and c_type != "matrix determinant" or c_type == "add rows to top and shift list" if barstate.isfirst print(manipulation_array, pos = "top_center", bg_color = color.teal, text_color = color.black, str_format = "#,###.##", text_size = size.normal, title = "work array") // original matrix if c_type != "matrix multiplication" and c_type != "element multiplication" and c_type != "matrix determinant" and c_type != "matrix transposition" if barstate.isfirst print(a, pos = "bottom_left", bg_color = color.teal, text_color = color.black, str_format = "#,###.##", text_size = size.normal, title = "modified original") // function title from = " (from = " + str.tostring(x) from_to = from + " -> to = " + str.tostring(y) + " )" title_txt = c_type + (c_type == "remove array of rows" or c_type == "remove array of columns" ? from_to : c_type == "insert array of rows" or c_type == "insert array of columns" or c_type == "get row/record from list" ? from + " )" : c_type == "matrix determinant" ? " det = " + str.tostring(determinant_4x4(determinant_array)) : "") if barstate.isfirst title_tab = table.new("bottom_center", 1, 1, bgcolor = color.orange) table.cell(title_tab, 0, 0, text = title_txt, text_color = color.black, text_size = size.large) // copy of resulting matrix if c_type != "get row/record from list" and c_type != "pop last row" and c_type != "pop last column" or c_type == "add rows to top and shift list" if barstate.isfirst print(c, pos = "middle_center", bg_color = color.teal, text_color = color.black, str_format = "#,###.##", text_size = size.normal, title = c_type == "matrix determinant" ? "original" : "result array") // copy of resulting matrix if c_type == "get row/record from list" or c_type == "pop last row" or c_type == "pop last column" and c_type != "matrix determinant" if barstate.isfirst result = array.copy(e) array.unshift(result, c_type == "pop last row" or c_type == "get row/record from list"? array.size(e) : 1) array.unshift(result, c_type == "pop last row" or c_type == "get row/record from list"? 1 : array.size(e)) print(result, pos ="middle_center", bg_color = color.teal, text_color = color.black, str_format = "#,###.##", text_size = size.normal, title = "result array") //}
RS
https://www.tradingview.com/script/ZGGKyBA5-RS/
bharatTrader
https://www.tradingview.com/u/bharatTrader/
181
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © bharatTrader //@version=5 // @description Utility methods for Relative Strength analysis library("RS") // @function Simple ratio of symbol vs benchmark // @param symbol to be compared // @param benchmark to be compared // @returns ratio of symbol to benchmark export ratio(float symbol, float benchmark) => symbol / benchmark // @function Simple spread of symbol vs benchmark // @param symbol to be compared // @param benchmark to be compared // @returns spread of symbol to benchmark export spread(float symbol, float benchmark) => symbol - benchmark // @function Simple add of symbol and benchmark // @param symbol to be compared // @param benchmark to be compared // @returns join of symbol to benchmark export join(float symbol, float benchmark) => symbol + benchmark // @function Relative strength comparison between two offsets // @param symbol to be compared // @param benchmark to be compared // @param offset1 starting offset, must be greater than offset 2 // @param offset2 starting offset, must be less than offset 1, default is current candle // @returns performance in percentage between the 2 offset. A value greater than 0 indicates outperformance, less than 0 indicates underperformance export atOffset(float symbol, float benchmark, int offset1, int offset2 = 0) => symbolRatio = symbol[offset2]/symbol[offset1] benchmarkRatio = benchmark[offset2]/benchmark[offset1] (symbolRatio / benchmarkRatio) - 1 // @function Equilibrium price - The price as per today's symbol and benchmark close, that will make the symbol to perform equal to benchmark // @param symbol to be compared // @param benchmark to be compared // @param offset to measure under/out performance // @returns Price - This is the price if achieved will make the symbol perform equally w.r.t. benchmark on the offset bar export equilibriumPrice(float symbol, float benchmark, int offset) => (benchmark * symbol[offset])/benchmark[offset] // @function Relative Strength performance crossed over/under specified threshold // @param symbol to be compared // @param benchmark to be compared // @param offset to measure under/out performance // @param threshold threshold set for alert // @returns 1/0/-1. 1 - crossover, 0 - no signal, -1 crossunder export thresholdCrossed(float symbol, float benchmark, int offset, float threshold) => r = atOffset(symbol, benchmark, offset) xover = ta.crossover(r, threshold) xunder = ta.crossunder(r, threshold) val = xover ? 1 : xunder ? -1 : 0 val // @function Return the percentage outperformance of the ratio from offset1 to offset2 along with percentage symbol price change // @param symbol to be compared // @param benchmark to be compared // @param offset1 starting offset, must be greater than offset 2 // @param offset2 starting offset, must be less than offset 1, default is current candle // @returns deltacrs deltaprice as a 2 element array export deltaCRSAndPrice(float symbol, float benchmark, int offset1, int offset2) => r1 = ratio(symbol[offset1], benchmark[offset1]) r2 = ratio(symbol[offset2], benchmark[offset2]) deltaCRS = (r2 - r1)/r1 * 100 deltaPrice = (symbol[offset2] - symbol[offset1]) / symbol[offset1] * 100 [deltaCRS, deltaPrice] //Usage benchmark = request.security("NSE:NIFTY", "",close) symbol = close hline(0, color=color.fuchsia) plot(atOffset(symbol, benchmark, 157))
bursamalaysianonshariah
https://www.tradingview.com/script/O5ADBRCt-bursamalaysianonshariah/
BURSATRENDBANDCHART
https://www.tradingview.com/u/BURSATRENDBANDCHART/
35
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © BURSATRENDBANDCHART //@version=5 // @description : Update 27 DEC 2022 ! List of Shariah stock for Bursa Malaysia library("bursamalaysianonshariah", overlay = true) // @function : To get current ticker Shariah status // @param : no parameter required // @returns : status() will return 0 if in the list (shariah), 1 if not in the list (non-shariah) and 2 if ticker not from Bursa Malaysia export status() => a = array.new_string() array.push(a,"3A") array.push(a,"AASIA") array.push(a,"AAX") array.push(a,"ABLEGLOB") array.push(a,"ABLEGRP") array.push(a,"ACME") array.push(a,"ACME-WA") array.push(a,"ACO") array.push(a,"ADVCON") array.push(a,"ADVENTA") array.push(a,"ADVPKG") array.push(a,"AEMULUS") array.push(a,"AEON") array.push(a,"AFUJIYA") array.push(a,"AGES") array.push(a,"AHB") array.push(a,"AHEALTH") array.push(a,"AIMFLEX") array.push(a,"AIRASIA") array.push(a,"AJI") array.push(a,"AJIYA") array.push(a,"ALAM") array.push(a,"ALAM-WA") array.push(a,"ALAQAR") array.push(a,"ALSREIT") array.push(a,"AME") array.push(a,"AME-WA") array.push(a,"AMLEX") array.push(a,"AMPROP") array.push(a,"AMTEL") array.push(a,"AMTEL-WA") array.push(a,"AMWAY") array.push(a,"ANCOMNY") array.push(a,"ANCOMNY-WB") array.push(a,"ANCOMLB") array.push(a,"ANEKA") array.push(a,"ANNJOO") array.push(a,"ANNUM") array.push(a,"ANZO") array.push(a,"ANZO-WB") array.push(a,"APB") array.push(a,"APM") array.push(a,"APOLLO") array.push(a,"ARANK") array.push(a,"ARBB") array.push(a,"ARK") array.push(a,"ARTRONIQ") array.push(a,"ASDION") array.push(a,"ASIABRN") array.push(a,"ASIAPAC") array.push(a,"ASIAPLY") array.push(a,"ASTINO") array.push(a,"AT") array.push(a,"AT-WC") array.push(a,"ATAIMS") array.push(a,"ATTA") array.push(a,"ATTA-WB") array.push(a,"ATTA-WC") array.push(a,"ATECH") array.push(a,"AURORA") array.push(a,"AVI") array.push(a,"AWANTEC") array.push(a,"AWANTEC-WA") array.push(a,"AWC") array.push(a,"AWC-WA") array.push(a,"AXIATA") array.push(a,"AXREIT") array.push(a,"AXTERIA") array.push(a,"AXTERIA-WA") array.push(a,"AYER") array.push(a,"AYS") array.push(a,"AZRB") array.push(a,"AZRB-WA") array.push(a,"BABA") array.push(a,"BAHVEST") array.push(a,"BAHVEST-WA") array.push(a,"BARAKAH") array.push(a,"BAUTO") array.push(a,"BCB") array.push(a,"BDB") array.push(a,"BERTAM") array.push(a,"BHIC") array.push(a,"BIG") array.push(a,"BIMB") array.push(a,"BIMB-WA") array.push(a,"BINACOM") array.push(a,"BINTAI") array.push(a,"BIOHLDG") array.push(a,"BIOHLDG-WA") array.push(a,"BIPORT") array.push(a,"BJFOOD") array.push(a,"BKAWAN") array.push(a,"BLDPLNT") array.push(a,"BOILERM") array.push(a,"BONIA") array.push(a,"BORNOIL") array.push(a,"BORNOIL-WC") array.push(a,"BORNOIL-WD") array.push(a,"BPLANT") array.push(a,"BPPLAS") array.push(a,"BPURI") array.push(a,"BPURI-WA") array.push(a,"BRAHIMS") array.push(a,"BSLCORP") array.push(a,"BTECH") array.push(a,"BTM") array.push(a,"BTM-WB") array.push(a,"BURSA") array.push(a,"BVLH") array.push(a,"CAB") array.push(a,"CABNET") array.push(a,"CLASSITA") array.push(a,"CAMRES") array.push(a,"CAREPLS") array.push(a,"CARIMIN") array.push(a,"CBIP") array.push(a,"CCK") array.push(a,"CCK-WA") array.push(a,"CEKD") array.push(a,"CENSOF") array.push(a,"CEPAT") array.push(a,"CEPCO") array.push(a,"CETECH") array.push(a,"CGB") array.push(a,"CHGP") array.push(a,"CHGP-WA") array.push(a,"CHHB") array.push(a,"CHHB-WB") array.push(a,"CHINHIN") array.push(a,"CHINWEL") array.push(a,"CHOOBEE") array.push(a,"CHUAN") array.push(a,"CIHLDG") array.push(a,"CJCEN") array.push(a,"CLOUD") array.push(a,"CME") array.push(a,"CME-WA") array.push(a,"CMSB") array.push(a,"CNH") array.push(a,"COCOLND") array.push(a,"COMFORT") array.push(a,"COMFORT-WB") array.push(a,"COMPUGT") array.push(a,"CRESBLD") array.push(a,"CRESNDO") array.push(a,"CRG") array.push(a,"CSCENIC") array.push(a,"CSCENIC-WA") array.push(a,"CSCSTEL") array.push(a,"CTIB") array.push(a,"CTOS") array.push(a,"CUSCAPI") array.push(a,"CVIEW") array.push(a,"CWG") array.push(a,"CYL") array.push(a,"CYPARK") array.push(a,"D&O") array.push(a,"SCIPACK") array.push(a,"SCIPACK-WB") array.push(a,"DANCO") array.push(a,"DANCO-WA") array.push(a,"DATAPRP") array.push(a,"DAYANG") array.push(a,"DBHD") array.push(a,"DESTINI") array.push(a,"DFCITY") array.push(a,"DIALOG") array.push(a,"DIGI") array.push(a,"DKLS") array.push(a,"DKSH") array.push(a,"DLADY") array.push(a,"DNEX") array.push(a,"DNONCE") array.push(a,"DOMINAN") array.push(a,"DPHARMA") array.push(a,"DPS") array.push(a,"DPS-WB") array.push(a,"DRBHCOM") array.push(a,"DSONIC") array.push(a,"DSONIC-WA") array.push(a,"DUFU") array.push(a,"INGENIEU") array.push(a,"INGENIEU-WA") array.push(a,"E&O") array.push(a,"MBRIGHT") array.push(a,"MBRIGHT-WB") array.push(a,"EATECH") array.push(a,"ECOFIRS") array.push(a,"ECOFIRS-WD") array.push(a,"ECOHLDS") array.push(a,"ECONBHD") array.push(a,"ECONBHD-WA") array.push(a,"ECOWLD") array.push(a,"ECOWLD-WA") array.push(a,"EDARAN") array.push(a,"EDEN") array.push(a,"EDGENTA") array.push(a,"EDUSPEC") array.push(a,"EDUSPEC-WB") array.push(a,"EFORCE") array.push(a,"EG") array.push(a,"EIG") array.push(a,"EITA") array.push(a,"EITA-WA") array.push(a,"EKOVEST") array.push(a,"ELSOFT") array.push(a,"EMETALL") array.push(a,"EMICO") array.push(a,"ENCORP") array.push(a,"ENEST") array.push(a,"ENGKAH") array.push(a,"ENGKAH-WB") array.push(a,"ENGTEX") array.push(a,"ENGTEX-WB") array.push(a,"ENRA") array.push(a,"ENRA-WA") array.push(a,"EPMB") array.push(a,"ESAFE") array.push(a,"EUPE") array.push(a,"EURO") array.push(a,"EUROSP") array.push(a,"EVERGRN") array.push(a,"EWEIN") array.push(a,"EWEIN-WB") array.push(a,"EWINT") array.push(a,"EWINT-WA") array.push(a,"F&N") array.push(a,"FAJAR") array.push(a,"FAREAST") array.push(a,"FAVCO") array.push(a,"FBBHD") array.push(a,"FGV") array.push(a,"FIAMMA") array.push(a,"FIHB") array.push(a,"FIMACOR") array.push(a,"FITTERS") array.push(a,"FLEXI") array.push(a,"FOCUSP") array.push(a,"FPGROUP") array.push(a,"FPI") array.push(a,"FM") array.push(a,"FRONTKN") array.push(a,"FRONTKN-WB") array.push(a,"FSBM") array.push(a,"FSBM-WA") array.push(a,"G3") array.push(a,"G3-WA") array.push(a,"GADANG") array.push(a,"GADANG-WB") array.push(a,"GAMUDA") array.push(a,"GASMSIA") array.push(a,"GBGAQRS") array.push(a,"GBGAQRS-WB") array.push(a,"GCAP") array.push(a,"GCB") array.push(a,"GCB-WB") array.push(a,"GDB") array.push(a,"GDB-WA") array.push(a,"GDEX") array.push(a,"GDEX-WC") array.push(a,"GENETEC") array.push(a,"GENP") array.push(a,"ONEGLOVE") array.push(a,"GFM") array.push(a,"GFM-WC") array.push(a,"GHLSYS") array.push(a,"GIIB") array.push(a,"GIIB-WA") array.push(a,"GKENT") array.push(a,"GLBHD") array.push(a,"GLOMAC") array.push(a,"GLOTEC") array.push(a,"GLOTEC-WA") array.push(a,"GMUTUAL") array.push(a,"GOB") array.push(a,"GOLDETF") array.push(a,"GOPENG") array.push(a,"GPHAROS") array.push(a,"GPP") array.push(a,"GREATEC") array.push(a,"GREENYB") array.push(a,"GTRONIC") array.push(a,"GUH") array.push(a,"HAILY") array.push(a,"HANDAL") array.push(a,"HARBOUR") array.push(a,"HARNLEN") array.push(a,"HARNLEN-WB") array.push(a,"HARTA") array.push(a,"HCK") array.push(a,"HCK-WA") array.push(a,"HENGYUAN") array.push(a,"HEVEA") array.push(a,"HEXIND") array.push(a,"HEXIND-OR") array.push(a,"HEXIND-WA") array.push(a,"HEXTAR") array.push(a,"HHGROUP") array.push(a,"HHGROUP-WA") array.push(a,"HHHCORP") array.push(a,"HIAPTEK") array.push(a,"HIBISCS") array.push(a,"HIGHTEC") array.push(a,"HIL") array.push(a,"HIL-WB") array.push(a,"HLIND") array.push(a,"HOHUP") array.push(a,"HOMERIZ") array.push(a,"HOMERIZ-WB") array.push(a,"HOMERIZ-WC") array.push(a,"HONGSENG") array.push(a,"HONGSENG-WA") array.push(a,"PTT") array.push(a,"HPMT") array.push(a,"HPPHB") array.push(a,"HSL") array.push(a,"HSPLANT") array.push(a,"HSSEB") array.push(a,"HSSEB-WA") array.push(a,"HTPADU") array.push(a,"HUAYANG") array.push(a,"HUBLINE") array.push(a,"HUBLINE-WC") array.push(a,"HUPSENG") array.push(a,"HWATAI") array.push(a,"HWGB") array.push(a,"IBRACO") array.push(a,"ICON") array.push(a,"ICON-WA") array.push(a,"ICONIC") array.push(a,"IDEAL") array.push(a,"IFCAMSC") array.push(a,"IHH") array.push(a,"IJM") array.push(a,"IMASPRO") array.push(a,"INARI") array.push(a,"INCKEN") array.push(a,"ZENTECH") array.push(a,"INNATURE") array.push(a,"INNO") array.push(a,"INTA") array.push(a,"INTA-WA") array.push(a,"IOICORP") array.push(a,"JSB") array.push(a,"IQGROUP") array.push(a,"IQZAN") array.push(a,"IREKA") array.push(a,"IRIS") array.push(a,"ITRONIC") array.push(a,"IVORY") array.push(a,"IWCITY") array.push(a,"JADEM") array.push(a,"JADI") array.push(a,"JAG") array.push(a,"JAKS") array.push(a,"JAKS-WB") array.push(a,"JAKS-WC") array.push(a,"JAYCORP") array.push(a,"JCY") array.push(a,"JETSON") array.push(a,"JHM") array.push(a,"JIANKUN") array.push(a,"JIANKUN-WA") array.push(a,"JISHAN") array.push(a,"JKGLAND") array.push(a,"JTIASA") array.push(a,"K1") array.push(a,"K1-WC") array.push(a,"KAB") array.push(a,"KAB-WA") array.push(a,"KAMDAR") array.push(a,"KANGER") array.push(a,"KANGER-WB") array.push(a,"KAREX") array.push(a,"KARYON") array.push(a,"KAWAN") array.push(a,"KEINHIN") array.push(a,"KEN") array.push(a,"KERJAYA") array.push(a,"KERJAYA-WB") array.push(a,"KESM") array.push(a,"KFIMA") array.push(a,"KGB") array.push(a,"KGB-WB") array.push(a,"KGROUP") array.push(a,"KGROUP-WC") array.push(a,"KHIND") array.push(a,"KHJB") array.push(a,"KIALIM") array.push(a,"KIMHIN") array.push(a,"KIMLUN") array.push(a,"KIMLUN-WA") array.push(a,"KKB") array.push(a,"KLCC") array.push(a,"KLK") array.push(a,"KMLOONG") array.push(a,"KMLOONG-WB") array.push(a,"KNUSFOR") array.push(a,"KOBAY") array.push(a,"KOMARK") array.push(a,"KOMARK-WC") array.push(a,"KOSSAN") array.push(a,"KOTRA") array.push(a,"KPJ") array.push(a,"RENEUCO") array.push(a,"RENEUCO-WA") array.push(a,"KPPROP") array.push(a,"KPS") array.push(a,"KPSCB") array.push(a,"KRETAM") array.push(a,"KRONO") array.push(a,"KSL") array.push(a,"KSSC") array.push(a,"KUB") array.push(a,"KYM") array.push(a,"L&G") array.push(a,"LAGENDA") array.push(a,"LAGENDA-WB") array.push(a,"RKI") array.push(a,"LAYHONG") array.push(a,"LAYHONG-WA") array.push(a,"LBALUM") array.push(a,"LBS") array.push(a,"LCTITAN") array.push(a,"LEBTECH") array.push(a,"LEESK") array.push(a,"LIIHEN") array.push(a,"LIONIND") array.push(a,"LIONPSIM") array.push(a,"LITRAK") array.push(a,"LKL") array.push(a,"LOTUS") array.push(a,"LOTUS-WB") array.push(a,"LSTEEL") array.push(a,"LTKM") array.push(a,"LUXCHEM") array.push(a,"LYC") array.push(a,"XOXTECH") array.push(a,"MAGNA") array.push(a,"MAGNI") array.push(a,"MAHSING") array.push(a,"MALAKOF") array.push(a,"MALTON") array.push(a,"MASTEEL") array.push(a,"MASTEEL-OR") array.push(a,"MASTER") array.push(a,"MATRIX") array.push(a,"MAXIM") array.push(a,"MAXIS") array.push(a,"MBL") array.push(a,"MBL-WA") array.push(a,"MBMR") array.push(a,"MCEHLDG") array.push(a,"MCEMENT") array.push(a,"MCLEAN") array.push(a,"MCOM") array.push(a,"MCT") array.push(a,"MEDIAC") array.push(a,"MEGASUN") array.push(a,"MELATI") array.push(a,"MELEWAR") array.push(a,"MELEWAR-WB") array.push(a,"MENANG") array.push(a,"MENTIGA") array.push(a,"MERCURY") array.push(a,"MERIDIAN") array.push(a,"MERIDIAN-WB") array.push(a,"MERIDIAN-WC") array.push(a,"MESB") array.push(a,"MESB-WA") array.push(a,"MESTRON") array.push(a,"MESTRON-WA") array.push(a,"METFSID") array.push(a,"METFUS50") array.push(a,"MFCB") array.push(a,"MFGROUP") array.push(a,"MFLOUR") array.push(a,"MFLOUR-WC") array.push(a,"MGB") array.push(a,"MGRC") array.push(a,"MHB") array.push(a,"MHC") array.push(a,"MHCARE") array.push(a,"MI") array.push(a,"MICROLN") array.push(a,"MIECO") array.push(a,"MIKROMB") array.push(a,"MILUX") array.push(a,"MINDA") array.push(a,"MINETEC") array.push(a,"MINHO") array.push(a,"MISC") array.push(a,"MITRA") array.push(a,"MITRA-WE") array.push(a,"MJPERAK") b = array.new_string() array.push(b,"MKH") array.push(b,"MKLAND") array.push(b,"MMAG") array.push(b,"MMAG-WB") array.push(b,"MMCCORP") array.push(b,"MMIS") array.push(b,"MMSV") array.push(b,"MOBILIA") array.push(b,"MPAY") array.push(b,"MPCORP") array.push(b,"MPI") array.push(b,"MPSOL") array.push(b,"MPSOL-WA") array.push(b,"MQTECH") array.push(b,"MQTECH-WA") array.push(b,"MRCB") array.push(b,"MRCB-WB") array.push(b,"MRDIY") array.push(b,"MSM") array.push(b,"MSNIAGA") array.push(b,"MTRONIC") array.push(b,"MTRONIC-WA") array.push(b,"MUDA") array.push(b,"MUH") array.push(b,"MUHIBAH") array.push(b,"MUIPROP") array.push(b,"MYCRON") array.push(b,"MYCRON-WA") array.push(b,"MYEG") array.push(b,"MYETFDJ") array.push(b,"MYETFID") array.push(b,"N2N") array.push(b,"N2N-WB") array.push(b,"NADIBHD") array.push(b,"NAIM") array.push(b,"NATWIDE") array.push(b,"NCT") array.push(b,"NESTCON") array.push(b,"NESTLE") array.push(b,"NEXGRAM") array.push(b,"NEXGRAM-WA") array.push(b,"NEXGRAM-WB") array.push(b,"NEXGRAM-WC") array.push(b,"NGGB") array.push(b,"NHFATT") array.push(b,"NICE") array.push(b,"NICE-WB") array.push(b,"NIHSIN") array.push(b,"NIHSIN-WB") array.push(b,"NOTION") array.push(b,"NOTION-WC") array.push(b,"NOVAMSC") array.push(b,"NPC") array.push(b,"NPS") array.push(b,"NWP") array.push(b,"NYLEX") array.push(b,"OCB") array.push(b,"OCK") array.push(b,"OCK-WB") array.push(b,"OCNCASH") array.push(b,"OCR") array.push(b,"OCR-WD") array.push(b,"OFI") array.push(b,"OIB") array.push(b,"OIB-WA") array.push(b,"OKA") array.push(b,"OMESTI") array.push(b,"OMESTI-WC") array.push(b,"OPCOM") array.push(b,"OPTIMAX") array.push(b,"ALRICH") array.push(b,"ALRICH-WA") array.push(b,"ORNA") array.push(b,"OVH") array.push(b,"OWG") array.push(b,"OWG-WA") array.push(b,"OWG-WB") array.push(b,"PA") array.push(b,"PA-WB") array.push(b,"PADINI") array.push(b,"PANTECH") array.push(b,"PANTECH-WB") array.push(b,"PAOS") array.push(b,"PAOS-WA") array.push(b,"PARAGON") array.push(b,"PARAMON") array.push(b,"PARAMON-WA") array.push(b,"PARKSON") array.push(b,"PASDEC") array.push(b,"PASDEC-WA") array.push(b,"PASUKGB") array.push(b,"PASUKGB-WA") array.push(b,"PBA") array.push(b,"PCCS") array.push(b,"PCCS-WA") array.push(b,"PCHEM") array.push(b,"PDZ") array.push(b,"PDZ-OR") array.push(b,"PDZ-WB") array.push(b,"PEB") array.push(b,"PECCA") array.push(b,"PELIKAN") array.push(b,"PENERGY") array.push(b,"PENTA") array.push(b,"PERDANA") array.push(b,"PERMAJU") array.push(b,"PERMAJU-WA") array.push(b,"PESONA") array.push(b,"PESTECH") array.push(b,"PETDAG") array.push(b,"PETGAS") array.push(b,"PETRONM") array.push(b,"PGLOBE") array.push(b,"PHARMA") array.push(b,"PHB") array.push(b,"PHB-WB") array.push(b,"PICORP") array.push(b,"PIE") array.push(b,"PJBUMI") array.push(b,"PJBUMI-WA") array.push(b,"PLB") array.push(b,"PLENITU") array.push(b,"PLS") array.push(b,"PLS-WA") array.push(b,"PMBTECH") array.push(b,"PMBTECH-WA") array.push(b,"PMETAL") array.push(b,"PMHLDG") array.push(b,"PNEPCB") array.push(b,"PNEPCB-WA") array.push(b,"PNEPCB-WB") array.push(b,"POHKONG") array.push(b,"PGF") array.push(b,"POS") array.push(b,"PPB") array.push(b,"PPHB") array.push(b,"PRESTAR") array.push(b,"PRIVA") array.push(b,"PRLEXUS") array.push(b,"PRLEXUS-WB") array.push(b,"PRTASCO") array.push(b,"PRTASCO-WA") array.push(b,"PTARAS") array.push(b,"PTRANS") array.push(b,"PTRANS-WB") array.push(b,"PUC") array.push(b,"PUC-WA") array.push(b,"PUNCAK") array.push(b,"PWF") array.push(b,"PWORTH") array.push(b,"PWROOT") array.push(b,"PWROOT-WA") array.push(b,"PWRWELL") array.push(b,"QES") array.push(b,"QL") array.push(b,"QUALITY") array.push(b,"RALCO") array.push(b,"RANHILL") array.push(b,"RESINTC") array.push(b,"REVENUE") array.push(b,"REVENUE-WA") array.push(b,"REX") array.push(b,"RGTBHD") array.push(b,"RGTBHD-WB") array.push(b,"RGTECH") array.push(b,"RL") array.push(b,"RL-WA") array.push(b,"ROHAS") array.push(b,"RSAWIT") array.push(b,"RVIEW") array.push(b,"S&FCAP") array.push(b,"S&FCAP-WC") array.push(b,"SALCON") array.push(b,"SALCON-WB") array.push(b,"SALUTE") array.push(b,"SAM") array.push(b,"SAMAIDEN") array.push(b,"SAMAIDEN-WA") array.push(b,"SAPIND") array.push(b,"SAPNRG") array.push(b,"SAPNRG-WA") array.push(b,"SAPRES") array.push(b,"SASBADI") array.push(b,"SAUDEE") array.push(b,"SAUDEE-WB") array.push(b,"SBCCORP") array.push(b,"SCABLE") array.push(b,"SCBUILD") array.push(b,"SCGM") array.push(b,"SCIB") array.push(b,"SCIB-WB") array.push(b,"SCIENTX") array.push(b,"SCIENTX-WC") array.push(b,"SCNWOLF") array.push(b,"SCNWOLF-WA") array.push(b,"SCOMNET") array.push(b,"SCOMNET-WA") array.push(b,"SCOPE") array.push(b,"SDRED") array.push(b,"SDS") array.push(b,"SEACERA") array.push(b,"SEAL") array.push(b,"SEALINK") array.push(b,"SEDANIA") array.push(b,"SEEHUP") array.push(b,"SEERS") array.push(b,"SEG") array.push(b,"SENDAI") array.push(b,"SENDAI-WA") array.push(b,"SERBADK") array.push(b,"SERBADK-WA") array.push(b,"SERNKOU") array.push(b,"SERNKOU-WA") array.push(b,"SERSOL") array.push(b,"SERSOL-WA") array.push(b,"SGBHD") array.push(b,"SHCHAN") array.push(b,"SHH") array.push(b,"SIGN") array.push(b,"SIME") array.push(b,"SIMEPLT") array.push(b,"SIMEPROP") array.push(b,"SJC") array.push(b,"SKBSHUT") array.push(b,"SKPRES") array.push(b,"SKPRES-WB") array.push(b,"SLIC") array.push(b,"SLP") array.push(b,"SLVEST") array.push(b,"SLVEST-WA") array.push(b,"SMCAP") array.push(b,"SMCAP-WC") array.push(b,"SMETRIC") array.push(b,"SMETRIC-WA") array.push(b,"SMI") array.push(b,"SMILE") array.push(b,"SMILE-WA") array.push(b,"SMISCOR") array.push(b,"SMRT") array.push(b,"SMTRACK") array.push(b,"SNC") array.push(b,"SOLID") array.push(b,"SOLUTN") array.push(b,"SOP") array.push(b,"SPRING") array.push(b,"SPRING-WA") array.push(b,"SPRITZER") array.push(b,"SPSETIA") array.push(b,"STAR") array.push(b,"STELLA") array.push(b,"STRAITS") array.push(b,"STRAITS-WA") array.push(b,"SUCCESS") array.push(b,"SUMATEC") array.push(b,"SUNCON") array.push(b,"SUNSURIA") array.push(b,"SUNWAY") array.push(b,"SUNWAY-WB") array.push(b,"SUPERLN") array.push(b,"SUPERMX") array.push(b,"SUPREME") array.push(b,"SURIA") array.push(b,"SWKPLNT") array.push(b,"SWSCAP") array.push(b,"SWSCAP-WB") array.push(b,"SYF") array.push(b,"SYMLIFE") array.push(b,"SYSCORP") array.push(b,"SYSTECH") array.push(b,"T7GLOBAL") array.push(b,"TAANN") array.push(b,"TAFI") array.push(b,"TAKAFUL") array.push(b,"TALAMT") array.push(b,"TALIWRK") array.push(b,"TAMBUN") array.push(b,"TANCO") array.push(b,"TASHIN") array.push(b,"TCS") array.push(b,"TCS-WA") array.push(b,"TDM") array.push(b,"TECHNAX") array.push(b,"TEKSENG") array.push(b,"TELADAN") array.push(b,"TELADAN-WA") array.push(b,"TENAGA") array.push(b,"TEXCYCL") array.push(b,"TGL") array.push(b,"TGUAN") array.push(b,"THETA") array.push(b,"THHEAVY") array.push(b,"THPLANT") array.push(b,"THRIVEN") array.push(b,"TWL") array.push(b,"TIMECOM") array.push(b,"TIMWELL") array.push(b,"TITIJYA") array.push(b,"TJSETIA") array.push(b,"TM") array.push(b,"TMCLIFE") array.push(b,"TOCEAN") array.push(b,"TOMYPAK") array.push(b,"TONGHER") array.push(b,"TOPBLDS") array.push(b,"TOPGLOV") array.push(b,"TOPVISN") array.push(b,"TOYOVEN") array.push(b,"TOYOVEN-WB") array.push(b,"TPC") array.push(b,"TRC") array.push(b,"TRIMODE") array.push(b,"TROP") array.push(b,"TSH") array.push(b,"TSRCAP") array.push(b,"TTV") array.push(b,"UCHITEC") array.push(b,"UEMS") array.push(b,"ULICORP") array.push(b,"UMCCA") array.push(b,"UMS") array.push(b,"UMSNGB") array.push(b,"UMW") array.push(b,"UNIMECH") array.push(b,"UNISEM") array.push(b,"UNIWALL") array.push(b,"UOADEV") array.push(b,"UPA") array.push(b,"UTAMA") array.push(b,"UTDPLT") array.push(b,"UWC") array.push(b,"UZMA") array.push(b,"VC") array.push(b,"VC-WB") array.push(b,"VC-WC") array.push(b,"VELESTO") array.push(b,"VELESTO-WA") array.push(b,"VERSATL") array.push(b,"IHB") array.push(b,"IHB-WA") array.push(b,"VINVEST") array.push(b,"VINVEST-WE") array.push(b,"VIS") array.push(b,"VIS-WB") array.push(b,"VITROX") array.push(b,"VIZIONE") array.push(b,"VIZIONE-WC") array.push(b,"VIZIONE-WD") array.push(b,"VOLCANO") array.push(b,"VS") array.push(b,"VS-WB") array.push(b,"VSTECS") array.push(b,"WAJA") array.push(b,"WARISAN") array.push(b,"WASEONG") array.push(b,"WATTA") array.push(b,"WCT") array.push(b,"WEGMANS") array.push(b,"WEGMANS-WA") array.push(b,"WEGMANS-WB") array.push(b,"WELLCAL") array.push(b,"WIDAD") array.push(b,"WIDAD-WA") array.push(b,"WONG") array.push(b,"WOODLAN") array.push(b,"WPRTS") array.push(b,"WTHORSE") array.push(b,"WTK") array.push(b,"CITAGLB") array.push(b,"CITAGLB-WA") array.push(b,"CITAGLB-WB") array.push(b,"XINHWA") array.push(b,"XINHWA-WA") array.push(b,"XL") array.push(b,"XL-WA") array.push(b,"Y&G") array.push(b,"YBS") array.push(b,"YGL") array.push(b,"YKGI") array.push(b,"YLI") array.push(b,"YNHPROP") array.push(b,"YONGTAI") array.push(b,"YSPSAH") array.push(b,"ZECON") array.push(b,"ZELAN") array.push(b,"ZHULIAN") array.push(b,"ACEINNO") array.push(b,"AIM") array.push(b,"BENALEC") array.push(b,"CARZO") array.push(b,"ECOMATE") array.push(b,"ESCERAM") array.push(b,"ESCERAM-WB") array.push(b,"FARLIM") array.push(b,"GPACKET") array.push(b,"GPACKET-WB") array.push(b,"ICTZONE") array.push(b,"IJMPLNT") array.push(b,"KNM") array.push(b,"NTPM") array.push(b,"PARKWD") array.push(b,"PEKAT") array.push(b,"PENSONIC") array.push(b,"PENSONIC-WB") array.push(b,"RCECAP") array.push(b,"RTSTECH") array.push(b,"SHL") array.push(b,"SCGBHD") array.push(b,"TASCO") array.push(b,"TECHBND") array.push(b,"TECHBND-WA") array.push(b,"TNLOGIS") array.push(b,"TURIYA") array.push(b,"WANGZNG") array.push(b,"YB") array.push(b,"SWIFT") array.push(b,"CORAZA") array.push(b,"SENHENG") array.push(b,"CAPITALA") array.push(b,"SIAB") array.push(b,"FARMFRESH") array.push(b,"CENGILD") array.push(b,"GUOCO") array.push(b,"MNHLDG") array.push(b,"MTAG") array.push(b,"NOVA") array.push(b,"OMH") array.push(b,"POHUAT") array.push(b,"PGB") array.push(b,"REDTONE") array.push(b,"SCOMI") array.push(b,"SCOMI-WB") array.push(b,"SEB") array.push(b,"TEXCHEM") array.push(b,"TRIVE") array.push(b,"TRIVE-WC") array.push(b,"CNERGEN") array.push(b,"YEWLEE") array.push(b,"SENFONG") array.push(b,"EIB") array.push(b,"UNIQUE") array.push(b,"SNS") array.push(b,"AGMO") //NEW ENTRY NOV 2022 array.push(b,"APPASIA") array.push(b,"APPASIA-WA") array.push(b,"APPASIA-Wb") array.push(b,"ASIAFILE") array.push(b,"BCMALL") array.push(b,"BCMALL-WA") array.push(b,"BETA") array.push(b,"CNASIA") array.push(b,"CNASIA-WA") array.push(b,"CNERGEN") array.push(b,"COMCORP") array.push(b,"COSMOS") array.push(b,"DELEUM") array.push(b,"EFFICEN") array.push(b,"EKSONS") array.push(b,"FAST") array.push(b,"FAST-WA") array.push(b,"FLBHD") array.push(b,"GCE") array.push(b,"HEXCARE") array.push(b,"HEXTECH") array.push(b,"HLT") array.push(b,"IBHD") array.push(b,"JFTECH") array.push(b,"JFTECH-WA") array.push(b,"KEYASIC") array.push(b,"KTB") array.push(b,"LBICAP") array.push(b,"LBICAP-WB") array.push(b,"LGMS") array.push(b,"AIRPORT") array.push(b,"MBSB") array.push(b,"M&G") array.push(b,"MUDAJYA") array.push(b,"MUDAJYA-WA") array.push(b,"NSOP") array.push(b,"ORGA") array.push(b,"PANSAR") array.push(b,"PANSAR-WA") array.push(b,"PRKCORP") array.push(b,"PERTAMA") array.push(b,"PRG") array.push(b,"PTRB") array.push(b,"RAMSSOL") array.push(b,"SFPTECH") array.push(b,"SHANG") array.push(b,"SINARAN") array.push(b,"SINARAN-WB") array.push(b,"SSB8") array.push(b,"SUNVIEW") array.push(b,"TECGUAN") array.push(b,"TOMEI") array.push(b,"UMC") array.push(b,"YXPM") var notmyx = syminfo.prefix != "MYX" and syminfo.prefix != "MYX_DLY" var found = (array.includes(a, syminfo.ticker)) or (array.includes(b, syminfo.ticker)) var int result = 0 result := found ? 0 : notmyx ? 2 : 1 //example using status() //bgcolor(status() == 1 ? color.new(color.red, 90): status() == 0 ? color.new(color.green, 90) : color.new(color.blue, 90)) //example // Function draw label draw_label()=> var label l = na l_text = string(na) l_position_x = int(0) l_position_y = float(0.0) l_color = color(na) l_text_color = color(na) label.delete(l[1]) l_position_x := bar_index + 1 l_position_y := high l_text_color := color.white //Contoh guna switch statement switch status() 0 => l_text := syminfo.ticker + " [S]\n" + syminfo.description, l_color := color.green 1 => l_text := syminfo.ticker + " [NS]\n" + syminfo.description, l_color := color.red => l_text := syminfo.tickerid + "\n" + syminfo.description, l_color := color.blue l := label.new( x = l_position_x, y = l_position_y, color = l_color, text = l_text, textcolor = l_text_color, style = label.style_label_left, size = size.normal) draw_label()
MathConstantsElectromagnetic
https://www.tradingview.com/script/8aIya1wr-MathConstantsElectromagnetic/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
10
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Mathematical Constants library(title='MathConstantsElectromagnetic') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Constants.cs // A collection of frequently used mathematical constants. // ELECTROMAGNETIC CONSTANTS { // @function Elementary Electron Charge: e = 1.602176487e-19 [C = A s] (2007 CODATA) export ElementaryCharge () => //{ 1.602176487e-19 //} // @function Magnetic Flux Quantum: theta_0 = h/(2*e) [Wb = m^2 kg s^-2 A^-1] (2007 CODATA) export MagneticFluxQuantum () => //{ 2.067833668e-15 //} // @function Conductance Quantum: G_0 = 2*e^2/h [S = m^-2 kg^-1 s^3 A^2] (2007 CODATA) export ConductanceQuantum () => //{ 7.7480917005e-5 //} // @function Josephson Constant: K_J = 2*e/h [Hz V^-1] (2007 CODATA) export JosephsonConstant () => //{ 483597.891e9 //} // @function Von Klitzing Constant: R_K = h/e^2 [Ohm = m^2 kg s^-3 A^-2] (2007 CODATA) export VonKlitzingConstant () => //{ 25812.807557 //} // @function Bohr Magneton: mu_B = e*h_bar/2*m_e [J T^-1] (2007 CODATA) export BohrMagneton () => //{ 927.400915e-26 //} // @function Nuclear Magneton: mu_N = e*h_bar/2*m_p [J T^-1] (2007 CODATA) export NuclearMagneton () => //{ 5.05078324e-27 //} //}
MathStatisticsKernelFunctions
https://www.tradingview.com/script/ooqAiNMr-MathStatisticsKernelFunctions/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
33
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description TODO: add library description here library(title='MathStatisticsKernelFunctions') // reference: // list: https://en.wikipedia.org/wiki/Kernel_%28statistics%29 // // y+ // | --------------------------------- // | | | | // | | | | // | | | | // -x -----o---------------o---------------o------ +x // -bandwidth origin (0) +bandwidth // @function Uniform kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export uniform (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else 0.5 //{ usage // b = -1 + (bar_index%100) * 0.02, plot(uniform(b, 0.9), color=color.red), plot(b, color=color.silver) //{ remarks: //}}} // @function Triangular kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export triangular (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else 1.0 - math.abs(distance / bandwidth) //{ usage // b = -1.0 + (bar_index%100) * 0.02, plot(triangular(b, 0.75)), plot(b, color=color.red) //{ remarks: //}}} // @function Epanechnikov kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export epanechnikov (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else 0.25 * (1.0 - math.pow(distance/bandwidth, 2.0)) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(epanechnikov(b, 0.9)), plot(b, color=color.red) //{ remarks: //}}} // @function Quartic kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export quartic (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else 0.9375 * math.pow(1.0 - math.pow(distance/bandwidth, 2.0), 2.0) //{ usage // b = -1 + (bar_index%100) * 0.02, , plot(b, color=color.red) //{ remarks: //}}} // @function Triweight kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export triweight (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else (35.0 / 32.0) * math.pow(1.0 - math.pow(distance/bandwidth, 2.0), 3.0) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(triweight(b, 0.9)), plot(b, color=color.red) //{ remarks: //}}} // @function Tricubic kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export tricubic (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else (70.0 / 81.0) * math.pow(1.0 - math.pow(math.abs(distance)/bandwidth, 3.0), 3.0) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(tricubic(b, 0.9)), plot(b, color=color.red) //{ remarks: //}}} // @function Gaussian kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export gaussian (float distance, float bandwidth=1.0) => //{ 1.0 / math.sqrt(2.0 * math.pi) * math.pow(math.e, -0.5 * math.pow(distance / bandwidth, 2.0)) //{ usage // b = -math.pi + (bar_index%100) * (math.pi*0.02), plot(b, color=color.red), plot(gaussian(b, 3.0)), plot(gaussian(b, 2.0), color=color.aqua), plot(gaussian(b, 1.0), color=color.yellow) //{ remarks: //}}} // @function Cosine kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export cosine (float distance, float bandwidth=1.0) => //{ if math.abs(distance) > bandwidth 0.0 else (math.pi / 4.0) * math.cos(math.pi / 2.0 * (distance / bandwidth)) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(cosine(b, 0.5)), plot(b, color=color.red) //{ remarks: //}}} // @function logistic kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export logistic (float distance, float bandwidth=1.0) => //{ _d = distance / bandwidth 1.0 / (math.pow(math.e, _d) + 2.0 + math.pow(math.e, -_d)) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(logistic(b, 0.1)), plot(b, color=color.red) //{ remarks: //}}} // @function Sigmoid kernel. // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export sigmoid (float distance, float bandwidth=1.0) => //{ _d = distance / bandwidth 2.0 / math.pi * (1.0 / (math.pow(math.e, _d) + math.pow(math.e, -_d))) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(sigmoid(b, 0.1)), plot(b, color=color.red) //{ remarks: //}}} // @function Kernel selection method. // @param kernel string, kernel to select. (options="uniform", "triangle", "epanechnikov", "quartic", "triweight", "tricubic", "gaussian", "cosine", "logistic", "sigmoid") // @param distance float, distance to kernel origin. // @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel. // @returns float. export select (string kernel, float distance, float bandwidth=1.0) => //{ switch (kernel) 'uniform' => uniform(distance, bandwidth) 'triangle' => triangular(distance, bandwidth) 'epanechnikov' => epanechnikov(distance, bandwidth) 'quartic' => quartic(distance, bandwidth) 'triweight' => triweight(distance, bandwidth) 'tricubic' => tricubic(distance, bandwidth) 'gaussian' => gaussian(distance, bandwidth) 'cosine' => cosine(distance, bandwidth) 'logistic' => logistic(distance, bandwidth) 'sigmoid' => sigmoid(distance, bandwidth) => runtime.error('MathStatisticsKernel -> select(): "kernel" invalid kernel.'), float(na) //{ usage // b = -1 + (bar_index%100) * 0.02, plot(select('uniform', b, 0.1)), plot(b, color=color.red) //{ remarks: //}}} string choice = input.string(defval='uniform', options=["uniform", "triangle", "epanechnikov", "quartic", "triweight", "gaussian", "cosine", "logistic", "sigmoid"]) float bandwidth = input.float(0.5) test = -1.0 + (bar_index % 100) * 0.02 plot(series=test, title='cycle', color=color.silver) plot(series=uniform(test, bandwidth), title='uniform', color=color.red) plot(series=triangular(test, bandwidth), title='triangle', color=color.lime) plot(series=epanechnikov(test, bandwidth), title='epanechnikov', color=color.blue) plot(series=quartic(test, bandwidth), title='quartic', color=color.aqua) plot(series=triweight(test, bandwidth), title='triweight', color=color.purple) plot(series=tricubic(test, bandwidth), title='tricubic', color=color.fuchsia) plot(series=gaussian(test, bandwidth), title='gaussian', color=color.orange) plot(series=cosine(test, bandwidth), title='cosine', color=color.yellow) plot(series=logistic(test, bandwidth), title='logistic', color=color.olive) plot(series=sigmoid(test, bandwidth), title='sigmoid', color=color.maroon) plot(series=select(choice, test, bandwidth), title='choice', color=color.gray)
MathConstantsAtomic
https://www.tradingview.com/script/NQZFDVWo-MathConstantsAtomic/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
9
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Mathematical Constants library(title='MathConstantsAtomic') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Constants.cs // A collection of frequently used mathematical constants. // ATOMIC AND NUCLEAR CONSTANTS { // @function Fine Structure Constant: alpha = e^2/4*Pi*e_0*h_bar*c_0 [1] (2007 CODATA) export FineStructureConstant () => //{ 7.2973525376e-3 //} // @function Rydberg Constant: R_infty = alpha^2*m_e*c_0/2*h [m^-1] (2007 CODATA) export RydbergConstant () => //{ 10973731.568528 //} // @function Bor Radius: a_0 = alpha/4*Pi*R_infty [m] (2007 CODATA) export BohrRadius () => //{ 0.52917720859e-10 //} // @function Hartree Energy: E_h = 2*R_infty*h*c_0 [J] (2007 CODATA) export HartreeEnergy () => //{ 4.35974394e-18 //} // @function Quantum of Circulation: h/2*m_e [m^2 s^-1] (2007 CODATA) export QuantumOfCirculation () => //{ 3.6369475199e-4 //} // @function Fermi Coupling Constant: G_F/(h_bar*c_0)^3 [GeV^-2] (2007 CODATA) export FermiCouplingConstant () => //{ 1.16637e-5 //} // @function Weak Mixin Angle: sin^2(theta_W) [1] (2007 CODATA) export WeakMixingAngle () => //{ 0.22256 //} // @function Electron Mass: [kg] (2007 CODATA) export ElectronMass () => //{ 9.10938215e-31 //} // @function Electron Mass Energy Equivalent: [J] (2007 CODATA) export ElectronMassEnergyEquivalent () => //{ 8.18710438e-14 //} // @function Electron Molar Mass: [kg mol^-1] (2007 CODATA) export ElectronMolarMass () => //{ 5.4857990943e-7 //} // @function Electron Compton Wavelength: [m] (2007 CODATA) export ComptonWavelength () => //{ 2.4263102175e-12 //} // @function Classical Electron Radius: [m] (2007 CODATA) export ClassicalElectronRadius () => //{ 2.8179402894e-15 //} // @function Thomson Cross Section: [m^2] (2002 CODATA) export ThomsonCrossSection () => //{ 0.6652458558e-28 //} // @function Electron Magnetic Moment: [J T^-1] (2007 CODATA) export ElectronMagneticMoment () => //{ -928.476377e-26 //} // @function Electon G-Factor: [1] (2007 CODATA) export ElectronGFactor () => //{ -2.0023193043622 //} // @function Muon Mass: [kg] (2007 CODATA) export MuonMass () => //{ 1.88353130e-28 //} // @function Muon Mass Energy Equivalent: [J] (2007 CODATA) export MuonMassEnegryEquivalent () => //{ 1.692833511e-11 //} // @function Muon Molar Mass: [kg mol^-1] (2007 CODATA) export MuonMolarMass () => //{ 0.1134289256e-3 //} // @function Muon Compton Wavelength: [m] (2007 CODATA) export MuonComptonWavelength () => //{ 11.73444104e-15 //} // @function Muon Magnetic Moment: [J T^-1] (2007 CODATA) export MuonMagneticMoment () => //{ -4.49044786e-26 //} // @function Muon G-Factor: [1] (2007 CODATA) export MuonGFactor () => //{ -2.0023318414 //} // @function Tau Mass: [kg] (2007 CODATA) export TauMass () => //{ 3.16777e-27 //} // @function Tau Mass Energy Equivalent: [J] (2007 CODATA) export TauMassEnergyEquivalent () => //{ 2.84705e-10 //} // @function Tau Molar Mass: [kg mol^-1] (2007 CODATA) export TauMolarMass () => //{ 1.90768e-3 //} // @function Tau Compton Wavelength: [m] (2007 CODATA) export TauComptonWavelength () => //{ 0.69772e-15 //} // @function Proton Mass: [kg] (2007 CODATA) export ProtonMass () => //{ 1.672621637e-27 //} // @function Proton Mass Energy Equivalent: [J] (2007 CODATA) export ProtonMassEnergyEquivalent () => //{ 1.503277359e-10 //} // @function Proton Molar Mass: [kg mol^-1] (2007 CODATA) export ProtonMolarMass () => //{ 1.00727646677e-3 //} // @function Proton Compton Wavelength: [m] (2007 CODATA) export ProtonComptonWavelength () => //{ 1.3214098446e-15 //} // @function Proton Magnetic Moment: [J T^-1] (2007 CODATA) export ProtonMagneticMoment () => //{ 1.410606662e-26 //} // @function Proton G-Factor: [1] (2007 CODATA) export ProtonGFactor () => //{ 5.585694713 //} // @function Proton Shielded Magnetic Moment: [J T^-1] (2007 CODATA) export ShieldedProtonMagneticMoment () => //{ 1.410570419e-26 //} // @function Proton Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA) export ProtonGyromagneticRatio () => //{ 2.675222099e8 //} // @function Proton Shielded Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA) export ShieldedProtonGyromagneticRatio () => //{ 2.675153362e8 //} // @function Neutron Mass: [kg] (2007 CODATA) export NeutronMass () => //{ 1.674927212e-27 //} // @function Neutron Mass Energy Equivalent: [J] (2007 CODATA) export NeutronMassEnegryEquivalent () => //{ 1.505349506e-10 //} // @function Neutron Molar Mass: [kg mol^-1] (2007 CODATA) export NeutronMolarMass () => //{ 1.00866491597e-3 //} // @function Neuron Compton Wavelength: [m] (2007 CODATA) export NeutronComptonWavelength () => //{ 1.3195908951e-1 //} // @function Neutron Magnetic Moment: [J T^-1] (2007 CODATA) export NeutronMagneticMoment () => //{ -0.96623641e-26 //} // @function Neutron G-Factor: [1] (2007 CODATA) export NeutronGFactor () => //{ -3.82608545 //} // @function Neutron Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA) export NeutronGyromagneticRatio () => //{ 1.83247185e8 //} // @function Deuteron Mass: [kg] (2007 CODATA) export DeuteronMass () => //{ 3.34358320e-27 //} // @function Deuteron Mass Energy Equivalent: [J] (2007 CODATA) export DeuteronMassEnegryEquivalent () => //{ 3.00506272e-10 //} // @function Deuteron Molar Mass: [kg mol^-1] (2007 CODATA) export DeuteronMolarMass () => //{ 2.013553212725e-3 //} // @function Deuteron Magnetic Moment: [J T^-1] (2007 CODATA) export DeuteronMagneticMoment () => //{ 0.433073465e-26 //} // @function Helion Mass: [kg] (2007 CODATA) export HelionMass () => //{ 5.00641192e-27 //} // @function Helion Mass Energy Equivalent: [J] (2007 CODATA) export HelionMassEnegryEquivalent () => //{ 4.49953864e-10 //} // @function Helion Molar Mass: [kg mol^-1] (2007 CODATA) export HelionMolarMass () => //{ 3.0149322473e-3 //} // @function Avogadro constant: [mol^-1] (2010 CODATA) export Avogadro () => //{ 6.0221412927e23 //} //}
MathConstantsScientific
https://www.tradingview.com/script/0oAR55cp-MathConstantsScientific/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
10
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Mathematical Constants library(title='MathConstantsScientific') // reference: // https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Constants.cs // A collection of frequently used mathematical constants. // Scientific Prefixes { // @function The SI prefix factor corresponding to 1 000 000 000 000 000 000 000 000 export Yotta () => //{ 1e24 //} // @function The SI prefix factor corresponding to 1 000 000 000 000 000 000 000 export Zetta () => //{ 1e21 //} // @function The SI prefix factor corresponding to 1 000 000 000 000 000 000 export Exa () => //{ 1e18 //} // @function The SI prefix factor corresponding to 1 000 000 000 000 000 export Peta () => //{ 1e15 //} // @function The SI prefix factor corresponding to 1 000 000 000 000 export Tera () => //{ 1e12 //} // @function The SI prefix factor corresponding to 1 000 000 000 export Giga () => //{ 1e9 //} // @function The SI prefix factor corresponding to 1 000 000 export Mega () => //{ 1e6 //} // @function The SI prefix factor corresponding to 1 000 export Kilo () => //{ 1e3 //} // @function The SI prefix factor corresponding to 100 export Hecto () => //{ 1e2 //} // @function The SI prefix factor corresponding to 10 export Deca () => //{ 1e1 //} // @function The SI prefix factor corresponding to 0.1 export Deci () => //{ 1e-1 //} // @function The SI prefix factor corresponding to 0.01 export Centi () => //{ 1e-2 //} // @function The SI prefix factor corresponding to 0.001 export Milli () => //{ 1e-3 //} // @function The SI prefix factor corresponding to 0.000 001 export Micro () => //{ 1e-6 //} // @function The SI prefix factor corresponding to 0.000 000 001 export Nano () => //{ 1e-9 //} // @function The SI prefix factor corresponding to 0.000 000 000 001 export Pico () => //{ 1e-12 //} // @function The SI prefix factor corresponding to 0.000 000 000 000 001 export Femto () => //{ 1e-15 //} // @function The SI prefix factor corresponding to 0.000 000 000 000 000 001 export Atto () => //{ 1e-18 //} // @function The SI prefix factor corresponding to 0.000 000 000 000 000 000 001 export Zepto () => //{ 1e-21 //} // @function The SI prefix factor corresponding to 0.000 000 000 000 000 000 000 001 export Yocto () => //{ 1e-24 //} //}
Probability
https://www.tradingview.com/script/VuCsvJyb-Probability/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
20
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description: a library of functions to deal with probabilities. library(title='Probability') // imports: import RicardoSantos/MathExtension/1 as me // me.log2() import RicardoSantos/ArrayGenerate/1 as agen // agen.sequence_float() //#region Helper functions: // @function Calculate the power of a square matrix // @param M Square matrix. // @param power Power to raise matrix by. // @returns Raised matrix. // // --- // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ matrix_power (matrix<float> M, int power) => int _dim = M.rows() if _dim != M.columns() runtime.error('Matrix is not square!') matrix<float> _A = matrix.new<float>(_dim, _dim, 0.0) matrix<float> _C = M.copy() // for _i = 1 to power // _C := f_matrix_multiply_2d(_C, matrix_a, dimension, dimension, dimension, dimension) for _i = 0 to _dim - 1 _A.set(_i, _i, 1.0) int _p = power for _i = 0 to 999999 if _p > 0 if (_p % 2) == 1 _A := matrix.mult(_A, _C) // _A := f_matrix_multiply_2d(matrix_a=_A, matrix_b=_C, dimension_ax=dimension, dimension_ay=dimension, dimension_bx=dimension, dimension_by=dimension) _C := matrix.mult(_C, _C) // _C := f_matrix_multiply_2d(matrix_a=_C, matrix_b=_C, dimension_ax=dimension, dimension_ay=dimension, dimension_bx=dimension, dimension_by=dimension) _p /= 2 int(na) else break int(na) _A // @function replaces a labels text with the representation of a 2d matrix. // @param label_id Label to update. // @param M Data source. // @returns Updates provided label text. method label_matrix (label label_id, matrix<float> M)=> int _Mrows = M.rows() int _Mcols = M.columns() label.set_text(id=label_id, text=str.tostring(M, '#.###')) //#endregion //#region Probability: // reference: // https://gist.github.com/Daniel-Hug/f0fee168155f1af72c390030cc9be463 // https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/basic-statistics/probability-distributions/how-to/cumulative-distribution-function-cdf/methods-and-formulas/methods-and-formulas/ // https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/basic-statistics/probability-distributions/supporting-topics/basics/calculating-probabilities-for-different-distributions/ // @function Complementary error function // @param value Value to test. // @returns float // // --- // `.erf(0.95) = 0.820891` // // --- // https://www.johndcook.com/blog/csharp_erf/ // https://reference.wolfram.com/language/ref/Erf.html export erf(float value) => // constants: float _a1 = 0.254829592, float _a2 = -0.284496736, float _a3 = 1.421413741 float _a4 = -1.453152027, float _a5 = 1.061405429, float _p = 0.3275911 float _x = math.abs(value) float _t = 1.0 / (1.0 + _p * _x) // erf(-_x) = -erf(x) float _y = 1.0 - ((((_a5 * _t + _a4) * _t + _a3) * _t + _a2) * _t + _a1) * _t * math.exp(-_x * _x) math.sign(value) * _y // @function Computes the inverse error function using the Mc Giles method, sacrifices accuracy for speed. // @param value value to test, expected value in (-1.0, 1.0) range. // @returns float // // --- // `.ierf_mcgiles(0.820891) = 0.72096 // correct = 0.95` \ // `.ierf_mcgiles(0.6) = -0.17696 // correct = 0.595116` // // --- // http://www.mimirgames.com/articles/programming/approximations-of-the-inverse-error-function/ // https://keisan.casio.com/exec/system/1180573448 export ierf_mcgiles(float value) => float _p = 0. float _w = -math.log((1.0 - value) * (1.0 + value)) if _w < 0.5 _w -= 2.5 _p += ((((((((2.81022636e-08 * _w) + 3.43273939e-07 * _w) + -3.5233877e-06 * _w) + -4.39150654e-06 * _w) + 0.00021858087 * _w) + -0.00125372503 * _w) + -0.00417768164 * _w) + 0.246640727 + _w) + 1.50140941 else _w := math.sqrt(nz(_w)) - 3.0 _p += ((((((((-0.000200214257 * _w) + 0.000100950558 * _w) + 0.00134934322 * _w) + -0.00367342844 * _w) + 0.00573950773 * _w) + -0.0076224613 * _w) + 0.00943887047 * _w) + 1.00167406 * _w) + 2.83297682 _p * value // @function computes the inverse error function using the Newton method with double refinement. // @param value value to test, expected value in (-1.0, 1.0) range. // @returns float // // --- // http://www.mimirgames.com/articles/programming/approximations-of-the-inverse-error-function/ // // --- // `.ierf(0.820891) = na` //https://reference.wolfram.com/language/ref/InverseErf.html \ // `.ierf_mcgiles(0.6) = na` // correct = 0.595116 // https://keisan.casio.com/exec/system/1180573448 export ierf_double(float value) => float _r = 0. float _z = math.sign(value) * value if _z <= 0.7 float _x2 = _z * _z _r += _z * (((-0.140543331 * _x2 + 0.914624893) * _x2 - 1.645349621) * _x2 + 0.886226899) _r /= (((0.012229801 * _x2 - 0.329097515) * _x2 + 1.442710462) * _x2 - 2.118377725) * _x2 + 1. else float _y = math.sqrt( -math.log((1 - _z) / 2)) _r += (((1.641345311 * _y + 3.429567803) * _y - 1.62490649) * _y - 1.970840454) _r /= ((1.637067800 * _y + 3.543889200) * _y + 1.) _r *= math.sign(value) _z *= math.sign(value) _r -= (erf(value=_r) - _z) / (2 / math.sqrt(math.pi) * math.exp(-_r * _r)) _r -= (erf(value=_r) - _z) / (2 / math.sqrt(math.pi) * math.exp(-_r * _r)) //Comment out if you do not want single refinement // @function computes the inverse error function using the Newton method. // @param value value to test, expected value in (-1.0, 1.0) range. // @returns float // // --- // http://www.mimirgames.com/articles/programming/approximations-of-the-inverse-error-function/ // // --- // .ierf(0.820891) = 0.95 //https://reference.wolfram.com/language/ref/InverseErf.html // .ierf_mcgiles(0.6) = 0.59512 // correct = 0.595116 // https://keisan.casio.com/exec/system/1180573448 export ierf(float value) => float _r = 0. float _z = math.sign(value) * value if _z <= 0.7 float _x2 = _z * _z _r += _z * (((-0.140543331 * _x2 + 0.914624893) * _x2 - 1.645349621) * _x2 + 0.886226899) _r /= (((0.012229801 * _x2 - 0.329097515) * _x2 + 1.442710462) * _x2 - 2.118377725) * _x2 + 1. else float _y = math.sqrt(-math.log((1 - _z) / 2)) _r += (((1.641345311 * _y + 3.429567803) * _y - 1.62490649) * _y - 1.970840454) _r /= ((1.637067800 * _y + 3.543889200) * _y + 1.) _r *= math.sign(value) _z *= math.sign(value) _r -= (erf(_r) - _z) / (2 / math.sqrt(math.pi) * math.exp(-_r * _r)) // _r -= (erf(_r) - _z) / (2 / math.sqrt(math.pi) * math.exp(-_r * _r)) //Comment out if you do not want single refinement // @function probability that the event will not occur. // @param probability Probability of event, expected value in (0.0, 1.0) range. // @returns float // // --- // `probability_complement(0.25) = 0.75` \ // `probability_complement(0.67) = 0.23` export complement(float probability) => 1.0 - probability // @function Gini Inbalance or Gini index for a given probability. // @param probability Probability of event, expected value in (0.0, 1.0) range. // @returns float // // --- // https://victorzhou.com/blog/gini-impurity/ // https://www.tradingview.com/script/IlAZiO7E-Function-Entropy-Gini-Index/ export entropy_gini_impurity_single(float probability) => probability * complement(probability=probability) // @function Gini Inbalance or Gini index for a series of events. // @param events List with event probability's, expected values to be in (0.0, 1.0) range. // @returns float // // --- // https://victorzhou.com/blog/gini-impurity/ // https://www.tradingview.com/script/IlAZiO7E-Function-Entropy-Gini-Index/ export entropy_gini_impurity(float[] events) => int _size = array.size(id=events) float _sum = 0. if _size > 0 for _i = 0 to _size - 1 _p = array.get(id=events, index=_i) _sum += entropy_gini_impurity_single(probability=_p) _sum // @function Entropy information value of the probability of a single event. // @param probability Probability of event, expected value in (0.0, 1.0) range. // @returns float, value as bits of information. // // --- // https://machinelearningmastery.com/what-is-information-entropy/ // https://www.tradingview.com/script/JFXtLbSo-Function-Shannon-Entropy/ export entropy_shannon_single(float probability) => -me.log2(value=probability + 1.0e-15) // @function Entropy information value of a distribution of events. // @param events List with event probability's, expected values to be in (0.0, 1.0) range. // @returns float // // --- // https://machinelearningmastery.com/what-is-information-entropy/ // https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html // https://www.tradingview.com/script/JFXtLbSo-Function-Shannon-Entropy/ export entropy_shannon(float[] events) => int _size = array.size(id=events) float _sum = 0. if _size > 0 for _i = 0 to _size - 1 _p = array.get(id=events, index=_i) _sum += _p * entropy_shannon_single(probability=_p) _sum // @function Calculates Chebyshev Inequality. // @param n_stdeviations Value expected to be positive, over or equal to 1.0. // @returns float // // --- // https://www.tradingview.com/script/ndG6Dffb-Function-Probability-Chebyshev-Inequality/ export inequality_chebyshev(float n_stdeviations=1.0) => n_stdeviations < 1 ? 0 : 1. - 1. / math.pow(base=n_stdeviations, exponent=2.0) // @function Calculates Chebyshev Inequality. // @param mean Mean of a distribution. // @param std standard deviation of a distribution. // @returns float // // --- // https://www.tradingview.com/script/ndG6Dffb-Function-Probability-Chebyshev-Inequality/ export inequality_chebyshev_distribution(float mean, float std) => inequality_chebyshev(n_stdeviations=mean / std) // @function Calculates Chebyshev Inequality for a array of values. // @param data_sample List of numeric values. // @returns float // // --- // https://www.tradingview.com/script/ndG6Dffb-Function-Probability-Chebyshev-Inequality/ export inequality_chebyshev_sample(float[] data_sample) => float _mean = array.avg(id=data_sample) float _std = array.stdev(id=data_sample) inequality_chebyshev(n_stdeviations=_mean / _std) // @function Probability that all arguments will happen when neither outcome // is affected by the other (accepts 1 or more arguments) // @param events List of event probabilities. // @returns Probability. // // --- // `.intersection_of_independent_events([0.25, 0.25]) = 0.0625` \ // `.intersection_of_independent_events([0.3, 0.3, 0.3]) = 0.027` export intersection_of_independent_events(float[] events) => int _size = array.size(id=events) if _size > 0 float _ret = array.get(id=events, index=0) if _size > 1 for _i = 1 to _size - 1 _ret *= array.get(id=events, index=_i) _ret // @function Probability that either one of the arguments will happen when neither outcome // is affected by the other (accepts 1 or more arguments) // @param events List of event probabilities. // @returns Probability. // // --- // `.union_of_independent_events([0.25, 0.25]) = 0.4375` \ // `.union_of_independent_events([0.3, 0.3, 0.3]) = 0.657` export union_of_independent_events(float[] events) => int _size = array.size(id=events) if _size > 0 float _ret = array.get(id=events, index=0) if _size > 1 for _i = 1 to _size - 1 float _Ai = array.get(id=events, index=_i) _ret += _Ai - nz(_ret) * _Ai //arguments[i] - ret * arguments[i]; _ret // @function Probabilities for each bin in the range of sample. // @param sample Samples to pool probabilities. // @param n_bins Number of bins to split the range // @return Probability distribution. // // --- // `.mass_function([1, 2, 3, 4], 4) = [0.25, 0.25, 0.25, 0.25]` export mass_function(float[] sample, int n_bins) => float[] _probabilities = array.new_float(size=n_bins, initial_value=0.0) int _size = array.size(id=sample), float _fraction = 1.0 / _size float _min = array.min(id=sample), float _max = array.max(id=sample), float _range = _max - _min if _size > 0 for _i = 0 to _size - 1 int _expected_index = math.floor(((array.get(id=sample, index=_i) - _min) / _range) * (n_bins - 1)) array.set(id=_probabilities, index=_expected_index, value=array.get(id=_probabilities, index=_expected_index) + _fraction) _probabilities // @function Use the CDF to determine the probability that a random observation // that is taken from the population will be less than or equal to a certain value. // Or returns the area of probability for a known value in a normal distribution. // @param mean Mean of the distribution. // @param stdev Standard deviation of the distribution. // @param value Limit value at which to stop. // @returns Probability. // // --- // `.cumulative_distribution_function(5, 30, 25) = 0.747507...` \ // `.cumulative_distribution_function(30, 25, 1.4241) = 0.126512` // // --- // https://en.wikipedia.org/wiki/Cumulative_distribution_function // https://stackoverflow.com/questions/5259421/cumulative-distribution-function-in-javascript // https://www.wolframalpha.com/input/?i=CDF%28normal+distribution+with+mean%3D+5+and+sd+%3D+30%2C+25%29 export cumulative_distribution_function(float mean, float stdev, float value) => _z = (value - mean) / math.sqrt(2.0 * math.pow(stdev, 2.0)) 0.5 * (1.0 + erf(_z)) // @function Transition matrix for the suplied distribution. // @param distribution Probability distribution. ex:. [0.25, 0.50, 0.25] // @returns Transition matrix. export transition_matrix(float[] distribution) => int _size = array.size(id=distribution) if _size < 0 runtime.error('Can not generate transition matrix from a empty distribution!') matrix<float> _T = matrix.new<float>(_size, _size, na) for _m = 0 to _size - 1 for _n = 0 to _size - 1 _T.set(_m, _n, distribution.get(_m) * distribution.get(_n)) _T // @function Probability of reaching target_state at target_step after starting from start_state // @param transition_matrix Probability transition matrix. // @param dimension Size of the matrix dimension. // @param target_step Number of steps to find probability. // @returns Probability. // // --- // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ export diffusion_matrix (matrix<float> transition_matrix, int target_step) => matrix_power(transition_matrix, target_step) // @function Probability of reaching target_state at target_step after starting from start_state // @param transition_matrix Probability transition matrix. // @param start_state State at which to start. // @param target_state State to find probability. // @param target_step Number of steps to find probability. // @returns Probability. // // --- // https://www.geeksforgeeks.org/finding-the-probability-of-a-state-at-a-given-time-in-a-markov-chain-set-2/ export state_at_time (matrix<float> transition_matrix, int start_state, int target_state, int target_step) => matrix<float> _T = matrix_power(transition_matrix, target_step) _T.get(target_state - 1, start_state - 1) //#endregion // import RicardoSantos/Probability/1 var label test = label.new(bar_index, 0.0, '') if barstate.islastconfirmedhistory t0 = erf(0.6) t1 = ierf(0.6) t2 = intersection_of_independent_events(array.new_float(3, 0.3)) t3 = union_of_independent_events(array.new_float(3, 0.3)) t4 = cumulative_distribution_function(30, 25, 1.4241) seq = agen.sequence_float(0.0, 1.0, 0.25) // [0.0, 0.25, 0.5, 0.75, 1.0] tm = transition_matrix(seq) label.set_xy(test, bar_index, 0.0) //label.set_text(test, tostring(t4)) // label_matrix(test, transition_matrix(array.new_float(4, 0.25))) // label_matrix(test, transition_matrix(seq)) //f_label_matrix_2d(test, f_matrix_multiply_2d(probability_transition_matrix(array.new_float(4, 0.25)), probability_transition_matrix(array.new_float(4, 0.25)), 4, 4, 4, 4), 4, 4) label_matrix(test, diffusion_matrix(tm, 25)) // label.set_text(test, str.tostring(state_at_time(tm, 2, 3, 25))) // 20230830 RS: previous version had wrong dimension value (4 -> 5).. // log.info('\n{0}', Probability.state_at_time(Probability.transition_matrix(seq), 4, 2, 3, 25)) // log.info('\n{0}\n\n{1}', // diffusion_matrix(tm, 25), // Probability.diffusion_matrix(Probability.transition_matrix(seq), 5, 25))
MathStatisticsKernelDensityEstimation
https://www.tradingview.com/script/oTcbPUuo-MathStatisticsKernelDensityEstimation/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
51
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description (KDE) Method for Kernel Density Estimation library(title='MathStatisticsKernelDensityEstimation') //| reference: //| https://www.highcharts.com/blog/tutorials/data-science-and-highcharts-kernel-density-estimation/ //| https://mathisonian.github.io/kde/ //| https://en.wikipedia.org/wiki/Kernel_density_estimation //| https://bookdown.org/egarpor/NP-UC3M/kde-i-kde.html //| https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/AV0405/MISHRA/kde.html //| https://en.wikipedia.org/wiki/Kernel_(statistics) //| https://aakinshin.net/posts/kde-discrete/ //| description: //| "In statistics, kernel density estimation (KDE) is a non-parametric way to estimate the probability density function of a random variable." from wikipedia.com // imports: import RicardoSantos/MathStatisticsKernelFunctions/1 as kernel // @funtion KDE method. // @param observations float array, sample data. // @param kernel string, the kernel to use, default='gaussian', options='uniform', 'triangle', 'epanechnikov', 'quartic', 'triweight', 'gaussian', 'cosine', 'logistic', 'sigmoid'. // @param bandwidth float, bandwidth to use in kernel, default=0.5, range=(0, +inf), less will smooth the data. // @param nsteps int, number of steps in range of distribution, default=20, this value is connected to how many line objects you can display per script. // @returns tuple with signature: (float array, float array) export kde (float[] observations, string kernel='gaussian', float bandwidth=0.5, int nsteps=20) => //{ int _osize = array.size(observations) switch (_osize < 1) => runtime.error('MathStatisticsKernelDensityEstimation -> kde(): "observations" has the wrong size.') (nsteps < 1) => runtime.error('MathStatisticsKernelDensityEstimation -> kde(): "nsteps" must be a positive number > 1.') float _range = array.range(observations) float _min = array.min(observations) - _range / 2 float _step = _range / nsteps // generate the bins range of the distribution. float[] _density_range_fill = array.new_float(nsteps * 2) for _i = 0 to (nsteps * 2) - 1 array.set(_density_range_fill, _i, _min + _i * _step) float[] _x = array.new_float(0) float[] _y = array.new_float(0) for _i = 0 to array.size(_density_range_fill) - 1 by 1 float _temp = 0. for _j = 0 to _osize - 1 by 1 _temp += kernel.select(kernel, array.get(_density_range_fill, _i) - array.get(observations, _j), 1.0 / bandwidth) _temp array.push(_x, array.get(_density_range_fill, _i)) array.push(_y, 1 / _osize * _temp) [_x, _y] //{ usage: //{ remarks: //}}} // @function Draw a horizontal distribution at current location on chart. // @param distribution_x float array, distribution points x value. // @param distribution_y float array, distribution points y value. // @param distribution_lines line array, array to append the distribution curve lines. // @param graph_lines line array, array to append the graph lines. // @param graph_labels label array, array to append the graph labels. // @returns void, updates arrays: distribution_lines, graph_lines, graph_labels. export draw_horizontal (float[] distribution_x, float[] distribution_y, line[] distribution_lines, line[] graph_lines, label[] graph_labels) => //{ int _sizex = array.size(distribution_x) int _sizey = array.size(distribution_y) switch (_sizex < 1 or _sizex > 500) => runtime.error('MathStatisticsKernelDensityEstimation -> draw_horizontal(): "distribution_x" has the wrong size, must be within range [1, 500].') (_sizex != _sizey) => runtime.error('MathStatisticsKernelDensityEstimation -> draw_horizontal(): "distribution_x" and "distribution_y" size do not match.') int _previousx = 0 float _previousy = array.get(distribution_y, 0) if _sizex == _sizey and _sizex > 1 int _nearest0_index = 0 for _i = 1 to _sizex - 1 by 1 _px = _i _py = array.get(distribution_y, _i) bool _xiscloserto0 = math.abs(array.get(distribution_x, _i)) < math.abs(array.get(distribution_x, _nearest0_index)) if _xiscloserto0 _nearest0_index := _i _nearest0_index array.push(distribution_lines, line.new(bar_index + _previousx, _previousy, bar_index + _px, _py)) _previousx := _px _previousy := _py _previousy int _top_index = array.indexof(distribution_y, array.max(distribution_y)) float _top_value = array.get(distribution_y, _top_index) float _std = array.stdev(distribution_y) array.push(graph_labels, label.new(bar_index, 0.0, str.tostring(array.get(distribution_x, 0)), style=label.style_label_right)) // range min array.push(graph_labels, label.new(bar_index + _sizex, 0.0, str.tostring(array.get(distribution_x, _sizex - 1)), style=label.style_label_left)) // range max array.push(graph_labels, label.new(bar_index + _top_index, 0.0, str.tostring(array.get(distribution_x, _top_index)), style=label.style_label_up, tooltip='Highest value')) // most frequent value array.push(graph_labels, label.new(bar_index, _std, str.format('Y std: {0, number, #.###}', _std), style=label.style_label_right, textalign=text.align_right, tooltip='Standard deviation')) // distribution std // array.push(graph_labels, label.new(bar_index, _top_value, str.format('Top probability: {0, number, #.###}\nSumY:{1, number, #.###}', nz(_top_value, 0.), array.sum(distribution_y)), style=label.style_label_right, textalign=text.align_right, tooltip=str.tostring(distribution_x) + '\n' + str.tostring(distribution_y))) array.push(graph_lines, line.new(bar_index, 0.0, bar_index+_sizex, 0.0, extend=extend.none, color=color.gray, style=line.style_dotted, width=2)) // axis y array.push(graph_lines, line.new(bar_index + _nearest0_index, 0.0 - _std, bar_index + _nearest0_index, _top_value + _std, extend=extend.none, color=color.gray, style=line.style_dotted, width=2)) // axis y array.push(graph_lines, line.new(bar_index + _top_index, 0.0, bar_index + _top_index, _top_value, extend=extend.none, color=color.blue, style=line.style_dashed, width=1)) // most frequent value array.push(graph_lines, line.new(bar_index, _std, bar_index + _sizex, _std, color=color.orange, style=line.style_dashed)) // distribution std //{ usage: // if barstate.islast // draw_horizontal(x, y) //{ remarks: //}}} // @function Draw a vertical distribution at current location on chart. // @param distribution_x float array, distribution points x value. // @param distribution_y float array, distribution points y value. // @param distribution_lines line array, array to append the distribution curve lines. // @param graph_lines line array, array to append the graph lines. // @param graph_labels label array, array to append the graph labels. // @returns void, updates arrays: distribution_lines, graph_lines, graph_labels. export draw_vertical (float[] distribution_x, float[] distribution_y, line[] distribution_lines, line[] graph_lines, label[] graph_labels) => //{ int _sizex = array.size(distribution_x) int _sizey = array.size(distribution_y) switch (_sizex < 1 or _sizex > 500) => runtime.error('MathStatisticsKernelDensityEstimation -> draw_vertical(): "distribution_x" has the wrong size, must be within range [1, 500].') (_sizex != _sizey) => runtime.error('MathStatisticsKernelDensityEstimation -> draw_vertical(): "distribution_x" and "distribution_y" size do not match.') int _previousx = 0 float _previousy = array.get(distribution_y, 0) if _sizex == _sizey and _sizex > 1 float _range = array.range(distribution_x) float _bottom = array.min(distribution_x) float _top = _bottom + _range float _step = _range / _sizex for _i = 1 to _sizex - 1 by 1 _px = math.min(int(array.get(distribution_y, _i)*500), 500)//_i _py = _bottom +_i*_step//array.get(distribution_y, _i) array.push(distribution_lines, line.new(bar_index + _previousx, _previousy, bar_index + _px, _py)) _previousx := _px _previousy := _py int _top_index = array.indexof(distribution_y, array.max(distribution_y)) float _top_value = array.get(distribution_y, _top_index) float _std = array.stdev(distribution_y) int _std_index = int(math.min(_std * 500, 500)) float _most_dense_level = _bottom + _top_index * _step int _most_dense_index = int(_top_value*500) array.push(graph_labels, label.new(bar_index, 0.0, str.tostring(array.get(distribution_x, 0)), style=label.style_label_up)) array.push(graph_labels, label.new(bar_index, _top, str.tostring(array.get(distribution_x, _sizex - 1)), style=label.style_label_down)) array.push(graph_labels, label.new(bar_index, _most_dense_level, str.tostring(array.get(distribution_x, _top_index)), style=label.style_label_right, tooltip='Highest value')) array.push(graph_labels, label.new(bar_index + _std_index, _bottom, str.format('Y std: {0, number, #.###}', _std), style=label.style_label_up, textalign=text.align_right, tooltip='Standard deviation')) // array.push(graph_labels, label.new(bar_index + _most_dense_index, _most_dense_level, str.format('\nTop probability: {0, number, #.###}\nSumY:{1, number, #.###}', nz(_top_value, 0.), array.sum(distribution_y)), style=label.style_label_left, textalign=text.align_left, tooltip=str.tostring(distribution_x) + '\n' + str.tostring(distribution_y))) array.push(graph_lines, line.new(bar_index, _bottom, bar_index, _top, extend=extend.none, color=color.gray, style=line.style_dotted, width=2)) // axis x array.push(graph_lines, line.new(bar_index, _bottom, bar_index+int(_most_dense_index*1.5), _bottom, extend=extend.none, color=color.gray, style=line.style_dotted, width=2)) // axis y array.push(graph_lines, line.new(bar_index, _most_dense_level, bar_index + _most_dense_index, _most_dense_level, extend=extend.none, color=color.blue, style=line.style_dashed, width=1)) // most frequent value array.push(graph_lines, line.new(bar_index + _std_index, _bottom, bar_index + _std_index, _top, color=color.orange, style=line.style_dashed)) // std //{ usage: //{ remarks: //}}} // @function Style the distribution lines. // @param lines line array, distribution lines to style. // @param horizontal bool, default=true, if the display is horizontal(true) or vertical(false). // @param to_histogram bool, default=false, if graph style should be switched to histogram. // @param line_color color, default=na, if defined will change the color of the lines. // @param line_style string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both) // @param linewidth int, default=na, if defined will change the line width. // @returns void. export style_distribution (line[] lines, bool horizontal=true, bool to_histogram=false, color line_color=na, string line_style=na, int line_width=na) => //{ int _size = array.size(lines) switch (_size < 1) => runtime.error('MathStatisticsKernelDensityEstimation -> style_distribution(): "lines" has the wrong size.') for _i = 0 to _size-1 line _line = array.get(lines, _i) if to_histogram if horizontal line.set_y1(_line, 0.0) line.set_x1(_line, line.get_x2(_line)) // TODO: this is bugged at the moment else line.set_x1(_line, bar_index) line.set_y1(_line, line.get_y2(_line)) if not na(line_color) line.set_color(_line, line_color) if not (line_style == '') line.set_style(_line, line_style) if not na(line_width) line.set_width(_line, line_width) //{ usage: //{ remarks: //}}} // @function Style the graph lines and labels // @param lines line array, graph lines to style. // @param lines labels array, graph labels to style. // @param horizontal bool, default=true, if the display is horizontal(true) or vertical(false). // @param line_color color, default=na, if defined will change the color of the lines. // @param line_style string, defaul=na, if defined will change the line style, options=('na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both) // @param linewidth int, default=na, if defined will change the line width. // @returns void. export style_graph ( line[] lines, label[] labels, color axis_x_color=na, string axis_x_style=na, int axis_x_width=na, color axis_y_color=na, string axis_y_style=na, int axis_y_width=na, color mostfreq_color=na, string mostfreq_style=na, int mostfreq_width=na, color std_color=na, string std_style=na, int std_width=na, color labels_color=na, color labels_text_color=na, string labels_size=na ) => //{ int _size = array.size(lines) switch (_size < 1) => runtime.error('MathStatisticsKernelDensityEstimation -> style_distribution(): "lines" has the wrong size.') // the lines line _axis_x = array.get(lines, 0) line _axis_y = array.get(lines, 1) line _mostfreq = array.get(lines, 2) line _stdline = array.get(lines, 3) // axis x if not na(axis_x_color) line.set_color(_axis_x, axis_x_color) if not (axis_x_style == '') line.set_style(_axis_x, axis_x_style) if not na(axis_x_width) line.set_width(_axis_x, axis_x_width) // axis y if not na(axis_y_color) line.set_color(_axis_y, axis_y_color) if not (axis_y_style == '') line.set_style(_axis_y, axis_y_style) if not na(axis_y_width) line.set_width(_axis_y, axis_y_width) // most freq if not na(mostfreq_color) line.set_color(_mostfreq, mostfreq_color) if not (mostfreq_style == '') line.set_style(_mostfreq, mostfreq_style) if not na(mostfreq_width) line.set_width(_mostfreq, mostfreq_width) // most freq if not na(std_color) line.set_color(_stdline, std_color) if not (std_style == '') line.set_style(_stdline, std_style) if not na(std_width) line.set_width(_stdline, std_width) // the labels if not na(labels_color) for _i = 0 to array.size(labels)-1 label.set_color(array.get(labels, _i), labels_color) if not na(labels_text_color) for _i = 0 to array.size(labels)-1 label.set_textcolor(array.get(labels, _i), labels_text_color) if not (labels_size == '') for _i = 0 to array.size(labels)-1 label.set_size(array.get(labels, _i), labels_size) //{ usage: //{ remarks: //}}} int sample_size = input.int(100) var float[] observations = array.new_float(sample_size) if barstate.isfirst for _i = 0 to sample_size-1 array.set(observations, _i, 50.0 + 100.0 * math.random()) string g_config = 'Configuration:' string i_kernel = input.string(title='Kernel:', defval='gaussian', options=['uniform', 'triangle', 'epanechnikov', 'quartic', 'triweight', 'gaussian', 'cosine', 'logistic', 'sigmoid'], tooltip='Kernel used in kde function.', group=g_config) float i_bandwidth = input.float(title='Bandwidth:', defval=0.618, tooltip='Bandwidth smoothness aplied to kernel.', group=g_config) int i_nstep = input.int(title='Nº Bins:', defval=20, tooltip='Number of Bins to split range.', group=g_config) [x, y] = kde(observations, i_kernel, i_bandwidth, i_nstep) na_str(string value) => value == 'na' ? na : value na_col(color value) => color.t(value) > 99 ? na : value na_width(int value) => value > 199 ? na : value bool horizontal = input.bool(true) bool histogram = input.bool(true) color line_color = na_col(input.color(defval=#ffffff00)) string line_style = na_str(input.string(defval='na', options=['na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both])) int line_width = na_width(input.int(200)) // graph options: color axis_x_color = na_col(input.color(defval=#ffffff00)) string axis_x_style = na_str(input.string(defval='na', options=['na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both])) int axis_x_width = na_width(input.int(200)) color axis_y_color = na_col(input.color(defval=#ffffff00)) string axis_y_style = na_str(input.string(defval='na', options=['na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both])) int axis_y_width = na_width(input.int(200)) color mostfreq_color = na_col(input.color(defval=#ffffff00)) string mostfreq_style = na_str(input.string(defval='na', options=['na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both])) int mostfreq_width = na_width(input.int(200)) color std_color = na_col(input.color(defval=#ffffff00)) string std_style = na_str(input.string(defval='na', options=['na', line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both])) int std_width = na_width(input.int(200)) color labels_color = na_col(input.color(defval=#ffffff00)) color labels_text_color = na_col(input.color(defval=#ffffff00)) string labels_size = na_str(input.string(defval='na', options=['na', size.tiny, size.small, size.normal, size.large, size.huge, size.auto])) line[] distribution_lines = array.new_line(0) line[] graph_lines = array.new_line(0) label[] graph_labels = array.new_label(0) if barstate.islast if horizontal draw_horizontal(x, y, distribution_lines, graph_lines, graph_labels) else draw_vertical(x, y, distribution_lines, graph_lines, graph_labels) distribution_lines := array.copy(distribution_lines) style_distribution(distribution_lines, horizontal, histogram, line_color, line_style, line_width) style_graph(graph_lines, graph_labels, axis_x_color, axis_x_style, axis_x_width, axis_y_color, axis_y_style, axis_y_width, mostfreq_color, mostfreq_style, mostfreq_width, std_color, std_style, std_width, labels_color, labels_text_color, labels_size )
log
https://www.tradingview.com/script/2nSunmfE-log/
GeoffHammond
https://www.tradingview.com/u/GeoffHammond/
33
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Geoff Hammond //@version=5 // @description Logging library for easily displaying debug, info, warn, error and critical messages library("log") // █ █▀█ █▀▀ █ █ █▄▄ █▀█ ▄▀█ █▀█ █▄█ // █▄▄ █▄█ █▄█ █▄▄ █ █▄█ █▀▄ █▀█ █▀▄ █ // @TODO: Realtime filtering. Console pagination. Styling. // ██╗ ██╗ ███████╗ ██╗ ██████╗ ███████╗ ██████╗ ██████╗ // ██║ ██║ ██╔════╝ ██║ ██╔══██╗ ██╔════╝ ██╔══██╗ ██╔════╝ // ███████║ █████╗ ██║ ██████╔╝ █████╗ ██████╔╝ ╚█████╗ // ██╔══██║ ██╔══╝ ██║ ██╔═══╝ ██╔══╝ ██╔══██╗ ╚═══██╗ // ██║ ██║ ███████╗ ███████╗ ██║ ███████╗ ██║ ██║ ██████╔╝ // ╚═╝ ╚═╝ ╚══════╝ ╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝ // COPY THESE HELPERS INTO YOUR SCRIPT // var LOG_TRACE = 1 // var LOG_DEBUG = 2 // var LOG_INFO = 3 // var LOG_WARNING = 4 // var LOG_ERROR = 5 // var LOG_FATAL = 6 // __LOG = log.init() // trace(msg, float val = na) => log.trace(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // debug(msg, float val = na) => log.debug(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // info(msg, float val = na) => log.info(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // warn(msg, float val = na) => log.warn(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // error(msg, float val = na) => log.error(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // fatal(msg, float val = na) => log.fatal(__LOG, str.tostring(msg) + (not na(val) ? str.format(': "{0}"', val) : '')) // log(int level, msg, color line_color = #c4c4c4) => log.log(__LOG, level, str.tostring(msg), line_color) // debug2(a, b) => log.debug(__LOG, str.format('{0} {1}', a, b)) // debug3(a, b, c) => log.debug(__LOG, str.format('{0} {1} {2}', a, b, c)) // debug4(a, b, c, d) => log.debug(__LOG, str.format('{0} {1} {2} {3}', a, b, c, d)) // debug5(a, b, c, d, e) => log.debug(__LOG, str.format('{0} {1} {2} {3} {4}', a, b, c, d, e)) // log_pass(level) => log.severity(__LOG) < na(level) ? LOG_ERROR : level // log_print(int level = 0, bool clear = false, bool force = false, int rows = 40, string text_size = na, string position = na, bool line_numbers = true) => // log.print(__LOG, level, clear, force, rows, text_size, position, line_numbers) // SOME USEFUL TIPS // By default the log console persists between bars (for history) and bars and ticks (for realtime). // Sometimes it is useful to clear the log after each candle or tick (assuming we are using the above helpers): // // log_print(clear = true) // starts afresh on every bar and tick (excludes historical bars but good realtime tick analysis) // log_print(clear = barstate.isnew) // clears the log at the start of each bar (again, excludes historical but good realtime candle analysis) // // It is also useful to be able to selectively understand the state of data at specific points or times within a script: // // if log.once() // debug('useful variable', my_var) // this log only gets written once, upon first execution of this statement // // if log.only(5) // debug3(a, b, c) // these variables are only logged the first five times this statement is executed // // log_print(clear = false) // clear must be false and you should not write other logs on every bar, or the above will be lost // // Final tip. If you want to view ONLY log entries of a particular level, then negate the constant: // // log_print(level = -LOG_DEBUG) // ██╗ ███╗ ███╗ ██████╗ █████╗ ██████╗ ████████╗ ██████╗ // ██║ ████╗ ████║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚══██╔══╝ ██╔════╝ // ██║ ██╔████╔██║ ██████╔╝ ██║ ██║ ██████╔╝ ██║ ╚█████╗ // ██║ ██║╚██╔╝██║ ██╔═══╝ ██║ ██║ ██╔══██╗ ██║ ╚═══██╗ // ██║ ██║ ╚═╝ ██║ ██║ ╚█████╔╝ ██║ ██║ ██║ ██████╔╝ // ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ import GeoffHammond/assert/4 // ██████╗ ██╗ █████╗ ██████╗ █████╗ ██╗ ██████╗ // ██╔════╝ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██╔════╝ // ██║ ██╗ ██║ ██║ ██║ ██████╦╝ ███████║ ██║ ╚█████╗ // ██║ ╚██╗ ██║ ██║ ██║ ██╔══██╗ ██╔══██║ ██║ ╚═══██╗ // ╚██████╔╝ ███████╗ ╚█████╔╝ ██████╦╝ ██║ ██║ ███████╗ ██████╔╝ // ╚═════╝ ╚══════╝ ╚════╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ var LOG_TRACE = 1 var LOG_DEBUG = 2 var LOG_INFO = 3 var LOG_WARN = 4 var LOG_ERROR = 5 var LOG_FATAL = 6 var FORMAT_TRACE = '[trace]: {0}' var FORMAT_DEBUG = '[debug]: {0}' var FORMAT_INFO = '[info]: {0}' var FORMAT_WARN = '[warn]: {0}' var FORMAT_ERROR = '[error]: {0}' var FORMAT_FATAL = '[fatal]: {0}' var FORMAT_LOG = '[log]: {0}' var FORMAT_LEVEL_SPLIT = ':' var FORMAT_LEVEL = '{0}:{1}:{2}:{3}' // level:r:g:b var FORMAT_LINE = '#{0} {1}' // line num:msg // ███████╗ ██╗ ██╗ ███╗ ██╗ █████╗ ████████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ // ██╔════╝ ██║ ██║ ████╗ ██║ ██╔══██╗ ╚══██╔══╝ ██║ ██╔══██╗ ████╗ ██║ ██╔════╝ // █████╗ ██║ ██║ ██╔██╗██║ ██║ ╚═╝ ██║ ██║ ██║ ██║ ██╔██╗██║ ╚█████╗ // ██╔══╝ ██║ ██║ ██║╚████║ ██║ ██╗ ██║ ██║ ██║ ██║ ██║╚████║ ╚═══██╗ // ██║ ╚██████╔╝ ██║ ╚███║ ╚█████╔╝ ██║ ██║ ╚█████╔╝ ██║ ╚███║ ██████╔╝ // ╚═╝ ╚═════╝ ╚═╝ ╚══╝ ╚════╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚══╝ ╚═════╝ array_get(arr, offset) => if array.size(arr) >= offset + 1 array.get(arr, offset) else na tuple_push(tuples, a, b) => array.push(tuples, a), array.push(tuples, b) tuple_set(tuples, offset, a, b) => array.set(tuples, offset * 2, a), array.set(tuples, (offset * 2) + 1, b) tuple_get(tuples, offset) => [array_get(tuples, offset * 2), array_get(tuples, (offset * 2) + 1)] tuple_size(tuples) => math.floor(array.size(tuples) / 2) tuple_remove(tuples, offset) => array.remove(tuples, offset * 2), array.remove(tuples, offset * 2) color_darken(_color, amount, int new_t = na) => float decimal = 1.0 - (amount / 100.0) float r = math.round(color.r(_color) * decimal) float g = math.round(color.g(_color) * decimal) float b = math.round(color.b(_color) * decimal) float t = new_t ? new_t : color.t(_color) color.rgb(r, g, b, t) // ██╗ █████╗ ██████╗ // ██║ ██╔══██╗ ██╔════╝ // ██║ ██║ ██║ ██║ ██╗ // ██║ ██║ ██║ ██║ ╚██╗ // ███████╗ ╚█████╔╝ ╚██████╔╝ // ╚══════╝ ╚════╝ ╚═════╝ write(string[] msgs, string msg, int level, color line_color) => lvl = str.format(FORMAT_LEVEL, level, color.r(line_color), color.g(line_color), color.b(line_color)) tuple_push(msgs, str.tostring(msg), lvl) msg_level(string lvl) => math.round(str.tonumber(array.get(str.split(lvl, FORMAT_LEVEL_SPLIT), 0))) filter(string[] unfiltered, int filter_level, bool clear, int limit, bool line_numbers = true) => varip console = array.new_string() varip total = 0 if clear array.clear(console) total := 0 unfiltered_size = tuple_size(unfiltered) if unfiltered_size filtered = array.new_string() count = 0 for i = unfiltered_size - 1 to 0 [msg, lvl] = tuple_get(unfiltered, i) level = msg_level(lvl) if (filter_level >= 0 and level >= filter_level) or (filter_level < 0 and level == -filter_level) count += 1 tuple_push(filtered, msg, lvl) if count == limit break filtered_size = tuple_size(filtered) if filtered_size for i = filtered_size - 1 to 0 total += 1 [msg, lvl] = tuple_get(filtered, i) tuple_push(console, line_numbers ? str.format(FORMAT_LINE, total, msg) : msg, lvl) if tuple_size(console) > limit tuple_remove(console, 0) array.clear(unfiltered) console msg_color(string lvl) => parts = str.split(lvl, FORMAT_LEVEL_SPLIT) if array.size(parts) == 4 r = str.tonumber(array.get(parts, 1)) g = str.tonumber(array.get(parts, 2)) b = str.tonumber(array.get(parts, 3)) color.rgb(r, g, b) else runtime.error(str.format('[Log:msg_color] Unable to process color for level: {0}', lvl)) color.red // ██╗ ██╗ ██████╗ ██████╗ █████╗ ██████╗ ██╗ ██╗ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚██╗ ██╔╝ // ██║ ██║ ██████╦╝ ██████╔╝ ███████║ ██████╔╝ ╚████╔╝ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██║ ██╔══██╗ ╚██╔╝ // ███████╗ ██║ ██████╦╝ ██║ ██║ ██║ ██║ ██║ ██║ ██║ // ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ // @function Restrict execution to only happen once. Usage: if log.once()\n happens_once() // @returns bool, true on first execution within scope, false subsequently export once() => varip pending = true if pending pending := false true else false // @function Restrict execution to happen a set number of times. Usage: if log.only(5)\n happens_five_times() // @param repeat int, the number of times to return true // @returns bool, true for the set number of times within scope, false subsequently export only(int repeat = 1) => var done = 0 if done < repeat done += 1 true else false // @function Initialises the log array // @returns string[], tuple based array to contain all pending log entries (__LOG) export init() => varip msgs = array.new_string() // @function Clears the log array // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) export clear(string[] msgs) => array.clear(msgs) // @function Writes a trace message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the trace message to write to the log export trace(string[] msgs, string msg) => write(msgs, str.format(FORMAT_TRACE, msg), LOG_TRACE, #00d5ca) // @function Writes a debug message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the debug message to write to the log export debug(string[] msgs, string msg) => write(msgs, str.format(FORMAT_DEBUG, msg), LOG_DEBUG, #b300ff) // @function Writes an info message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the info message to write to the log export info(string[] msgs, string msg) => write(msgs, str.format(FORMAT_INFO, msg), LOG_INFO, #e6e6e6) // @function Writes a warning message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the warn message to write to the log export warn(string[] msgs, string msg) => write(msgs, str.format(FORMAT_WARN, msg), LOG_WARN, #d47400) // @function Writes an error message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the error message to write to the log export error(string[] msgs, string msg) => write(msgs, str.format(FORMAT_ERROR, msg), LOG_ERROR, #d42000) // @function Writes a critical message to the log console // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param msg string, the fatal message to write to the log export fatal(string[] msgs, string msg) => write(msgs, str.format(FORMAT_FATAL, msg), LOG_FATAL, #d40000) // @function Write a log message to the log console with a custom level // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param level ing, the logging level to assign to the message // @param msg string, the log message to write to the log export log(string[] msgs, int level, string msg, color line_color = #c4c4c4) => write(msgs, str.format(FORMAT_LOG, msg), level, line_color) // @function Checks the unprocessed log messages and returns the highest present level // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @returns int, the highest level found within the unfiltered logs export severity(string[] msgs) => severity = 0 size = tuple_size(msgs) if size for i = 0 to size - 1 [msg, lvl] = tuple_get(msgs, i) level = msg_level(lvl) if level > severity severity := level severity // @function Prints all log messages to the screen // @param msgs string[], the current collection of unfiltered and unprocessed logs (__LOG) // @param level int, the minimum required log level of each message to be displayed // @param clear bool, clear the printed log console after each render (useful with realtime when set to barstate.isconfirmed) // @param rows int, the number of rows to display in the log console // @param text_size string, the text size of the log console (global size vars) // @param position string, the position of the log console (global position vars) // @param line_numbers bool, disable the automatic prepending of line numbers export print(string[] msgs, int level = 0, bool clear = false, bool force = false, int rows = 40, string text_size = na, string position = na, bool line_numbers = true) => console = filter(msgs, level, clear, rows, line_numbers) if barstate.islast or force size = tuple_size(console) if size var tbl = table.new(na(position) ? position.bottom_left : position, 1, rows, #000000, #FFFFFF, 1) table.clear(tbl, 0, 0, 0, rows - 1) for i = 0 to size - 1 [msg, lvl] = tuple_get(console, i) color = msg_color(lvl) bgcolor = color_darken(color, 96) table.cell(tbl, 0, i, msg, text_color=color, text_halign=text.align_left, text_size=na(text_size) ? size.normal : text_size, bgcolor=bgcolor) // ██╗ ██╗ ███╗ ██╗ ██╗ ████████╗ ████████╗ ███████╗ ██████╗ ████████╗ ██████╗ // ██║ ██║ ████╗ ██║ ██║ ╚══██╔══╝ ╚══██╔══╝ ██╔════╝ ██╔════╝ ╚══██╔══╝ ██╔════╝ // ██║ ██║ ██╔██╗██║ ██║ ██║ ██║ █████╗ ╚█████╗ ██║ ╚█████╗ // ██║ ██║ ██║╚████║ ██║ ██║ ██║ ██╔══╝ ╚═══██╗ ██║ ╚═══██╗ // ╚██████╔╝ ██║ ╚███║ ██║ ██║ ██║ ███████╗ ██████╔╝ ██║ ██████╔╝ // ╚═════╝ ╚═╝ ╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ // @function Log module unit tests, for inclusion in parent script test suite. Usage: log.unittest_log(__ASSERTS) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) export unittest_log(string[] case) => assert.new_case(case, 'Log:once') assert.is_true(once(), case) assert.is_true(once(), case) for i = 1 to 3 trigger = once() if i == 1 assert.is_true(trigger, case) else assert.is_false(trigger, case) assert.new_case(case, 'Log:only') assert.is_true(only(), case) assert.is_false(only(0), case) // but why? assert.is_true(only(1), case) assert.is_true(only(2), case) for i = 1 to 3 trigger = only(2) if i <= 2 assert.is_true(trigger, case) else assert.is_false(trigger, case) __LOG = init() assert.new_case(case, 'Log:init') assert.str_array_equal(__LOG, array.new_string(), case) assert.new_case(case, 'Log:write') write(__LOG, 'msg', 1, color.white) assert.str_array_equal(__LOG, array.from('msg', '1:255:255:255'), case) write(__LOG, 'msg2', 2, #000000) assert.str_array_equal(__LOG, array.from('msg', '1:255:255:255', 'msg2', '2:0:0:0'), case) assert.new_case(case, 'Log:clear') clear(__LOG) assert.str_array_equal(__LOG, array.new_string(), case) assert.new_case(case, 'Log:trace') trace(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_TRACE, 'msg'), str.format(FORMAT_LEVEL, LOG_TRACE, 0, 213, 202)), case) clear(__LOG) assert.new_case(case, 'Log:debug') debug(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_DEBUG, 'msg'), str.format(FORMAT_LEVEL, LOG_DEBUG, 179, 0, 255)), case) clear(__LOG) assert.new_case(case, 'Log:info') info(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_INFO, 'msg'), str.format(FORMAT_LEVEL, LOG_INFO, 230, 230, 230)), case) clear(__LOG) assert.new_case(case, 'Log:warn') warn(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_WARN, 'msg'), str.format(FORMAT_LEVEL, LOG_WARN, 212, 116, 0)), case) clear(__LOG) assert.new_case(case, 'Log:error') error(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_ERROR, 'msg'), str.format(FORMAT_LEVEL, LOG_ERROR, 212, 32, 0)), case) clear(__LOG) assert.new_case(case, 'Log:fatal') fatal(__LOG, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_FATAL, 'msg'), str.format(FORMAT_LEVEL, LOG_FATAL, 212, 0, 0)), case) clear(__LOG) assert.new_case(case, 'Log:log') log(__LOG, 9, 'msg') assert.str_array_equal(__LOG, array.from(str.format(FORMAT_LOG, 'msg'), str.format(FORMAT_LEVEL, 9, 196, 196, 196)), case) clear(__LOG) log(__LOG, 9, 'msg', #000000) assert.str_array_equal(__LOG, array.from(str.format(FORMAT_LOG, 'msg'), str.format(FORMAT_LEVEL, 9, 0, 0, 0)), case) clear(__LOG) assert.new_case(case, 'Log:severity') trace(__LOG, 'msg'), assert.equal(severity(__LOG), 1, case) debug(__LOG, 'msg'), assert.equal(severity(__LOG), 2, case) info(__LOG, 'msg'), assert.equal(severity(__LOG), 3, case) warn(__LOG, 'msg'), assert.equal(severity(__LOG), 4, case) error(__LOG, 'msg'), assert.equal(severity(__LOG), 5, case) fatal(__LOG, 'msg'), assert.equal(severity(__LOG), 6, case) log(__LOG, 9, 'msg'), assert.equal(severity(__LOG), 9, case) assert.new_case(case, 'Log:msg_level') assert.equal(msg_level('1'), 1, case) assert.equal(msg_level(str.format('{0}', 1)), 1, case) assert.equal(msg_level(str.format('{0}{1}{2}', 1, FORMAT_LEVEL_SPLIT, 2)), 1, case) assert.equal(msg_level(str.format('{0}{1}{2}', 1, FORMAT_LEVEL_SPLIT, 2)), 1, case) assert.equal(msg_level(str.format(FORMAT_LEVEL, 1, 255, 255, 255)), 1, case) assert.equal(msg_level(str.format(FORMAT_LEVEL, 1, 0, 0, 0)), 1, case) assert.equal(msg_level(str.format(FORMAT_LEVEL, 1, 'in', 'theory', 'anything')), 1, case) assert.new_case(case, 'Log:msg_color') assert.color_equal(msg_color('0:255:255:255'), #FFFFFF, case) assert.color_equal(msg_color('0:0:0:0'), #000000, case) assert.color_equal(msg_color('0:0:213:202'), #00d5ca, case) assert.color_equal(msg_color('0:179:0:255'), #b300ff, case) assert.color_equal(msg_color('0:230:230:230'), #e6e6e6, case) assert.color_equal(msg_color('0:212:116:0'), #d47400, case) assert.color_equal(msg_color('0:212:32:0'), #d42000, case) assert.color_equal(msg_color('0:212:0:0'), #d40000, case) assert.color_equal(msg_color('0:196:196:196'), #c4c4c4, case) clear(__LOG) assert.new_case(case, 'Log:filter') write(__LOG, 'one', 1, #000000) write(__LOG, 'two', 2, #000000) write(__LOG, 'three', 3, #000000) lvl1 = str.format(FORMAT_LEVEL, 1, 0, 0, 0) lvl2 = str.format(FORMAT_LEVEL, 2, 0, 0, 0) lvl3 = str.format(FORMAT_LEVEL, 3, 0, 0, 0) assert.str_array_equal(filter(array.copy(__LOG), 1, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'one'), lvl1, str.format(FORMAT_LINE, 2, 'two'), lvl2, str.format(FORMAT_LINE, 3, 'three'), lvl3), case) assert.str_array_equal(filter(array.copy(__LOG), 2, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'two'), lvl2, str.format(FORMAT_LINE, 2, 'three'), lvl3), case) assert.str_array_equal(filter(array.copy(__LOG), 3, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'three'), lvl3), case) assert.str_array_equal(filter(array.copy(__LOG), -1, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'one'), lvl1), case) assert.str_array_equal(filter(array.copy(__LOG), -2, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'two'), lvl2), case) assert.str_array_equal(filter(array.copy(__LOG), -3, false, 5, true), array.from(str.format(FORMAT_LINE, 1, 'three'), lvl3), case) assert.str_array_equal(filter(array.copy(__LOG), 1, false, 5, false), array.from('one', lvl1, 'two', lvl2, 'three', lvl3), case) write(__LOG, 'two', 2, #000000) for i = 0 to 2 write(__LOG, i % 2 == 0 ? 'one' : 'two', i % 2 == 0 ? 1 : 2, #000000) console = filter(__LOG, 1, false, 2) if i % 2 == 0 assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 1 + i, 'two'), lvl2, str.format(FORMAT_LINE, 2 + i, 'one'), lvl1), case, str.format('loop1 #{0}', i + 1)) else assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 1 + i, 'one'), lvl1, str.format(FORMAT_LINE, 2 + i, 'two'), lvl2), case, str.format('loop1 #{0}', i + 1)) for i = 0 to 2 write(__LOG, i % 2 == 0 ? 'one' : 'two', i % 2 == 0 ? 1 : 2, #000000) console = filter(__LOG, 1, true, 2) assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 1, i % 2 == 0 ? 'one': 'two'), i % 2 == 0 ? lvl1 : lvl2), case, str.format('loop2 #{0}', i + 1)) for i = 0 to 2 write(__LOG, 'one', 1, #000000) write(__LOG, 'three', 3, #000000) write(__LOG, i % 2 == 0 ? 'one' : 'two', i % 2 == 0 ? 1 : 2, #000000) console = filter(__LOG, 2, false, 2) if i == 0 assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 1, 'three'), lvl3), case, str.format('loop3 #{0}', i + 1)) else if i == 1 assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 2, 'three'), lvl3, str.format(FORMAT_LINE, 3, 'two'), lvl2), case, str.format('loop3 #{0}', i + 1)) else if i == 2 assert.str_array_equal(console, array.from(str.format(FORMAT_LINE, 3, 'two'), lvl2, str.format(FORMAT_LINE, 4, 'three'), lvl3), case, str.format('loop3 #{0}', i + 1)) // @function Run the log module unit tests as a stand alone. Usage: log.unittest() // @param verbose bool, optionally disable the full report to only display failures export unittest(bool verbose = true) => if assert.once() __ASSERTS = assert.init() unittest_log(__ASSERTS) assert.report(__ASSERTS, verbose) // ██████╗ ██╗ ██╗ ███╗ ██╗ // ██╔══██╗ ██║ ██║ ████╗ ██║ // ██████╔╝ ██║ ██║ ██╔██╗██║ // ██╔══██╗ ██║ ██║ ██║╚████║ // ██║ ██║ ╚██████╔╝ ██║ ╚███║ // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══╝ unittest() __LOG = init() if once() trace(__LOG, 'Hi') debug(__LOG, 'Sigh') info(__LOG, 'Ooh') warn(__LOG, 'Gah') error(__LOG, 'Yikes') fatal(__LOG, '#$@*') log(__LOG, 8, 'Umm') log(__LOG, 9, 'Mmmmm (custom colors)', #ed8cb4) print(__LOG) // __ // /. _\ // .--.|/_/__ // ''.--o/___ \ // /.'o|_o '.| // |/ |_| ' // ' |_| Ooh, a fatal bug warning! // |_| / // |_[~] o // |_| U> // |_| H
enhanced_ta
https://www.tradingview.com/script/Puxp2q46-enhanced-ta/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
105
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // //@version=5 // @description Collection of all custom and enhanced TA indicators library("enhanced_ta", overlay=true) import HeWhoMustNotBeNamed/arrayutils/17 as pa bandwidth(float middle, float upper, float lower)=> 100*(upper-lower)/middle percentb(float source, float upper, float lower)=> 100*(source-lower)/(upper-lower) customseries(float source=close, simple string type="sma", simple int length) => switch type "ema" => ta.ema(source, length) "sma" => ta.sma(source, length) "rma" => ta.rma(source, length) "hma" => ta.hma(source, length) "wma" => ta.wma(source, length) "vwma" => ta.vwma(source, length) "swma" => ta.swma(source) "linreg" => ta.linreg(source, length, 0) "median" => ta.median(source, length) "mom" => ta.mom(source, length) "high" => ta.highest(source, length) "low" => ta.lowest(source, length) "medianHigh" => ta.median(ta.highest(source, length), length) "medianLow" => ta.median(ta.lowest(source, length), length) "percentrank" => ta.percentrank(source, length) => (ta.highest(length) + ta.lowest(length))/2 getStickyRange(float highsource, float lowsource, float upper, float lower, simple bool sticky=false)=> newUpper = upper newLower = lower highBreakout = highsource[1] >= newUpper[1] lowBreakout = lowsource[1] <= newLower[1] newUpper := (highBreakout or lowBreakout or not sticky)? newUpper : nz(newUpper[1], newUpper) newLower := (highBreakout or lowBreakout or not sticky)? newLower : nz(newLower[1], newLower) [newUpper, newLower] // @function returns custom moving averages // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns moving average for the given type and length export ma(float source=close, simple string maType="sma", simple int length) => customseries(source, maType, length) // @function returns ATR with custom moving average // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns ATR for the given moving average type and length export atr(simple string maType="sma", simple int length) => customseries(ta.tr, maType, length) // @function returns ATR as percentage of close price // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns ATR as percentage of close price for the given moving average type and length export atrpercent(simple string maType="sma", simple int length) => 100*atr(maType, length)/close // @function returns Bollinger band for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger band with custom moving average for given source, length and multiplier export bb(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => float middle = ma(source, maType, length) float upper = middle + ta.stdev(source, length)*multiplier float lower = middle - ta.stdev(source, length)*multiplier [newUpper, newLower] = getStickyRange(high, low, upper, lower, sticky) upper := newUpper lower := newLower [middle, upper, lower] // @function returns Bollinger bandwidth for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger Bandwidth for custom moving average for given source, length and multiplier export bbw(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => [middle, upper, lower] = bb(source, maType, length, multiplier, sticky) bandwidth(middle, upper, lower) // @function returns Bollinger Percent B for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger Percent B for custom moving average for given source, length and multiplier export bpercentb(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => [middle, upper, lower] = bb(source, maType, length, multiplier, sticky) percentb(source, upper, lower) // @function returns Keltner Channel for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Channel for custom moving average for given souce, length and multiplier export kc(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => float middle = ma(source, maType, length) float span = (useTrueRange) ? ta.tr : (high - low) float rangeMa = ma(span, maType, length) float upper = middle + rangeMa*multiplier float lower = middle - rangeMa*multiplier [newUpper, newLower] = getStickyRange(high, low, upper, lower, sticky) upper := newUpper lower := newLower [middle, upper, lower] // @function returns Keltner Channel Width with custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Channel Width for custom moving average export kcw(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => [middle, upper, lower] = kc(source, maType, length, multiplier, useTrueRange, sticky) bandwidth(middle, upper, lower) // @function returns Keltner Channel Percent K Width with custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Percent K for given moving average, source, length and multiplier export kpercentk(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => [middle, upper, lower] = kc(source, maType, length, multiplier, useTrueRange, sticky) percentb(source, upper, lower) // @function returns Custom Donchian Channel // @param length - donchian channel length // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel export dc(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => highSource = useAlternateSource? alternateSource : high lowSource = useAlternateSource? alternateSource : low [upper, lower] = getStickyRange(highSource, lowSource, ta.highest(highSource, length), ta.lowest(lowSource, length), sticky) middle = (upper+lower)/2 [middle, upper, lower] // @function returns Donchian Channel Width // @param length - donchian channel length // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel width export dcw(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => [middle, upper, lower] = dc(length, useAlternateSource, alternateSource, sticky) bandwidth(middle, upper, lower) // @function returns Donchian Channel Percent of price // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param length - donchian channel length // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel Percent D export dpercentd(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => [middle, upper, lower] = dc(length, useAlternateSource, alternateSource, sticky) percentb(useAlternateSource? alternateSource : hl2, upper, lower) // @function oscillatorRange - returns Custom overbought/oversold areas for an oscillator input // @param source - Osillator source such as RSI, COG etc. // @param method - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param highlowLength - length on which highlow of the oscillator is calculated // @param rangeLength - length used for calculating oversold/overbought range - usually same as oscillator length // @param sticky - overbought, oversold levels won't change unless crossed // @returns Dynamic overbought and oversold range for oscillator input export oscillatorRange(float source, simple string method="highlow", simple int highlowLength=50, simple int rangeLength=14, simple bool sticky=false) => oscillatorHighest = customseries(source, "high", highlowLength) oscillatorLowest = customseries(source, "low", highlowLength) oscOverbought = customseries(oscillatorHighest, method == "highlow"? "low" : method, rangeLength) oscOversold = customseries(oscillatorLowest, method == "highlow"? "high" : method, rangeLength) getStickyRange(source, source, oscOverbought, oscOversold, sticky) // @function oscillator - returns Choice of oscillator with custom overbought/oversold range // @param type - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr // @param length - Oscillator length - not used for TSI // @param shortLength - shortLength only used for TSI // @param longLength - longLength only used for TSI // @param source - custom source if required // @param highSource - custom high source for stochastic oscillator // @param lowSource - custom low source for stochastic oscillator // @param method - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param highlowLength - length on which highlow of the oscillator is calculated // @param sticky - overbought, oversold levels won't change unless crossed // @returns Oscillator value along with dynamic overbought and oversold range for oscillator input export oscillator(simple string type="rsi", simple int length=14, simple int shortLength = 13, simple int longLength = 25, float source = close, float highSource = high, float lowSource = low, simple string method="highlow", simple int highlowLength=50, simple bool sticky=false)=> oscillator = switch type "cci" => ta.cci(source, length) "cmo" => ta.cmo(source, length) "cog" => ta.cog(source, length) "mfi" => ta.mfi(source, length) "roc" => ta.roc(source, length) "rsi" => ta.rsi(source, length) "stoch" => ta.stoch(source, highSource, lowSource, length) "tsi" => ta.tsi(source, shortLength, longLength) "wpr" => ta.wpr(length) => ta.rsi(source, length) [overbought, oversold] = oscillatorRange(oscillator, method, highlowLength, length, sticky) [oscillator, overbought, oversold] // @function multibands - returns Choice of oscillator with custom overbought/oversold range // @param bandType - Band type - can be either bb or kc // @param source - custom source if required // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length - Oscillator length - not used for TSI // @param useTrueRange - if set to false, uses high-low. // @param sticky - for sticky borders which only change upon source crossover/crossunder // @param numberOfBands - Number of bands to generate // @param multiplierStart - Starting ATR or Standard deviation multiplier for first band // @param multiplierStep - Incremental value for multiplier for each band // @returns array of band values sorted in ascending order export multibands(simple string bandType="bb", float source=close, simple string maType = "sma", simple int length = 60, simple bool useTrueRange=true, simple bool sticky=false, simple int numberOfBands=7, simple float multiplierStart = 0.5, simple float multiplierStep = 0.5)=> bands = array.new_float() for i=0 to numberOfBands-1 multiplier = multiplierStart + i*multiplierStep middle = 0.0 upper = 0.0 lower = 0.0 if(bandType == "bb") [bbmiddle, bbupper, bblower] = bb(source, maType, length, multiplier, sticky) middle := bbmiddle upper := bbupper lower := bblower else [kcmiddle, kcupper, kclower] = kc(source, maType, length, multiplier, useTrueRange, sticky) middle := kcmiddle upper := kcupper lower := kclower array.unshift(bands, lower) array.unshift(bands, upper) if(i == 0) array.unshift(bands, middle) array.sort(bands) bands // @function mbandoscillator - Multiband oscillator created on the basis of bands // @param bandType - Band type - can be either bb or kc // @param source - custom source if required // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length - Oscillator length - not used for TSI // @param useTrueRange - if set to false, uses high-low. // @param stickyBands - for sticky borders which only change upon source crossover/crossunder for band detection // @param numberOfBands - Number of bands to generate // @param multiplierStart - Starting ATR or Standard deviation multiplier for first band // @param multiplierStep - Incremental value for multiplier for each band // @returns oscillator currentStates - Array containing states for last n bars export mbandoscillator(simple string bandType="kc", float source=close, simple string maType = "sma", simple int length = 60, simple bool useTrueRange=false, simple bool stickyBands=false, simple int numberOfBands=100, simple float multiplierStart = 0.5, simple float multiplierStep = 0.5 )=> states = multibands(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep) currentState = array.size(states) for i = 0 to array.size(states) - 1 by 1 if source < array.get(states, i) currentState := i break currentState // @function finds difference between two timestamps // @param timeStart - start timestamp // @param endTime - end timestamp export timer(int timeStart, int timeEnd=timenow)=> timeDiff = math.abs(timeEnd - timeStart) mseconds = timeDiff seconds = mseconds/1000 minutes = seconds/60 hours = minutes/60 days = hours/24 tmSeconds = mseconds%1000 tSeconds = seconds%60 tMinutes = minutes%60 tHours = hours%24 [days, tHours, tMinutes, tSeconds, tmSeconds] //******************************************** USAGE ****************************************** // display = input.string("multibands", title="Display Indicator", options=["all", "ma", "atr", "multibands", "band", "bandwidth", "bandpercent","oscillator"]) overlay = input.bool(true, title="Overlay", inline="o") nonOverlay = input.bool(true, title="NonOverlay", inline="o") //************************************ ma *************************************************** // masource = input.source(close, title="Source", group="Moving Average") matype = input.string("sma", title="Type", group="Moving Average", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"]) malength = input.int(20, title="Length", group="Moving Average") _ma = ma(masource, matype, malength) displayMa = display == "ma" or (display == "all" and overlay) plot(displayMa? _ma : na, title="Moving Average", color=color.blue) //************************************ ATR *************************************************** // amatype = input.string("sma", title="Type", group="ATR", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"]) amalength = input.int(20, title="Length", group="ATR") displayPercent = input.bool(false, title="Display as Percent", group="ATR") _atr = atr(amatype, amalength) _atrpercent = atrpercent(amatype, amalength) displayAtr = display == "atr" or (display == "all" and nonOverlay) plot(displayAtr? displayPercent? _atrpercent : _atr : na, title="ATR (or Percent)", color = color.blue) //************************************ bands *************************************************** // bandType = input.string("BB", title="Type", group="Bands/Bandwidth/BandPercent", options=["BB", "KC", "DC"]) bmasource = input.source(close, title="Source", group="Bands/Bandwidth/BandPercent") bmatype = input.string("sma", title="Type", group="Bands/Bandwidth/BandPercent", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"]) bmalength = input.int(20, title="Length", group="Bands/Bandwidth/BandPercent") multiplier = input.float(2.0, step=0.5, title="Multiplier", group="Bands/Bandwidth/BandPercent") useTrueRange = input.bool(true, title="Use True Range (KC)", group="Bands/Bandwidth/BandPercent") useAlternateSource = input.bool(false, title="Use Alternate Source (DC)", group="Bands/Bandwidth/BandPercent") bsticky = input.bool(true, title="Sticky", group="Bands/Bandwidth/BandPercent") displayBands = display == "band" or (display == "all" and overlay) var cloudTransparency = 90 [bbmiddle, bbupper, bblower] = bb(bmasource, bmatype, bmalength, multiplier, sticky=bsticky) [kcmiddle, kcupper, kclower] = kc(bmasource, bmatype, bmalength, multiplier, useTrueRange, sticky=bsticky) [dcmiddle, dcupper, dclower] = dc(bmalength, useAlternateSource, bmasource, sticky=bsticky) upper = bandType == "BB"? bbupper : bandType == "KC"? kcupper : dcupper lower = bandType == "BB"? bblower : bandType == "KC"? kclower : dclower middle = bandType == "BB"? bbmiddle : bandType == "KC"? kcmiddle : dcmiddle uPlot = plot(displayBands? upper: na, title="Upper", color=color.new(color.green, cloudTransparency)) lPlot = plot(displayBands? lower: na, title="Lower", color=color.new(color.red, cloudTransparency)) mPlot = plot(displayBands? middle: na, title="Middle", color=color.new(color.blue, cloudTransparency)) fill(uPlot, mPlot, title='UpperRange', color=color.new(color.green, cloudTransparency)) fill(lPlot, mPlot, title='LowerRange', color=color.new(color.red, cloudTransparency)) //************************************ bandwidth *************************************************** // _bbw = bbw(bmasource, bmatype, bmalength, multiplier, sticky=bsticky) _kcw = kcw(bmasource, bmatype, bmalength, multiplier, useTrueRange, sticky=bsticky) _dcw = dcw(bmalength, useAlternateSource, bmasource, sticky=bsticky) _bandwidth = bandType == "BB"? _bbw : bandType == "KC"? _kcw : _dcw _displayBandwidth = display == "bandwidth" or (display == "all" and nonOverlay) plot(_displayBandwidth? _bandwidth: na, title="Bandwidth", color=color.maroon) //************************************ bandpercent *************************************************** // _bpercentb = bpercentb(bmasource, bmatype, bmalength, multiplier, sticky=bsticky) _kpercentk = kpercentk(bmasource, bmatype, bmalength, multiplier, useTrueRange, sticky=bsticky) _dpercentd = dpercentd(bmalength, useAlternateSource, bmasource, sticky=bsticky) _bandpercent = bandType == "BB"? _bpercentb : bandType == "KC"? _kpercentk : _dpercentd _displayBandPercent = display == "bandpercent" or (display == "all" and nonOverlay) plot(_displayBandPercent? _bandpercent: na, title="BandPercent", color=color.fuchsia) //************************************ Oscillators *************************************************** // oscType = input.string("cci", title="Oscillator Type", group="Oscillator", options=["cci", "cmo", "cog", "mfi", "roc", "rsi", "stoch", "tsi", "wpr"]) oLength = input.int(14, title="Length", group="Oscillator") shortLength = input.int(9, title="Short Length (TSI)", group="Oscillator") longLength = input.int(9, title="Long Length (TSI)", group="Oscillator") method = input.string("highlow", title="Dynamic Overvought/Oversold Calculation method", group="Oscillator", options=["highlow", "sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"]) highlowlength = input.int(50, title="Length", group="Oscillator") osticky = input.bool(true, title="Sticky", group="Oscillator") [_oscillator, _overbought, _oversold] = oscillator(oscType, oLength, shortLength, longLength, method = method, highlowLength=highlowlength, sticky=osticky) // Just using oscillatorRange with only oscillator input // [newUpper, newLower] = oscillatorRange(oscillator, method, highlowlength, oLength, osticky) _displayOscillator = display == "oscillator" or (display == "all" and nonOverlay) plot(_displayOscillator? _oscillator: na, title="Oscillator", color=color.blue) plot(_displayOscillator? _overbought: na, title="Overbought", color=color.red) plot(_displayOscillator? _oversold: na, title="Oversold", color=color.green) bands = multibands() _displayMultibands = (display == "multibands" or (display == "all" and overlay)) and array.size(bands) == 15 plot(_displayMultibands? array.get(bands, 0): na, title="L7", color=color.red) plot(_displayMultibands? array.get(bands, 1): na, title="L6", color=color.red) plot(_displayMultibands? array.get(bands, 2): na, title="L5", color=color.red) plot(_displayMultibands? array.get(bands, 3): na, title="L4", color=color.red) plot(_displayMultibands? array.get(bands, 4): na, title="L3", color=color.red) plot(_displayMultibands? array.get(bands, 5): na, title="L2", color=color.red) plot(_displayMultibands? array.get(bands, 6): na, title="L1", color=color.red) plot(_displayMultibands? array.get(bands, 7): na, title="M", color=color.blue) plot(_displayMultibands? array.get(bands, 8): na, title="U1", color=color.green) plot(_displayMultibands? array.get(bands, 9): na, title="U2", color=color.green) plot(_displayMultibands? array.get(bands, 10): na, title="U3", color=color.green) plot(_displayMultibands? array.get(bands, 11): na, title="U4", color=color.green) plot(_displayMultibands? array.get(bands, 12): na, title="U5", color=color.green) plot(_displayMultibands? array.get(bands, 13): na, title="U6", color=color.green) plot(_displayMultibands? array.get(bands, 14): na, title="U7", color=color.green)
FunctionDecisionTree
https://www.tradingview.com/script/mH1N5tpz-FunctionDecisionTree/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
27
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Method to generate decision tree based on weights. library(title='FunctionDecisionTree') // @function Method to generate decision tree based on weights. // @param weights float array, weights for decision consideration. // @param depth int, depth of the tree. // @returns int array export decision_tree(float[] weights, int depth) => //{ int _size_w = array.size(id=weights) // int[] _path = array.new_int(size=0, initial_value=0) int _sumweights = math.ceil(array.sum(id=weights)) if _size_w > 0 and depth > 0 and _sumweights == 1 for _d = 1 to depth by 1 for _w = 0 to 999 by 1 int _select_weight_index = int(math.random(max=_size_w)) float _rng = math.random(max=1.0) float _weight = array.get(id=weights, index=_select_weight_index) if _weight >= _rng array.push(id=_path, value=_select_weight_index) break _path //{ usage: // Input Parameters: int depth = input.int(defval=1, minval=1) int paths = input.int(defval=2, minval=1) int number_of_weights = input.int(defval=2, minval=1) // Array to contain weights, sum of array values must be 1. var float[] node_weights = array.new_float(size=number_of_weights, initial_value=0) if barstate.isfirst float _weight = 1.0 / number_of_weights for _i=1 to number_of_weights array.set(node_weights, _i-1, _weight) string t = '' for _p = 1 to paths by 1 _path = decision_tree(node_weights, depth) t := t + '\nPath ' + str.tostring(_p, '#') + ': ' + str.tostring(_path) t var label la = label.new(bar_index, 0.0, t) //{ remarks: //}}}
Signal_Data_2021_09_09__2021_11_18
https://www.tradingview.com/script/eGaloNLV-Signal-Data-2021-09-09-2021-11-18/
ubiquity
https://www.tradingview.com/u/ubiquity/
5
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © ubiquity //@version=5 // @description Functions to support my timing signals system library("Signal_Data_2021_09_09__2021_11_18", overlay=true) // import ubiquity/DebugConsole/1 as dbug // @function parses a string into smaller strings and stores them in an array // @param _arr is the array to store the shorter strings // @param str is the string to parse // @param sep is the sentinal value used to separate the string into smaller strings // @returns nothing. the parsed strings are all in the array stringArrayAppend(_arr, str, sep) => var string[] str_a = str.split(str, sep) for i = 0 to array.size(str_a) - 1 by 1 if array.size(str_a) > 0 ts = array.shift(str_a) array.push(_arr, ts) // ====================================================================== // All the data below is from an external preprocessing system // ====================================================================== // pine script limits string length to 4096. // So to bypass this limitation the external preprocessor chops up long strings of data into multiple strings // Then the stringArrayAppend function parses them all into a single array. // You can see this with strings H03, H04, H06 and H08 as they are used multiple times. var H01_str1 = '1624428394,1,250.7,12,250.7;1624692925,1,296.07,9,296.07;1624793000,1,312.57,6,312.57;1624916000,1,332.08,5,332.08;1625055872,1,353.19,8,353.19;1625192288,1,12.85,10,12.85;1625416854,1,43.93,7,43.93;1625611188,1,70.48,11,70.48;1625717999,1,85.23,2,85.23;1625879796,1,108.03,0,108.03;1626088441,1,138.49,3,138.49;1626092947,1,139.17,4,139.17;1626183160,3,139.82,4,139.82;1626787310,1,249.8,12,249.8;1627058055,1,295.42,9,295.42;1627151078,1,310.81,6,310.81;1627271757,1,330.25,5,330.25;1627418836,1,352.93,8,352.93;1627554419,1,12.85,10,12.85;1627781658,1,44.64,7,44.64;1627826849,2,129.54,0,129.54;1627959127,1,68.91,11,68.91;1628430607,1,136.24,0,136.24;1628487915,1,144.94,2,144.94;1628566929,1,157.11,4,157.11;1628676926,1,174.36,3,174.36;1629129863,1,247.59,12,247.59;1629343661,2,162.8,4,162.8;1629417555,1,294.82,9,294.82;1629503728,1,308.83,6,308.83;1629616710,1,326.93,5,326.93;1629780597,1,352.35,8,352.35;1629914372,1,12.24,10,12.24;1630144290,1,44.76,7,44.76;1630300411,1,66.16,11,66.16;1630975905,1,164.64,0,164.64;1631042611,1,175.36,4,175.36;1631149243,1,192.75,2,192.75;1631249270,1,209.24,3,209.24;1631464503,1,244.74,12,244.74;1631770780,1,294.41,9,294.41;1631852032,1,307.35,6,307.35;1631956459,1,323.77,5,323.77;1632137960,1,351.62,8,351.62;1632269780,1,11.17,10,11.17;1632502566,1,44.29,7,44.29;1632641551,1,63.42,11,63.42;1633518322,1,193.41,0,193.41;1633521828,1,194.0,4,194.0;1633556391,1,199.82,2,199.82;1633665658,0,195.1,4,195.1;1633796291,2,196.59,0,196.59;1633806663,3,242.54,12,242.54;1633808084,1,242.54,12,242.54;1633808198,1,242.56,3,242.56;1633819708,2,196.27,4,196.27;1634122397,1,294.33,9,294.33;1634201651,1,306.89,6,306.89;1634300947,1,322.34,5,322.34;1634489989,1,350.93,8,350.93;1634619782,1,9.96,10,9.96;1634855259,1,43.36,7,43.36;1634989671,1,61.9,11,61.9;1635967613,1,206.65,2,206.65;1636005323,1,213.13,4,213.13;1636060475,1,222.67,0,222.67;1636169859,1,241.73,12,241.73;1636348711,1,272.61,3,272.61;1636480280,1,294.6,9,294.6;1636548988,2,217.38,4,217.38;1636560868,1,307.66,6,307.66;1636660334,1,323.33,5,323.33;1636839954,1,350.49,8,350.49;1636966909,1,8.96,10,8.96;1637203449,1,42.25,7,42.25;1637344743,1,61.7,11,61.7;1637694190,0,241.7,12,241.7;1637861107,2,241.7,12,241.7;1638160763,2,247.17,0,247.17;1638492318,1,232.78,4,232.78;1638543473,1,241.74,12,241.74;1638603780,1,252.37,0,252.37;1638621780,1,255.54,2,255.54;1638840072,1,293.62,3,293.62;1638849332,1,295.2,9,295.2;1638934963,1,309.56,6,309.56;1639039972,1,326.58,5,326.58;1639194604,1,350.43,8,350.43;1639240140,3,295.32,9,295.32;1639317336,1,8.46,10,8.46;1639551048,1,41.31,7,41.31;1639599133,4,241.7,12,241.7' var H02_str1 = '1624084961,1,192.63,10,12.63;1624269748,1,223.41,7,43.41;1624428394,1,250.7,11,70.7;1624459818,1,256.15,2,76.15;1624491556,3,116.12,9,296.12;1624559980,1,273.46,0,93.46;1624711758,1,299.21,3,119.21;1624775366,1,309.7,4,129.7;1625144894,4,132.35,6,312.35;1625611188,1,70.48,12,250.48;1625625347,3,132.02,6,312.02;1625933404,1,115.73,9,295.73;1626042733,1,131.71,6,311.71;1626174010,1,151.36,5,331.36;1626315402,1,173.1,8,353.1;1626441141,1,192.93,10,12.93;1626561980,0,115.56,9,295.56;1626634786,1,224.37,7,44.37;1626787310,1,249.8,11,69.8;1626957891,3,150.61,5,330.61;1627026799,1,290.19,2,110.19;1627094213,1,301.44,0,121.44;1627244082,2,115.37,9,295.37;1627254817,1,327.56,4,147.56;1627304641,1,335.42,3,155.42;1627573817,4,149.88,5,329.88;1627854601,2,130.21,6,310.21;1627884862,0,130.18,6,310.18;1627959127,1,68.91,12,248.91;1628287893,1,115.09,9,295.09;1628387387,1,129.75,6,309.75;1628511753,1,148.59,5,328.59;1628554776,3,172.68,8,352.68;1628644782,2,148.39,5,328.39;1628666133,1,172.66,8,352.66;1628791331,1,192.6,10,12.6;1628990298,1,224.78,7,44.78;1629129863,1,247.59,11,67.59;1629419310,0,147.23,5,327.23;1629633717,1,329.62,0,149.62;1629736960,1,345.69,4,165.69;1629770559,1,350.83,2,170.83;1629854018,2,172.33,8,352.33;1629907007,1,11.16,3,191.16;1629984257,3,192.21,10,12.21;1630300411,1,66.16,12,246.16;1630604570,4,172.1,8,352.1;1630647445,1,114.57,9,294.57;1630738475,1,127.95,6,307.95;1630851696,1,145.12,5,325.12;1631021653,1,171.97,8,351.97;1631075409,2,191.75,10,11.75;1631142960,1,191.72,10,11.72;1631342194,1,224.59,7,44.59;1631464503,1,244.74,11,64.74;1631611254,0,171.79,8,351.79;1632182081,1,358.23,0,178.23;1632222147,1,4.18,4,184.18;1632362681,1,24.59,2,204.59;1632390058,3,224.32,7,44.32;1632514533,1,45.95,3,225.95;1632641551,1,63.42,12,243.42;1633010064,1,114.32,9,294.32;1633093180,4,190.75,10,10.75;1633097397,1,126.95,6,306.95;1633202917,1,142.73,5,322.73;1633276241,0,190.65,10,10.65;1633384056,1,171.23,8,351.23;1633501126,1,190.53,10,10.53;1633697989,1,223.86,7,43.86;1633806663,3,242.54,11,62.54;1633808084,1,242.54,11,62.54;1634621140,1,10.16,2,190.16;1634711291,1,23.1,4,203.1;1634741800,1,27.43,0,207.43;1634989671,1,61.9,12,241.9;1635111724,1,78.56,3,258.56;1635372457,1,114.42,9,294.42;1635462176,1,127.15,6,307.15;1635567820,1,142.57,5,322.57;1635750283,1,170.65,8,350.65;1635865252,1,189.38,10,9.38;1636061154,1,222.79,7,42.79;1636070262,0,222.78,7,42.78;1636169859,1,241.73,11,61.73;1636818998,2,222.43,7,42.43;1637169785,4,222.26,7,42.26;1637205603,1,42.55,4,222.55;1637264853,1,50.73,2,230.73;1637312246,1,57.24,0,237.24;1637344743,1,61.7,12,241.7;1637664532,1,105.44,3,285.44;1637694190,0,241.7,11,61.7;1637732760,1,114.88,9,294.88;1637830294,1,128.55,6,308.55;1637861107,2,241.7,11,61.7;1637943816,1,144.83,5,324.83;1638114597,1,170.4,8,350.4;1638230092,1,188.61,10,8.61;1638428476,1,221.72,7,41.72;1638543473,1,241.74,11,61.74;1639599133,4,241.7,11,61.7' var H03_str1 = '1620322354,12,251.0,10,11.0;1624086909,1,192.95,6,312.95;1624108948,1,196.54,2,76.54;1624186306,1,209.34,0,89.34;1624203318,1,212.18,5,332.18;1624283836,3,113.19,8,353.19;1624327005,1,233.2,8,353.2;1624330849,1,233.86,3,113.86;1624407395,1,247.06,4,127.06;1624440021,1,252.72,10,12.72;1624443076,0,92.17,5,332.17;1624619033,1,283.58,7,43.58;1624780648,1,310.56,11,70.56;1624820851,1,317.06,2,77.06;1624885463,4,130.49,12,250.49;1624953211,1,337.8,0,97.8;1625138534,1,5.2,3,125.2;1625174859,1,10.38,12,250.38;1625191081,1,12.68,4,132.68;1625215293,4,132.85,10,12.85;1625504218,1,55.85,9,295.85;1625514373,3,130.46,12,250.46;1625622425,1,72.02,6,312.02;1625688541,3,132.9,10,12.9;1625764145,1,91.66,5,331.66;1625915431,1,113.14,8,353.14;1626032297,1,130.17,12,250.17;1626050947,1,132.92,10,12.92;1626119110,2,91.41,5,331.41;1626258298,1,164.25,7,44.25;1626331574,1,175.62,9,295.62;1626338934,0,113.1,8,353.1;1626421360,1,189.78,11,69.78;1626431579,1,191.41,6,311.41;1626553382,1,211.02,5,331.02;1626613980,1,220.94,2,100.94;1626687197,1,233.05,8,353.05;1626712214,1,237.22,0,117.22;1626805818,1,252.92,10,12.92;1626876345,1,264.82,4,144.82;1626906330,1,269.89,3,149.89;1626992719,1,284.47,7,44.47;1627143216,1,309.52,11,69.52;1627144499,2,112.98,8,352.98;1627472501,1,0.92,2,120.92;1627507137,1,6.0,0,126.0;1627527508,1,8.97,12,248.97;1627680349,1,30.65,4,150.65;1627760454,1,41.73,3,161.73;1627767433,0,128.88,12,248.88;1627799724,2,128.89,12,248.89;1627858848,1,55.2,9,295.2;1627962069,2,132.78,10,12.78;1627967945,1,70.11,6,310.11;1627973609,3,164.68,7,44.68;1628105861,1,89.17,5,329.17;1628116878,0,132.76,10,12.76;1628271787,1,112.75,8,352.75;1628378964,1,128.5,12,248.5;1628407050,1,132.69,10,12.69;1628615928,1,164.76,7,44.76;1628680896,1,174.99,9,294.99;1628721934,3,174.98,9,294.98;1628761030,1,187.74,11,67.74;1628771545,1,189.43,6,309.43;1628887119,1,208.03,5,328.03;1629037992,1,232.56,8,352.56;1629159718,1,252.49,10,12.49;1629237067,1,265.2,0,145.2;1629344219,1,282.81,4,162.81;1629344265,1,282.81,2,162.81;1629356327,1,284.79,7,44.79;1629446759,2,164.79,7,44.79;1629482474,1,305.39,3,185.39;1629494277,1,307.3,11,67.3;1629605754,3,187.07,11,67.07;1629614257,4,164.79,7,44.79;1629722892,3,188.66,6,308.66;1629875002,1,6.47,12,246.47;1629987793,2,174.7,9,294.7;1630070361,1,34.49,0,154.49;1630174451,1,48.92,4,168.92;1630216203,1,54.65,9,294.65;1630249111,1,59.15,2,179.15;1630315552,1,68.23,6,308.23;1630384203,1,77.62,3,197.62;1630442902,1,85.7,5,325.7;1630630312,1,112.1,8,352.1;1630675108,2,185.95,11,65.95;1630724490,1,125.87,12,245.87;1630764830,1,131.89,10,11.89;1630805427,2,187.91,6,307.91;1630930777,4,174.53,9,294.53;1630933507,3,205.01,5,325.01;1630976064,1,164.66,7,44.66;1630978137,0,164.66,7,44.66;1631037366,1,174.51,9,294.51;1631102149,1,185.04,11,65.04;1631118532,1,187.72,6,307.72;1631221380,1,204.63,5,324.63;1631386222,1,231.86,8,351.86;1631506060,1,251.55,10,11.55;1631709039,1,284.51,7,44.51;1631765203,1,293.52,0,173.52;1631812733,1,301.11,4,181.11;1631834691,1,304.6,11,64.6;1631843559,0,174.41,9,294.41;1631943365,1,321.72,2,201.72;1632061536,1,340.01,3,220.01;1632178362,2,203.54,5,323.54;1632186233,4,183.91,11,63.91;1632219848,1,3.84,12,243.84;1632575356,1,54.34,9,294.34;1632606601,4,187.07,6,307.07;1632639821,0,183.42,11,63.42;1632641708,1,63.44,0,183.44;1632668190,1,67.05,6,307.05;1632671928,1,67.56,4,187.56;1632785074,1,83.01,5,323.01;1632802697,1,85.42,2,205.42;1632932026,3,231.37,8,351.37;1632953961,0,186.98,6,306.98;1632989186,1,111.35,8,351.35;1632995039,1,112.18,3,232.18;1633072879,1,123.37,12,243.37;1633123038,1,130.73,10,10.73;1633305894,2,202.67,5,322.67;1633339132,1,164.0,7,44.0;1633402986,1,174.31,9,294.31;1633454782,1,182.83,11,62.83;1633479335,1,186.9,6,306.9;1633572483,1,202.54,5,322.54;1633740762,1,231.13,8,351.13;1633854424,1,250.35,10,10.35;1634056416,1,283.71,7,43.71;1634174322,1,302.58,11,62.58;1634231320,1,311.54,2,191.54;1634284650,1,319.83,4,199.83;1634298371,0,202.34,5,322.34;1634301157,1,322.37,0,202.37;1634410143,3,250.07,10,10.07;1634566482,1,2.2,12,242.2;1634610988,4,202.33,5,322.33' var H03_str2 = '1634639986,1,12.88,3,252.88;1634934916,1,54.38,9,294.38;1635027098,1,67.02,6,307.02;1635070613,1,72.96,2,192.96;1635139996,1,82.41,5,322.41;1635171058,1,86.65,4,206.65;1635216866,1,92.91,0,212.91;1635346054,1,110.73,8,350.73;1635426178,1,122.01,12,242.01;1635478897,1,129.55,10,9.55;1635577492,1,144.01,3,264.01;1635701575,1,162.96,7,42.96;1635740290,2,202.65,5,322.65;1635774159,1,174.48,9,294.48;1635819633,1,181.86,11,61.86;1635852687,1,187.3,6,307.3;1635944863,1,202.77,5,322.77;1636105993,1,230.59,8,350.59;1636212975,1,249.24,10,9.24;1636408057,1,282.62,7,42.62;1636524427,1,301.79,11,61.79;1636734209,0,230.5,8,350.5;1636763287,1,339.06,4,219.06;1636780959,1,341.72,2,221.72;1636849114,1,351.84,0,231.84;1636916975,1,1.76,12,241.76;1637195936,1,41.21,3,281.21;1637249856,2,230.45,8,350.45;1637294240,1,54.77,9,294.77;1637302072,3,282.2,7,42.2;1637392338,1,68.21,6,308.21;1637509916,1,84.26,5,324.26;1637670252,1,106.23,4,226.23;1637700614,1,110.42,8,350.42;1637769708,1,120.03,2,240.03;1637781677,1,121.7,12,241.7;1637789648,1,122.82,0,242.82;1637831392,1,128.7,10,8.7;1638058694,1,161.87,7,41.87;1638105273,1,168.97,3,288.97;1638144144,1,174.99,9,294.99;1638186868,1,181.71,11,61.71;1638195011,4,230.4,8,350.4;1638231823,1,188.89,6,308.89;1638240062,2,248.61,10,8.61;1638283073,0,248.6,10,8.6;1638332375,1,205.41,5,325.41;1638478667,1,230.4,8,350.4;1638582131,1,248.55,10,8.55;1638770157,1,281.58,7,41.58;1638887620,1,301.67,11,61.67;1639251591,1,358.89,4,238.89;1639270132,1,1.61,12,241.61;1639411397,1,21.86,0,261.86;1639477179,1,31.08,2,271.08' var H04_str1 = '1623708052,6,313.11,7,43.11;1624136840,1,201.13,3,111.13;1624167451,1,206.2,9,296.2;1624224564,1,215.76,4,125.76;1624266519,1,222.86,6,312.86;1624379140,1,242.18,5,332.18;1624500535,1,263.2,8,353.2;1624614183,1,282.75,10,12.75;1624799769,1,313.66,7,43.66;1624970511,1,340.44,11,70.44;1624970511,1,340.44,12,250.44;1625021975,1,348.17,2,78.17;1625173837,1,10.24,0,100.24;1625285682,1,25.91,9,295.91;1625362778,4,133.91,7,43.91;1625377469,1,38.55,3,128.55;1625403973,1,42.17,6,312.17;1625413142,0,102.88,10,12.88;1625419683,1,44.32,4,134.32;1625547782,1,61.8,5,331.8;1625557164,2,83.17,8,353.17;1625703125,1,83.16,8,353.16;1625772313,3,134.07,7,44.07;1625843914,1,102.91,10,12.91;1626059430,1,134.18,7,44.18;1626230138,1,159.92,11,69.92;1626230138,1,159.92,12,249.92;1626401352,1,186.6,2,96.6;1626516638,1,205.06,0,115.06;1626519805,1,205.57,9,295.57;1626615903,1,221.26,6,311.26;1626689730,1,233.47,4,143.47;1626706306,2,102.92,10,12.92;1626712027,1,237.19,3,147.19;1626733909,1,240.84,5,330.84;1626865710,1,263.03,8,353.03;1626983448,1,282.91,10,12.91;1627173752,1,314.51,7,44.51;1627329024,1,339.22,11,69.22;1627329024,1,339.22,12,249.22;1627558717,3,158.94,11,68.94;1627558717,3,158.94,12,248.94;1627641822,1,25.26,9,295.26;1627727041,1,37.13,2,127.13;1627737359,1,38.55,0,128.55;1627750053,1,40.3,6,310.3;1627890039,1,59.46,5,329.46;1627911024,1,62.33,4,152.33;1628004284,1,75.1,3,165.1;1628042219,2,134.69,7,44.69;1628060084,1,82.8,8,352.8;1628202100,1,102.74,10,12.74;1628294237,0,134.72,7,44.72;1628420658,1,134.74,7,44.74;1628573149,1,158.08,11,68.08;1628573149,1,158.08,12,248.08;1628672348,4,157.88,11,67.88;1628672348,4,157.88,12,247.88;1628868025,1,204.95,9,294.95;1628956436,1,219.27,6,309.27;1629040775,1,233.02,0,143.02;1629069791,1,237.76,5,327.76;1629081920,2,157.59,11,67.59;1629081920,2,157.59,12,247.59;1629136603,1,248.7,2,158.7;1629153080,1,251.4,4,161.4;1629220717,1,262.51,8,352.51;1629282447,1,272.66,3,182.66;1629341961,1,282.44,10,12.44;1629540688,1,314.79,7,44.79;1629680100,1,336.89,11,66.89;1629680100,1,336.89,12,246.89;1630000919,1,24.69,9,294.69;1630098257,1,38.38,6,308.38;1630220166,0,156.16,11,66.16;1630220166,0,156.16,12,246.16;1630226169,1,56.02,5,326.02;1630307592,1,67.14,0,157.14;1630406143,1,80.63,4,170.63;1630417250,1,82.16,8,352.16;1630496788,1,93.18,2,183.18;1630559462,1,101.98,10,11.98;1630621449,1,110.82,3,200.82;1630783402,1,134.69,7,44.69;1630897610,3,204.53,9,294.53;1630917937,1,155.45,11,65.45;1630917937,1,155.45,12,245.45;1631220470,1,204.48,9,294.48;1631299979,1,217.62,6,307.62;1631401686,1,234.41,5,324.41;1631565560,1,261.27,0,171.27;1631568804,1,261.8,8,351.8;1631617043,1,269.64,4,179.64;1631690123,1,281.46,10,11.46;1631742050,1,289.81,2,199.81;1631851351,1,307.24,3,217.24;1631859273,3,217.34,6,307.34;1631897092,1,314.46,7,44.46;1632024122,1,334.26,11,64.26;1632024122,1,334.26,12,244.26;1632316305,2,204.36,9,294.36;1632361041,1,24.36,9,294.36;1632451186,1,37.12,6,307.12;1632566913,1,53.18,5,323.18;1632773454,1,81.42,8,351.42;1632880627,1,96.15,0,186.15;1632903418,1,99.31,4,189.31;1632914405,1,100.84,10,10.84;1633013318,1,114.79,2,204.79;1633044677,3,232.82,5,322.82;1633098381,2,204.32,9,294.32;1633145495,1,134.07,7,44.07;1633218165,1,145.05,3,235.05;1633270370,1,153.13,11,63.13;1633270370,1,153.13,12,243.13;1633582988,1,204.31,9,294.31;1633657031,1,216.89,6,306.89;1633748627,1,232.47,5,322.47;1633918615,1,261.08,8,351.08;1634035155,1,280.26,10,10.26;1634053832,1,283.29,2,193.29;1634084818,1,288.3,4,198.3;1634095507,1,290.02,0,200.02;1634244717,1,313.63,7,43.63;1634366971,1,332.45,11,62.45;1634366971,1,332.45,12,242.45;1634417961,1,340.16,3,250.16;1634472744,0,204.34,9,294.34;1634720134,1,24.36,9,294.36;1634809487,1,36.97,6,306.97;1634876369,4,204.37,9,294.37;1634920290,1,52.36,5,322.36;1635128025,1,80.78,8,350.78;1635266002,1,99.65,10,9.65;1635296757,3,260.74,8,350.74;1635311392,1,105.92,2,195.92;1635400906,1,118.43,4,208.43;1635451509,1,125.62,0,215.62;1635503084,1,133.05,7,43.05;1635587599,0,217.19,6,307.19;1635630315,1,151.97,11,61.97;1635630315,1,151.97,12,241.97;1635786018,1,176.39,3,266.39' var H04_str2 = '1635845947,2,204.49,9,294.49;1635955038,1,204.51,9,294.51;1636029940,1,217.38,6,307.38;1636119167,1,232.89,5,322.89;1636278385,1,260.56,8,350.56;1636387485,1,279.17,10,9.17;1636559668,1,307.46,4,217.46;1636560487,1,307.59,2,217.59;1636563846,2,217.66,6,307.66;1636586033,4,217.67,6,307.67;1636591509,1,312.54,7,42.54;1636634761,1,319.34,0,229.34;1636715345,1,331.79,11,61.79;1636715345,1,331.79,12,241.79;1636963632,3,278.96,10,8.96;1636967160,1,8.99,3,278.99;1637006297,0,233.67,5,323.67;1637077850,1,24.72,9,294.72;1637173167,1,38.05,6,308.05;1637288551,1,53.99,5,323.99;1637451779,2,234.18,5,324.18;1637481900,1,80.43,8,350.43;1637615958,1,98.76,10,8.76;1637854322,1,131.96,7,41.96;1637896764,1,138.03,4,228.03;1637990615,1,151.7,11,61.7;1637990615,1,151.7,12,241.7;1638008850,1,154.4,2,244.4;1638016059,1,155.47,0,245.47;1638302159,1,200.38,3,290.38;1638330178,1,205.04,9,295.04;1638412982,1,219.06,6,309.06;1638508937,1,235.68,5,325.68;1638649332,1,260.41,8,350.41;1638752553,1,278.52,10,8.52;1638890158,2,260.41,8,350.41;1638944479,4,236.41,5,326.41;1638946835,1,311.52,7,41.52;1639043965,1,327.21,4,237.21;1639071850,1,331.61,12,241.61;1639071850,1,331.61,11,61.61;1639186532,1,349.22,0,259.22;1639236791,1,356.71,2,266.71;1639290061,0,260.44,8,350.44;1639436429,1,25.38,9,295.38;1639440141,1,25.9,3,295.9;1639542965,1,40.2,6,310.2;1640330220,6,311.09,7,41.09' var H06_str1 = '1620322354,11,71.0,10,11.0;1624344201,1,236.15,9,296.15;1624440323,1,252.77,6,312.77;1624508893,6,312.73,10,12.73;1624552407,1,272.16,5,332.16;1624675847,1,293.2,8,353.2;1624780648,1,310.56,12,250.56;1624794352,1,312.79,10,12.79;1624885463,4,130.49,11,70.49;1624992440,1,343.75,7,43.75;1625074770,1,355.97,9,295.97;1625174859,1,10.38,11,70.38;1625188535,1,12.32,6,312.32;1625242329,1,19.88,2,79.88;1625329143,1,31.91,5,331.91;1625408762,1,42.83,0,102.83;1625484584,1,53.17,8,353.17;1625512457,0,103.97,7,43.97;1625514373,3,130.46,11,70.46;1625622077,1,71.97,3,131.97;1625628809,1,72.9,10,12.9;1625651234,1,75.98,4,135.98;1625852293,1,104.1,7,44.1;1626032297,1,130.17,11,70.17;1626181492,1,152.5,2,92.5;1626313588,1,172.82,0,112.82;1626421360,1,189.78,12,249.78;1626498249,1,202.09,4,142.09;1626512628,1,204.41,3,144.41;1626702031,1,235.52,9,295.52;1626773855,2,104.41,7,44.41;1626795073,1,251.11,6,311.11;1626910872,1,270.66,5,330.66;1627043540,1,293.0,8,353.0;1627143216,1,309.52,12,249.52;1627163808,1,312.89,10,12.89;1627363668,1,344.56,7,44.56;1627434765,1,355.32,9,295.32;1627527508,1,8.97,11,68.97;1627537996,1,10.48,6,310.48;1627673876,1,29.75,5,329.75;1627767433,0,128.88,11,68.88;1627799724,2,128.89,11,68.89;1627841595,1,52.85,8,352.85;1627975819,1,71.19,0,131.19;1627987396,1,72.78,10,12.78;1627992747,1,73.52,2,133.52;1628140344,1,94.0,4,154.0;1628215930,1,104.71,7,44.71;1628241446,1,108.37,3,168.37;1628378964,1,128.5,11,68.5;1628761030,1,187.74,12,247.74;1628842392,1,200.81,0,140.81;1628926381,1,214.39,2,154.39;1628960871,1,219.99,4,159.99;1629052322,1,234.9,9,294.9;1629083088,1,239.93,3,179.93;1629139181,1,249.12,6,309.12;1629250963,1,267.48,5,327.48;1629403140,1,292.46,8,352.46;1629494277,1,307.3,12,247.3;1629525673,1,312.37,10,12.37;1629605754,3,187.07,12,247.07;1629731062,1,344.79,7,44.79;1629796343,1,354.74,9,294.74;1629875002,1,6.47,11,66.47;1629889066,1,8.54,6,308.54;1630012459,1,26.33,5,326.33;1630198534,1,52.23,8,352.23;1630343655,1,72.07,10,12.07;1630543938,1,99.79,0,159.79;1630578778,1,104.72,7,44.72;1630631766,1,112.31,4,172.31;1630675108,2,185.95,12,245.95;1630724490,1,125.87,11,65.87;1630730710,1,126.79,2,186.79;1630843106,1,143.8,3,203.8;1631102149,1,185.04,12,245.04;1631369257,1,229.06,0,169.06;1631402001,1,234.46,9,294.46;1631424762,1,238.21,4,178.21;1631481467,1,247.52,6,307.52;1631543439,1,257.66,2,197.66;1631583467,1,264.19,5,324.19;1631647235,1,274.54,3,214.54;1631754074,1,291.74,8,351.74;1631834691,1,304.6,12,244.6;1631877483,1,311.37,10,11.37;1632090356,1,344.41,7,44.41;1632156307,1,354.38,9,294.38;1632186233,4,183.91,12,243.91;1632219848,1,3.84,11,63.84;1632242588,1,7.19,6,307.19;1632354137,1,23.37,5,323.37;1632554597,1,51.49,8,351.49;1632639821,0,183.42,12,243.42;1632696783,1,70.95,10,10.95;1632938039,1,104.14,7,44.14;1633072879,1,123.37,11,63.37;1633109642,1,128.75,0,188.75;1633124760,1,130.99,4,190.99;1633160851,3,234.32,9,294.32;1633208221,1,143.53,2,203.53;1633423569,1,177.68,3,237.68;1633454782,1,182.83,12,242.83;1633759511,1,234.32,9,294.32;1633833788,1,246.88,6,306.88;1633884543,1,255.4,2,195.4;1633893113,1,256.83,4,196.83;1633898687,1,257.76,0,197.76;1633926618,1,262.41,5,322.41;1634101834,1,291.03,8,351.03;1634153187,3,246.88,6,306.88;1634174322,1,302.58,12,242.58;1634205796,1,307.54,3,247.54;1634222521,1,310.16,10,10.16;1634433809,3,250.36,2,190.36;1634440462,1,343.54,7,43.54;1634513040,1,354.35,9,294.35;1634566482,1,2.2,11,62.2;1634598894,1,6.93,6,306.93;1634705914,1,22.34,5,322.34;1634909181,1,50.83,8,350.83;1635047140,1,69.75,10,9.75;1635291424,1,103.15,7,43.15;1635426178,1,122.01,11,62.01;1635448527,3,262.52,5,322.52;1635546707,1,139.44,2,199.44;1635618105,1,150.11,4,210.11;1635670656,1,158.15,0,218.15;1635819633,1,181.86,12,241.86;1635978734,1,208.56,3,268.56;1636128602,1,234.53,9,294.53;1636202765,1,247.46,6,307.46;1636214313,2,211.15,3,271.15;1636292624,1,263.02,5,323.02;1636355565,1,273.77,2,213.77;1636368510,1,275.96,4,215.96;1636434371,1,287.01,0,227.01;1636455637,1,290.54,8,350.54;1636524427,1,301.79,12,241.79;1636569898,1,309.1,10,9.1;1636748265,1,336.8,3,276.8' var H06_str2 = '1636785810,1,342.44,7,42.44;1636868400,1,354.67,9,294.67;1636916975,1,1.76,11,61.76;1636959562,1,7.9,6,307.9;1637070907,1,23.74,5,323.74;1637096484,0,234.72,9,294.72;1637262827,1,50.45,8,350.45;1637396847,1,68.82,10,8.82;1637486034,2,234.82,9,294.82;1637639928,1,102.05,7,42.05;1637781677,1,121.7,11,61.7;1637910441,3,287.47,4,228.14;1637975089,6,308.67,10,8.67;1638110196,1,169.73,4,229.73;1638186868,1,181.71,12,241.71;1638225857,1,187.93,0,247.93;1638228809,1,188.41,2,248.41;1638256740,2,248.91,6,308.91;1638305173,3,290.4,8,350.4;1638314067,0,248.97,6,308.97;1638485504,1,231.59,3,291.59;1638505542,1,235.09,9,295.09;1638585930,1,249.22,6,309.22;1638680881,1,265.96,5,325.96;1638790878,4,235.18,9,295.18;1638821314,1,290.41,8,350.41;1638852122,1,295.67,4,235.67;1638887620,1,301.67,12,241.67;1638928553,1,308.5,10,8.5;1638978984,1,316.78,0,256.78;1639015598,1,322.69,2,262.69;1639135323,1,341.45,7,41.45;1639227112,1,355.27,3,295.27;1639227385,1,355.31,9,295.31;1639250654,2,266.96,5,326.96;1639270132,1,1.61,11,61.61;1639327786,1,9.96,6,309.96;1639450323,1,27.33,5,327.33;1639617645,1,50.46,8,350.46' var H08_str1 = '1618178952,11,71.75,9,296.75;1618178952,12,251.75,9,296.75;1624061527,0,87.96,6,312.96;1624094041,0,88.32,7,43.32;1624112851,1,197.18,5,332.18;1624164191,1,205.65,11,70.65;1624164191,1,205.65,12,250.65;1624198217,1,211.33,2,76.33;1624239004,1,218.19,8,353.19;1624281372,1,225.39,0,90.39;1624353162,1,237.7,10,12.7;1624425427,1,250.19,3,115.19;1624430880,1,251.13,9,296.13;1624461905,3,115.7,11,70.7;1624461905,3,115.7,12,250.7;1624497711,1,262.71,4,127.71;1624526681,1,267.72,6,312.72;1624531408,1,268.54,7,43.54;1624566087,4,128.2,8,353.2;1624639997,1,287.14,5,332.14;1624690255,1,295.62,11,70.62;1624690255,1,295.62,12,250.62;1624726680,1,301.69,2,76.69;1624766195,1,308.2,8,353.2;1624849622,1,321.66,0,96.66;1624888572,1,327.8,10,12.8;1624971368,3,122.85,2,77.85;1624974182,1,340.99,9,295.99;1625024865,1,348.6,3,123.6;1625081086,1,356.89,4,131.89;1625084492,1,357.39,6,312.39;1625094178,1,358.8,7,43.8;1625221495,1,16.96,5,331.96;1625281957,1,25.39,11,70.39;1625281957,1,25.39,12,250.39;1625351344,3,128.18,8,353.18;1625358743,1,35.98,2,80.98;1625374788,1,38.18,8,353.18;1625519142,1,57.89,10,12.89;1625528381,1,59.15,0,104.15;1625613699,1,70.82,9,295.82;1625730339,1,86.94,6,311.94;1625742655,1,88.66,3,133.66;1625745553,1,89.06,7,44.06;1625756746,0,106.67,5,331.67;1625765143,1,91.8,4,136.8;1625834405,2,86.87,6,311.87;1625869750,1,106.59,5,331.59;1625930361,1,115.29,11,70.29;1625930361,1,115.29,12,250.29;1625983587,2,89.15,7,44.15;1626018458,1,128.13,8,353.13;1626068645,1,135.55,2,90.55;1626151317,1,147.93,10,12.93;1626208839,1,156.66,0,111.66;1626234907,1,160.65,9,295.65;1626337049,1,176.48,6,311.48;1626354913,1,179.28,7,44.28;1626383931,2,96.26,4,141.26;1626399935,1,186.38,4,141.38;1626410038,1,187.98,3,142.98;1626461036,1,196.11,5,331.11;1626489934,0,114.76,11,69.76;1626489934,0,114.76,12,249.76;1626514808,1,204.76,11,69.76;1626514808,1,204.76,12,249.76;1626596471,1,218.06,8,353.06;1626597637,2,100.6,3,145.6;1626716430,1,237.92,10,12.92;1626717955,1,238.18,2,103.18;1626764698,3,147.92,10,12.92;1626791429,1,250.5,9,295.5;1626807940,1,253.28,0,118.28;1626833400,2,105.74,5,330.74;1626883528,1,266.04,6,311.04;1626903694,1,269.45,7,44.45;1626969121,1,280.49,4,145.49;1626999215,1,285.56,5,330.56;1627003232,1,286.24,3,151.24;1627053418,1,294.65,11,69.65;1627053418,1,294.65,12,249.65;1627133833,1,307.98,8,352.98;1627204784,2,114.42,11,69.42;1627204784,2,114.42,12,249.42;1627256841,1,327.88,10,12.88;1627298603,4,147.88,10,12.88;1627336303,1,340.35,9,295.35;1627353685,1,343.03,2,118.03;1627398056,1,349.8,0,124.8;1627436443,1,355.57,6,310.57;1627463425,1,359.58,7,44.58;1627568273,1,14.84,4,149.84;1627568601,1,14.88,5,329.88;1627632139,1,23.9,11,68.9;1627632139,1,23.9,12,248.9;1627640466,1,25.07,3,160.07;1627653991,3,160.26,9,295.26;1627676873,0,127.88,8,352.88;1627732425,1,37.87,8,352.87;1627757490,2,127.87,8,352.87;1627877858,1,57.8,10,12.8;1627968399,1,70.18,9,295.18;1628076082,1,85.02,6,310.02;1628093917,1,87.5,0,132.5;1628109659,1,89.7,7,44.7;1628123209,1,91.59,2,136.59;1628211082,1,104.02,5,329.02;1628251419,1,109.81,4,154.81;1628278170,1,113.68,12,248.68;1628278170,1,113.68,11,68.68;1628354971,1,124.94,3,169.94;1628373798,1,127.73,8,352.73;1628505777,1,147.67,10,12.67;1628585592,1,160.02,9,295.02;1628610535,2,147.65,10,12.65;1628677827,1,174.51,6,309.51;1628686757,3,174.5,6,309.5;1628710984,1,179.77,7,44.77;1628741927,1,184.69,0,139.69;1628794896,1,193.17,5,328.17;1628819666,1,197.15,2,152.15;1628853803,1,202.65,11,67.65;1628853803,1,202.65,12,247.65;1628863927,1,204.28,4,159.28;1628946048,1,217.59,8,352.59;1628951530,4,159.93,9,294.93;1628982785,1,223.56,3,178.56;1629068338,1,237.52,10,12.52;1629072378,3,179.79,7,44.79;1629143797,1,249.88,9,294.88;1629194856,2,159.87,9,294.87;1629230072,1,264.05,6,309.05;1629265005,1,269.79,7,44.79;1629266748,5,327.46,10,12.46;1629334976,1,281.29,0,146.29;1629341416,1,282.35,5,327.35;1629403052,1,292.45,11,67.45;1629403052,1,292.45,12,247.45;1629435224,0,147.41,10,12.41;1629440188,1,298.51,4,163.51;1629448227,1,299.82,2,164.82;1629495103,1,307.44,8,352.44;1629584291,1,321.78,3,186.78' var H08_str2 = '1629619328,1,327.34,10,12.34;1629698499,1,339.76,9,294.76;1629788905,1,353.61,6,308.61;1629829962,1,359.78,7,44.78;1629909229,1,11.49,5,326.49;1629920455,2,173.51,6,308.51;1629928750,3,191.46,5,326.46;1629955598,1,18.21,0,153.21;1629977207,1,21.31,11,66.31;1629977207,1,21.31,12,246.31;1630060287,1,33.08,4,168.08;1630090209,1,37.26,8,352.26;1630124729,1,42.06,2,177.06;1630234192,1,57.11,10,12.11;1630262454,1,60.98,3,195.98;1630285165,2,179.75,7,44.75;1630325810,1,69.63,9,294.63;1630424452,1,83.15,6,308.15;1630472020,1,89.73,7,44.73;1630526589,0,159.59,9,294.59;1630549320,1,100.55,5,325.55;1630622852,1,111.02,11,66.02;1630622852,1,111.02,12,246.02;1630635290,3,201.01,12,246.01;1630635290,3,201.01,11,66.01;1630657718,1,116.06,0,161.06;1630719896,4,172.96,6,307.96;1630732540,1,127.06,8,352.06;1630739532,1,128.11,4,173.11;1630840663,1,143.42,2,188.42;1630862849,1,146.85,10,11.85;1630943759,1,159.52,9,294.52;1630948077,1,160.21,3,205.21;1630949289,2,189.99,5,324.99;1631026605,1,172.77,6,307.77;1631069039,1,179.64,7,44.64;1631130937,1,189.75,5,324.75;1631192633,1,199.89,11,64.89;1631192633,1,199.89,12,244.89;1631271810,1,212.96,0,167.96;1631295554,1,216.89,8,351.89;1631329502,1,222.5,4,177.5;1631414975,1,236.6,10,11.6;1631444842,1,241.51,2,196.51;1631493206,1,249.45,9,294.45;1631546738,1,258.2,3,213.2;1631572962,1,262.48,6,307.48;1631602606,4,179.53,7,44.53;1631616358,1,269.53,7,44.53;1631668436,0,172.43,6,307.43;1631675347,1,279.08,5,324.08;1631730716,2,199.7,11,64.7;1631730716,2,199.7,12,244.7;1631741282,1,289.69,11,64.69;1631741282,1,289.69,12,244.69;1631812252,3,216.72,8,351.72;1631848015,1,306.71,8,351.71;1631866698,1,309.67,0,174.67;1631912291,1,316.85,4,181.85;1631972865,1,326.32,10,11.32;1632045628,1,337.57,2,202.57;1632057443,1,339.38,9,294.38;1632142006,1,352.23,6,307.23;1632170085,1,356.44,3,221.44;1632189811,1,359.38,7,44.38;1632251297,1,8.47,5,323.47;1632281520,0,179.36,7,44.36;1632321296,1,18.65,11,63.65;1632321296,1,18.65,12,243.65;1632446925,1,36.52,8,351.52;1632522752,1,47.09,0,182.09;1632556071,1,51.69,4,186.69;1632587488,1,56.01,10,11.01;1632684932,1,69.34,9,294.34;1632693220,1,70.47,2,205.47;1632735817,4,188.05,5,323.05;1632777884,1,82.02,6,307.02;1632830100,1,89.18,7,44.18;1632877088,1,95.66,3,230.66;1632893453,1,97.93,5,322.93;1632968534,1,108.43,11,63.43;1632968534,1,108.43,12,243.43;1633028784,0,187.83,5,322.83;1633093076,1,126.32,8,351.32;1633173792,3,234.49,0,189.49;1633217713,1,144.99,0,189.99;1633222248,1,145.68,10,10.68;1633229410,1,146.78,4,191.78;1633265228,3,235.66,10,10.66;1633299662,1,157.73,2,202.73;1633309715,1,159.32,9,294.32;1633388219,1,171.91,6,306.91;1633431355,1,178.96,7,43.96;1633483398,1,187.58,5,322.58;1633521392,1,193.93,3,238.93;1633535056,3,239.1,4,194.1;1633543828,1,197.7,11,62.7;1633543828,1,197.7,12,242.7;1633652742,1,216.16,8,351.16;1633725841,2,197.56,11,62.56;1633725841,2,197.56,12,242.56;1633765085,2,197.02,3,242.02;1633765882,1,235.4,10,10.4;1633799660,1,241.12,4,196.12;1633801992,1,241.51,2,196.51;1633802900,1,241.67,0,196.67;1633848274,1,249.32,9,294.32;1633880145,0,197.55,11,62.55;1633880145,0,197.55,12,242.55;1633923406,1,261.88,6,306.88;1633964895,1,268.75,7,43.75;1633990560,4,197.58,11,62.58;1633990560,4,197.58,12,242.58;1634017556,1,277.39,5,322.39;1634080430,1,287.59,11,62.59;1634080430,1,287.59,12,242.59;1634103270,1,291.26,3,246.26;1634196054,1,306.01,8,351.01;1634318965,1,325.11,10,10.11;1634323956,1,325.88,2,190.88;1634350893,3,249.34,9,294.34;1634387859,1,335.62,4,200.62;1634407555,1,338.59,0,203.59;1634412494,1,339.34,9,294.34;1634496629,1,351.92,6,306.92;1634541213,1,358.5,7,43.5;1634601644,1,7.33,5,322.33;1634669160,1,17.08,11,62.08;1634669160,1,17.08,12,242.08;1634754819,1,29.28,3,254.28;1634801545,1,35.85,8,350.85;1634938020,1,54.81,10,9.81;1634952727,1,56.83,2,191.83;1635044470,1,69.39,9,294.39;1635054420,1,70.75,4,205.75;1635096783,1,76.52,0,211.52;1635137310,1,82.05,6,307.05;1635182467,1,88.21,7,43.21;1635249957,1,97.44,5,322.44;1635319112,1,106.99,11,61.99;1635319112,1,106.99,12,241.99;1635387603,2,197.0,11,62.0;1635387603,2,197.0,12,242.0' var H08_str3 = '1635415316,3,262.13,6,307.13;1635452167,1,125.71,8,350.71;1635459521,0,215.71,8,350.71;1635466184,1,127.72,3,262.72;1635580826,1,144.51,10,9.51;1635658444,1,156.27,2,201.27;1635679134,1,159.46,9,294.46;1635720341,1,165.91,4,210.91;1635760329,1,172.26,6,307.26;1635773306,1,174.34,0,219.34;1635795435,1,177.92,7,42.92;1635855230,1,187.72,5,322.72;1635909605,1,196.8,11,61.8;1635909605,1,196.8,12,241.8;1635916191,3,267.86,7,42.86;1636019695,1,215.61,8,350.61;1636071500,1,224.59,3,269.59;1636127099,1,234.27,10,9.27;1636214767,1,249.55,9,294.55;1636257456,1,256.95,2,211.95;1636276533,1,260.25,4,215.25;1636289658,1,262.51,6,307.51;1636316607,4,215.56,8,350.56;1636319727,1,267.66,7,42.66;1636338687,1,270.9,0,225.9;1636381066,1,278.09,5,323.09;1636432926,1,286.77,11,61.77;1636432926,1,286.77,12,241.77;1636450461,2,215.54,8,350.54;1636547590,1,305.53,8,350.53;1636643558,1,320.72,3,275.72;1636665074,1,324.06,10,9.06;1636767213,1,339.65,9,294.65;1636855873,1,352.84,6,307.84;1636869948,1,354.9,4,219.9;1636887007,1,357.4,7,42.4;1636897251,1,358.89,2,223.89;1636926265,3,278.59,5,323.59;1636961267,1,8.15,0,233.15;1636964615,1,8.63,5,323.63;1637021354,1,16.73,11,61.73;1637021354,1,16.73,12,241.73;1637028993,0,233.94,10,8.94;1637154553,1,35.46,8,350.46;1637197523,5,323.88,10,8.88;1637287584,1,53.85,10,8.85;1637312689,1,57.3,3,282.3;1637335520,0,237.51,3,282.51;1637403973,1,69.8,9,294.8;1637431623,2,233.81,10,8.81;1637502832,1,83.29,6,308.29;1637530747,1,87.1,7,42.1;1637554207,1,90.31,4,225.31;1637620600,1,99.4,5,324.4;1637644929,1,102.74,2,237.74;1637671826,1,106.44,0,241.44;1637673722,1,106.7,11,61.7;1637673722,1,106.7,12,241.7;1637808093,1,125.41,8,350.41;1637815727,3,286.7,11,61.7;1637815727,3,286.7,12,241.7;1637897279,2,242.36,3,287.36;1637935874,1,143.68,10,8.68;1638000596,1,153.17,3,288.17;1638046037,1,159.96,9,294.96;1638136570,1,173.81,6,308.81;1638155922,1,176.83,7,41.83;1638210890,1,185.53,4,230.53;1638240335,1,190.27,5,325.27;1638279912,1,196.72,11,61.72;1638279912,1,196.72,12,241.72;1638318474,2,250.04,9,295.04;1638324474,1,204.09,0,249.09;1638331584,1,205.28,2,250.28;1638391594,1,215.4,8,350.4;1638407499,0,250.06,9,295.06;1638496794,1,233.56,10,8.56;1638574146,1,247.14,3,292.14;1638587860,4,233.55,10,8.55;1638591023,1,250.12,9,295.12;1638671425,1,264.3,6,309.3;1638684581,1,266.62,7,41.62;1638760667,1,279.93,4,234.93;1638767428,1,281.11,5,326.11;1638799723,1,286.7,11,61.7;1638799723,1,286.7,12,241.7;1638881449,1,300.63,0,255.63;1638909997,1,305.41,8,350.41;1638912415,1,305.82,2,260.82;1639020579,1,323.49,10,8.49;1639125221,1,339.9,3,294.9;1639127713,1,340.28,9,295.28;1639129471,2,264.76,6,309.76;1639221006,2,266.42,7,41.42;1639224288,1,354.86,6,309.86;1639234818,1,356.42,7,41.42;1639342865,1,12.13,5,327.13;1639361387,1,14.78,4,239.78;1639374423,1,16.63,11,61.63;1639374423,1,16.63,12,241.63;1639508674,1,35.45,8,350.45;1639528847,1,38.25,0,263.25;1639602268,1,48.36,2,273.36;1639639389,1,53.44,10,8.44;1639710106,0,265.38,6,310.38;1639783139,0,266.24,7,41.24' // @function get the start time for each harmonic signal // @param harmonic is an integer identifying the harmonic // @returns the starting timestamp of the harmonic data export import_start_time(int harmonic) => switch harmonic 1 => 1624428394 2 => 1624084961 3 => 1620322354 4 => 1623708052 6 => 1620322354 8 => 1618178952 => 9999999999 // @function access point for pre-processed data imported here by copy paste // @param index is the current data index, use 0 to initialize // @param harmonic is the data set to index, use 0 to initialize // @param get_length when true returns the length of the indicated harmonic array rather than the data // @returns the data from the indicated harmonic array starting at index, and the starting timestamp of that data export import_signal(int index, int harmonic, bool get_length=false) => var event_str = '' var H_array = array.new_string(0) // the arrays must be defined in the function as libraries cannot export global variables var H01_array = array.new_string(0) var H02_array = array.new_string(0) var H03_array = array.new_string(0) var H04_array = array.new_string(0) var H06_array = array.new_string(0) var H08_array = array.new_string(0) // initialize the data if the array is zero length. // This is call dependant which means it is also harmonic dependant if harmonic == 1 and array.size(H01_array) == 0 stringArrayAppend(H01_array, H01_str1, ';') if harmonic == 2 and array.size(H02_array) == 0 stringArrayAppend(H02_array, H02_str1, ';') if harmonic == 3 and array.size(H03_array) == 0 stringArrayAppend(H03_array, H03_str1, ';') stringArrayAppend(H03_array, H03_str2, ';') if harmonic == 4 and array.size(H04_array) == 0 stringArrayAppend(H04_array, H04_str1, ';') stringArrayAppend(H04_array, H04_str2, ';') if harmonic == 6 and array.size(H06_array) == 0 stringArrayAppend(H06_array, H06_str1, ';') stringArrayAppend(H06_array, H06_str2, ';') if harmonic == 8 and array.size(H08_array) == 0 stringArrayAppend(H08_array, H08_str1, ';') stringArrayAppend(H08_array, H08_str2, ';') stringArrayAppend(H08_array, H08_str3, ';') H_array := switch harmonic 1 => H01_array 2 => H02_array 3 => H03_array 4 => H04_array 6 => H06_array 8 => H08_array => array.new_string(0) // [_t, _c] = dbug.init(size=50, visible=true) // _msg = str.format('index {0} harmonic {1} flag {2} array length {3} {4}', index, harmonic, get_length, array.size(H_array), array.size(H04_str)) event_str := if get_length str.tostring(array.size(H_array)) // return the length of the array as a string else if index < array.size(H_array) array.get(H_array, index) else '' // _msg += str.format(' item length {0} array length {1}', str.length(event_str), array.size(H_array)) // dbug.queue(_c, 'inDB: ' + _msg) // dbug.update(_t, _c) // event_str // *** Library Purpose and How to Use *** // CAUTION: Every unique call of the import_signal function initializes the data into a new dataset in the local scope of the function. // That can consume time and memory to parse the strings and fill the arrays, so be sure to call the function as few times as possible. // Keep in mind that you can call the function as many times as required in a loop as it is the same call and initializes the data on the first iteration of the loop. // Calling the function in different places in your script is what counts as different calls. // The intention is to create a (very limited) way to import external data into pine script // As far as I can tell, putting the data into a library frees up resources in your main script so you can have more code! // It can also be thought of as using libraries as classes to encapsulate the data and even some of the functionality around that data. // This example is limited but you could build a sophisticated data handling system in a set of libraries. // You can organize the data in any way that suits your needs. // In this example the data starts with a timestamp and then follows with data related to that timestamp. // Sections use a semi-colon as a separator character and the data in each section uses a comma. // After importing the library into your main script: // import ubiquity/Signal_Data_2021_09_09__2021_11_18/7 as sdata // The data store must be initialized in your main script inside an if barstate.isfirst block: // if barstate.isfirst // // initialize the data // sdata.import_signal(0, 0) // The initialization runs the library function and ensures the barstate.isfirst code in that function // is executed so the imported data strings are parsed into the string arrays. // After that, whenever the function is called it accesses the data from the array. // Then the data can be used - This following example script is not part of this library. // It is an example of how to use the data in the main script. // get_signal(harmonic) => // // the index variable is the offset into the array and is maintained uniquely across function calls // var index = 0 // var in_session = false // var start_time = sdata.import_start_time(harmonic) // timestamp = start_time // fid = 0 // fwave = 0.0 // sid = 0 // swave = 0.0 // is_signal = false // var signal_str = '' // var signal = array.new_string(0) // // catch up to the start of the data // signal_str := sdata.import_signal(index, harmonic) // while not in_session and str.length(signal_str) > 0 and topen > timestamp // // split the data string // signal := str.split(signal_str, ',') // // convert the string to a number // timestamp := int(str.tonumber(array.get(signal, 0))) // if topen > timestamp // index += 1 // signal_str := sdata.import_signal(index, harmonic) // // if the first bar of the timeframe starts before the first signal, activate the session right away // if not in_session and not (topen < start_time) // in_session := true // if in_session and str.length(signal_str) > 0 // // split the data string // signal := str.split(signal_str, ',') // // convert the first string to a number // timestamp := int(str.tonumber(array.get(signal, 0))) // if tclose[2] < timestamp and timestamp <= tclose // // when the signal is triggered convert the remaining strings to numbers // fid := int(str.tonumber(array.get(signal, 1))) // fwave := str.tonumber(array.get(signal, 2)) // sid := int(str.tonumber(array.get(signal, 3))) // swave := str.tonumber(array.get(signal, 4)) // index += 1 // is_signal := true // [index, is_signal, fid, fwave, sid, swave] // // exposing the index to the global namespace allows it to be used in more function calls (not shown in this example) // [H01_index, is_H01_signal, H01_p1id, H01_p1wave, H01_p2id, H01_p2wave] = get_signal(1) // bgcolor(color=show_signal_bgcolor and is_H01_signal ? color.white : na, title='H01 Signal') // [H02_index, is_H02_signal, H02_p1id, H02_p1wave, H02_p2id, H02_p2wave] = get_signal(2) // bgcolor(color=show_signal_bgcolor and is_H02_signal ? color.orange : na, title='H02 Signal') // [H03_index, is_H03_signal, H03_p1id, H03_p1wave, H03_p2id, H03_p2wave] = get_signal(3) // bgcolor(color=show_signal_bgcolor and is_H03_signal ? color.navy : na, title='H03 Signal')
CreateAndShowZigzag
https://www.tradingview.com/script/s1kd2R7I-CreateAndShowZigzag/
LonesomeTheBlue
https://www.tradingview.com/u/LonesomeTheBlue/
191
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © LonesomeTheBlue //@version=5 // @description Functions in this library creates/updates zigzag array and shows the zigzag library("CreateAndShowZigzag") Trz(float [] zigzag, int mLoc)=> for x = array.size(zigzag) - 1 to array.size(zigzag) > 1 ? 0 : na by 2 if bar_index - array.get(zigzag, x) <= mLoc break array.pop(zigzag) array.pop(zigzag) addtozigzag(float [] zigzag, float value) => array.unshift(zigzag, bar_index) array.unshift(zigzag, value) updatezigzag(float [] zigzag, float value, int dir) => if array.size(zigzag) == 0 addtozigzag(zigzag, value) else if dir == 1 and value > array.get(zigzag, 0) or dir == -1 and value < array.get(zigzag, 0) array.set(zigzag, 0, value) array.set(zigzag, 1, bar_index) export getZigzag(float [] zigzag, int prd, int mLoc)=> Trz(zigzag, mLoc) float ph = ta.highestbars(high, prd) == 0 ? high : na float pl = ta.lowestbars(low, prd) == 0 ? low : na var int dir = 0 dir := ph and na(pl) ? 1 : pl and na(ph) ? -1 : dir bool bothexist = ph and pl bool dirchanged = dir != dir[1] if ph or pl if bothexist updatezigzag(zigzag, dir == 1 ? ph : pl, dir) dir := -dir addtozigzag(zigzag, dir == 1 ? ph : pl) else if dirchanged //and not nz(bothexist[1], false) addtozigzag(zigzag, dir == 1 ? ph : pl) else updatezigzag(zigzag, dir == 1 ? ph : pl, dir) [dir, bothexist] export showZigzag(float [] zigzag, float [] zigzagold, int dir, bool specialcase, color upcol, color dncol)=> var line zzline = na if specialcase line.set_xy1(zzline, math.round(array.get(zigzag, 3)), array.get(zigzag, 2)) if array.get(zigzag, 0) != array.get(zigzagold, 0) or array.get(zigzag, 1) != array.get(zigzagold, 1) if array.get(zigzag, 2) == array.get(zigzagold, 2) and array.get(zigzag, 3) == array.get(zigzagold, 3) line.delete(zzline) zzline := line.new(x1=math.round(array.get(zigzag, 1)), y1=array.get(zigzag, 0), x2=math.round(array.get(zigzag, 3)), y2=array.get(zigzag, 2), color=dir == 1 ? upcol : dncol) export getTN()=> int TN = 8 tick__ = syminfo.mintick while tick__ < 1 TN += 1 tick__ *= 10 tick__ := high while tick__ > 1 TN += 1 tick__ /= 10 TN
MathComplexTrignometry
https://www.tradingview.com/script/6GGcGa8y-MathComplexTrignometry/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
17
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods for complex number trignometry operations. library(title='MathComplexTrignometry') // reference: // https://github.com/mathnet/mathnet-numerics/blob/a50d68d52def605a53d129cc60ea3371a2e97548/src/Numerics/Trigonometry.cs // test values : https://www.mathsisfun.com/numbers/complex-number-calculator.html //#region -> Imports: import RicardoSantos/DebugConsole/11 as console logger = console.Console.new().init(30) import RicardoSantos/MathTrigonometry/1 as trig import RicardoSantos/MathConstants/1 as constants import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/MathComplexCore/3 as complex import RicardoSantos/MathComplexOperator/2 as complex_op import RicardoSantos/MathComplexExtension/2 as complex_ex //#endregion string strof_a = input.string('3.1416+1.618i', 'A:') TMath.complex input_a = complex.from(strof_a) // preview of functions parameters: bool show_1 = input.bool(title='Show Trig functions:', defval=true) bool show_2 = input.bool(title='Show hyper Trig functions:', defval=true) bool show_3 = input.bool(title='Show arc Trig functions:', defval=true) bool show_4 = input.bool(title='Show hyper arc Trig functions:', defval=true) //#region -> Methods: // sinh () { // @function Hyperbolic Sine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method sinh (TMath.complex this) => if complex.is_real(this) complex.new(trig.sinh(this.re), 0.0) else float _absre = math.abs(this.re) if _absre >= 22.0 float _h = math.exp(_absre) * 0.5 complex.new(math.sign(this.re) * _h * math.cos(this.im), _h * math.sin(this.im)) else complex.new(trig.sinh(this.re) * math.cos(this.im), trig.cosh(this.re) * math.sin(this.im)) // usage: if show_2 logger.queue_one(str.format('sinh({0}): {1}', strof_a, complex.to_string(sinh(input_a), '#.##'))) // } // cosh () { // @function Hyperbolic cosine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method cosh (TMath.complex this) => if complex.is_real(this) complex.new(trig.cosh(this.re), 0.0) else float _absre = math.abs(this.re) if _absre >= 22.0 float _h = math.exp(_absre) * 0.5 complex.new(_h * math.cos(this.im), math.sign(this.re) * _h * math.sin(this.im)) else complex.new(trig.cosh(this.re) * math.cos(this.im), trig.sinh(this.re) * math.sin(this.im)) // usage: if show_2 logger.queue_one(str.format('cosh({0}): {1}', strof_a, complex.to_string(cosh(input_a), '#.##'))) // } // tanh () { // @function Hyperbolic tangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method tanh (TMath.complex this) => if complex.is_real(this) complex.new(trig.tanh(this.re), 0.0) else if math.abs(this.re) >= 22.0 float _e = math.exp(-math.abs(this.re)) if _e == 0.0 complex.new(math.sign(this.re), 0.0) else complex.new(math.sign(this.re), 4.0 * math.cos(this.im) * math.sin(this.im) * math.pow(_e, 2.0)) else float POSINF = 1.7976931348623157e+308 // positive float infinity, credit to Xel_Arjona. float _tani = math.tan(this.im) float _sinhr = trig.sinh(this.re) float _coshr = trig.cosh(this.re) if math.abs(_tani) >= POSINF complex.new(_coshr / _sinhr, 0.0) else float _beta = 1.0 + math.pow(_tani, 2.0) float _denom = 1.0 + _beta * math.pow(_sinhr, 2.0) complex.new(_beta * _coshr * _sinhr / _denom, _tani / _denom) // usage: if show_2 logger.queue_one(str.format('tanh({0}): {1}', strof_a, complex.to_string(tanh(input_a), '#.##'))) // } // coth () { // @function Hyperbolic cotangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method coth (TMath.complex this) => if complex.is_real(this) complex.new(trig.coth(this.re), 0.0) else complex_op.divide(complex.one(), tanh(this)) // usage: if show_2 logger.queue_one(str.format('coth({0}): {1}', strof_a, complex.to_string(coth(input_a), '#.##'))) // } // sech () { // @function Hyperbolic Secant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method sech (TMath.complex this) => if complex.is_real(this) complex.new(trig.sech(this.re), 0.0) else float _absre = math.abs(this.re) float _tani = math.tan(this.im) float _cosi = math.cos(this.im) float _sinhr = trig.sinh(this.re) float _coshr = trig.cosh(this.re) if _absre >= 22.0 float _e = math.exp(-_absre) if _e == 0.0 complex.zero() else float _e2 = math.pow(_e, 2.0) complex.new(4.0 * _coshr * _cosi * _e2, -4.0 * _sinhr * _tani * _cosi * _e2) else float POSINF = 1.7976931348623157e+308 // positive float infinity, credit to Xel_Arjona. if math.abs(_tani) >= POSINF complex.new(0.0, -math.sign(_tani) / _sinhr) else float _beta = 1.0 + math.pow(_tani, 2.0) float _denom = 1.0 +_beta * math.pow(_sinhr, 2.0) complex.new(_coshr / _cosi / _denom, -_sinhr * _tani / _cosi / _denom) // usage: if show_2 logger.queue_one( str.format('sech({0}): {1}', strof_a, complex.to_string(sech(input_a), '#.##'))) // } // csch () { // @function Hyperbolic Cosecant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method csch (TMath.complex this) => if complex.is_real(this) complex.new(trig.csch(this.re), 0.0) else float _absre = math.abs(this.re) float _coti = trig.cot(this.im) float _sini = math.sin(this.im) float _sinhr = trig.sinh(this.re) float _coshr = trig.cosh(this.re) if _absre >= 22.0 float _e = math.exp(-_absre) if _e == 0.0 complex.zero() else float _e2 = math.pow(_e, 2.0) complex.new(4.0 * _sinhr * _coti * _sini * _e2, -4.0 * _coshr * _sini * _e2) else float POSINF = 1.7976931348623157e+308 // positive float infinity, credit to Xel_Arjona. if math.abs(_coti) >= POSINF complex.new(math.sign(_coti) / _sinhr, 0.0) else float _beta = 1.0 + math.pow(_coti, 2.0) float _denom = 1.0 +_beta * math.pow(_sinhr, 2.0) complex.new(_sinhr * _coti / _sini / _denom, -_coshr / _sini / _denom) // usage: if show_2 logger.queue_one(str.format('csch({0}): {1}', strof_a, complex.to_string(csch(input_a), '#.##'))) // } // sin () { // @function Trigonometric Sine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method sin (TMath.complex this) => if complex.is_real(this) complex.new(math.sin(this.re), 0.0) else complex.new(math.sin(this.re) * trig.cosh(this.im), math.cos(this.re) * trig.sinh(this.im)) // usage: if show_1 logger.queue_one(str.format('sin({0}): {1}', strof_a, complex.to_string(sin(input_a), '#.##'))) // } // cos () { // @function Trigonometric cosine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method cos (TMath.complex this) => if complex.is_real(this) complex.new(math.cos(this.re), 0.0) else complex.new(math.cos(this.re) * trig.cosh(this.im), -math.sin(this.re) * trig.sinh(this.im)) // usage: if show_1 logger.queue_one(str.format('cos({0}): {1}', strof_a, complex.to_string(cos(input_a), '#.##'))) // } // tan () { // @function Trigonometric tangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method tan (TMath.complex this) => if complex.is_real(this) complex.new(math.tan(this.re), 0.0) else TMath.complex _z = tanh(complex.new(-this.im, this.re)) complex.new(_z.im, -_z.re) // usage: if show_1 logger.queue_one(str.format('tan({0}): {1}', strof_a, complex.to_string(tan(input_a), '#.##'))) // } // cot () { // @function Trigonometric cotangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method cot (TMath.complex this) => if complex.is_real(this) complex.new(trig.cot(this.re), 0.0) else TMath.complex _z = coth(complex.new(this.im, -this.re)) complex.new(_z.im, -_z.re) // usage: if show_1 logger.queue_one(str.format('cot({0}): {1}', strof_a, complex.to_string(cot(input_a), '#.##'))) // } // sec () { // @function Trigonometric Secant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method sec (TMath.complex this) => if complex.is_real(this) complex.new(trig.sec(this.re), 0.0) else float _cosr = math.cos(this.re) float _sinhi = trig.sinh(this.im) float _denom = math.pow(_cosr, 2) + math.pow(_sinhi, 2) complex.new(_cosr * trig.cosh(this.im) / _denom, math.sin(this.re) * _sinhi / _denom) // usage: if show_1 logger.queue_one(str.format('sec({0}): {1}', strof_a, complex.to_string(sec(input_a), '#.##'))) // } // csc () { // @function Trigonometric Cosecant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method csc (TMath.complex this) => if complex.is_real(this) complex.new(trig.csc(this.re), 0.0) else float _sinr = math.sin(this.re) float _sinhi = trig.sinh(this.im) float _denom = math.pow(_sinr, 2) + math.pow(_sinhi, 2) complex.new(_sinr * trig.cosh(this.im) / _denom, -math.cos(this.re) * _sinhi / _denom) // usage: if show_1 logger.queue_one(str.format('csc({0}): {1}', strof_a, complex.to_string(csc(input_a), '#.##'))) // } // asin () { // @function Trigonometric Arc Sine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method asin (TMath.complex this) => TMath.complex _imo = complex.imaginary_one() TMath.complex _nimo = complex_op.negative(_imo) TMath.complex _one = complex.one() if this.im > 0.0 or (this.im == 0.0 and this.re < 0.0) TMath.complex _ncomplex = complex_op.negative(this) TMath.complex _sq = complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(_ncomplex))) TMath.complex _ln = complex_ex.natural_logarithm(complex_op.add(_sq, complex_op.multiply(_imo, _ncomplex))) complex_op.negative(complex_op.multiply(_nimo, _ln)) else TMath.complex _sq = complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(this))) TMath.complex _ln = complex_ex.natural_logarithm(complex_op.add(_sq, complex_op.multiply(_imo, this))) complex_op.multiply(_nimo, _ln) // usage: if show_3 logger.queue_one(str.format('asin({0}): {1}', strof_a, complex.to_string(asin(input_a), '#.##'))) // } // acos () { // @function Trigonometric Arc Cosine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acos (TMath.complex this) => TMath.complex _imo = complex.imaginary_one() TMath.complex _nimo = complex_op.negative(complex.imaginary_one()) TMath.complex _one = complex.one() if this.im < 0.0 or (this.im == 0.0 and this.re > 0.0) TMath.complex _ncomplex = complex_op.negative(this) TMath.complex _1_sqrt = complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(_ncomplex))) complex_op.subtract(complex.new(math.pi, 0.0), complex_op.multiply(_nimo, complex_ex.natural_logarithm(complex_op.add(_ncomplex, complex_op.multiply(_imo, _1_sqrt))))) else TMath.complex _1_sqrt = complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(this))) complex_op.multiply(_nimo, complex_ex.natural_logarithm(complex_op.add(this, complex_op.multiply(_imo, _1_sqrt)))) // usage: if show_3 logger.queue_one(str.format('acos({0}): {1}', strof_a, complex.to_string(acos(input_a), '#.##'))) // } // atan () { // @function Trigonometric Arc Tangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method atan (TMath.complex this) => TMath.complex _iz = complex.new(-this.im, this.re) TMath.complex _one = complex.one() complex_op.multiply(complex.new(0.0, 0.5), complex_op.subtract(complex_ex.natural_logarithm(complex_op.subtract(_one, _iz)), complex_ex.natural_logarithm(complex_op.add(_one, _iz)))) // usage: if show_3 logger.queue_one(str.format('atan({0}): {1}', strof_a, complex.to_string(atan(input_a), '#.##'))) // } // acot () { // @function Trigonometric Arc Cotangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acot (TMath.complex this) => if complex.is_zero(this) complex.new(constants.PiOver2(), 0.0) else TMath.complex _one = complex.one() TMath.complex _half = complex.new(0.5, 0.0) TMath.complex _imo = complex.imaginary_one() TMath.complex _inv = complex_op.divide(_imo, this) complex_op.multiply(complex_op.multiply(_imo, _half), complex_op.subtract(complex_ex.natural_logarithm(complex_op.subtract(_one, _inv)), complex_ex.natural_logarithm(complex_op.add(_one, _inv)))) // usage: if show_3 logger.queue_one(str.format('acot({0}): {1}', strof_a, complex.to_string(acot(input_a), '#.##'))) // } // asec () { // @function Trigonometric Arc Secant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method asec (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _imo = complex.imaginary_one() TMath.complex _inv = complex_op.divide(_one, this) TMath.complex _nimo = complex_op.negative(_imo) TMath.complex _imosqrt = complex_op.multiply(_imo, complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(_inv)))) complex_op.multiply(_nimo, complex_ex.natural_logarithm(complex_op.add(_inv, _imosqrt))) // usage: if show_3 logger.queue_one(str.format('asec({0}): {1}', strof_a, complex.to_string(asec(input_a), '#.##'))) // } // acsc () { // @function Trigonometric Arc Cosecant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acsc (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _imo = complex.imaginary_one() TMath.complex _inv = complex_op.divide(_one, this) TMath.complex _nimo = complex_op.negative(_imo) TMath.complex _sqrt = complex_ex.square_root(complex_op.subtract(_one, complex_ex.square(_inv))) complex_op.multiply(_nimo, complex_ex.natural_logarithm(complex_op.add(complex_op.multiply(_imo, _inv), _sqrt))) // usage: if show_3 logger.queue_one(str.format('acsc({0}): {1}', strof_a, complex.to_string(acsc(input_a), '#.##'))) // } // asinh () { // @function Hyperbolic Arc Sine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method asinh (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _sq = complex_ex.square_root(complex_op.add(complex_ex.square(this), _one)) complex_ex.natural_logarithm(complex_op.add(this, _sq)) // usage: if show_4 logger.queue_one(str.format('asinh({0}): {1}', strof_a, complex.to_string(asinh(input_a), '#.##'))) // } // acosh () { // @function Hyperbolic Arc Cosine of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acosh (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _sqn = complex_ex.square_root(complex_op.subtract(this, _one)) TMath.complex _sqp = complex_ex.square_root(complex_op.add(this, _one)) TMath.complex _sq = complex_op.multiply(_sqn, _sqp) complex_ex.natural_logarithm(complex_op.add(this, _sq)) // usage: if show_4 logger.queue_one(str.format('acosh({0}): {1}', strof_a, complex.to_string(acosh(input_a), '#.##'))) // } // atanh () { // @function Hyperbolic Arc Tangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method atanh (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _half = complex.new(0.5, 0.0) TMath.complex _lnn = complex_ex.natural_logarithm(complex_op.subtract(_one, this)) TMath.complex _lnp = complex_ex.natural_logarithm(complex_op.add(_one, this)) TMath.complex _ln = complex_op.subtract(_lnp, _lnn) complex_op.multiply(_half, _ln) // usage: if show_4 logger.queue_one(str.format('atanh({0}): {1}', strof_a, complex.to_string(atanh(input_a), '#.##'))) // } // acoth () { // @function Hyperbolic Arc Cotangent of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acoth (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _half = complex.new(0.5, 0.0) TMath.complex _inv = complex_op.divide(_one, this) TMath.complex _lnn = complex_ex.natural_logarithm(complex_op.subtract(_one, _inv)) TMath.complex _lnp = complex_ex.natural_logarithm(complex_op.add(_one, _inv)) TMath.complex _ln = complex_op.subtract(_lnp, _lnn) complex_op.multiply(_half, _ln) // usage: if show_4 logger.queue_one(str.format('acoth({0}): {1}', strof_a, complex.to_string(acoth(input_a), '#.##'))) // } // asech () { // @function Hyperbolic Arc Secant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method asech (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _inv = complex_op.divide(_one, this) TMath.complex _sqn = complex_ex.square_root(complex_op.subtract(_inv, _one)) TMath.complex _sqp = complex_ex.square_root(complex_op.add(_inv, _one)) TMath.complex _sq = complex_op.multiply(_sqn, _sqp) complex_ex.natural_logarithm(complex_op.add(_inv, _sq)) // usage: if show_4 logger.queue_one(str.format('asech({0}): {1}', strof_a, complex.to_string(asech(input_a), '#.##'))) // } // acsch () { // @function Hyperbolic Arc Cosecant of complex number. // @param this complex . Complex number in the form `(real, imaginary)`. // @returns complex. Complex number. export method acsch (TMath.complex this) => TMath.complex _one = complex.one() TMath.complex _inv = complex_op.divide(_one, this) TMath.complex _sq = complex_ex.square_root(complex_op.add(complex_ex.square(_inv), _one)) complex_ex.natural_logarithm(complex_op.add(_inv, _sq)) // usage: if show_4 logger.queue_one(str.format('acsch({0}): {1}', strof_a, complex.to_string(acsch(input_a), '#.##'))) // remarks: // } //#endregion logger.update()
zigzag
https://www.tradingview.com/script/DnjLJ7fc-zigzag/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
170
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Library dedicated to zigzags and related indicators library("zigzag", overlay=true) add_to_array(arr, val, maxItems) => array.insert(arr, 0, val) if array.size(arr) > maxItems array.pop(arr) pivots(length, highSource=high, lowSource = low) => float phigh = ta.highestbars(highSource, length) == 0 ? highSource : na float plow = ta.lowestbars(lowSource, length) == 0 ? lowSource : na [phigh, plow, bar_index, bar_index] getSentiment(pDir, oDir, sDir) => sentiment = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3) sentiment getSentimentDetails(sentiment) => sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣' sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I' [sentimentSymbol, sentimentLabel, sentimentColor] getDoubleDivergenceDetails(doubleDivergence)=> doubleDivergence >0? '⬆' : doubleDivergence<0? '⬇' : '▣' addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, value, bar, dir, numberOfPivots, oscHigh, oscLow, directionBias, divergenceOption) => newDir = dir oscDir = dir lPDir = 0 lODir = 0 ratio = 1.0 oscillatorSource = dir > 0? oscHigh[bar_index - bar] : oscLow[bar_index - bar] if array.size(zigzagpivots) >= 2 lastPoint = array.get(zigzagpivots, 0) llastPoint = array.get(zigzagpivots, 1) newDir := dir * value > dir * llastPoint ? dir * 2 : dir ratio := math.round(math.abs(value-lastPoint)/math.abs(llastPoint-lastPoint), 2) llastOsc = array.get(zigzagoscillators, 1) oscDir := dir * oscillatorSource > dir * llastOsc ? dir * 2 : dir if array.size(zigzagpivots) >=4 lllastPoint = array.get(zigzagpivots, 3) lllastOsc = array.get(zigzagoscillators, 3) lODir := dir * llastOsc > dir * lllastOsc ? dir * 2 : dir lPDir := dir * llastPoint > dir * lllastPoint ? dir * 2 : dir sentiment = getSentiment(newDir, oscDir, directionBias[bar_index-bar]) llastSentiment = array.size(zigzagdivergence) >=2 ? array.get(zigzagdivergence, 1): na useHiddenDoubleD = divergenceOption == 1 or divergenceOption == 3 useRegularDoubleD = divergenceOption == 1 or divergenceOption == 2 doubleDivergence = (sentiment == llastSentiment and ((math.abs(sentiment) == 3 and useHiddenDoubleD) or (math.abs(sentiment) == 2 and useRegularDoubleD))) ? sentiment/math.abs(sentiment) : 0 add_to_array(zigzagpivots, value, numberOfPivots) add_to_array(zigzagpivotbars, bar, numberOfPivots) add_to_array(zigzagpivotdirs, newDir, numberOfPivots) add_to_array(zigzagpivotratios, ratio, numberOfPivots) add_to_array(zigzagoscillators, oscillatorSource, numberOfPivots) add_to_array(zigzagoscillatordirs, oscDir, numberOfPivots) add_to_array(zigzagtrendbias, directionBias[bar_index-bar], numberOfPivots) add_to_array(zigzagdivergence, sentiment, numberOfPivots) add_to_array(zigzagdoubledivergence, doubleDivergence, numberOfPivots) zigzagcore(phigh, plow, phighbar, plowbar, numberOfPivots, oscHigh, oscLow, directionBias, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, divergenceOption) => pDir = 1 newZG = false doubleZG = phigh and plow if array.size(zigzagpivots) >= 1 pDir := array.get(zigzagpivotdirs, 0) pDir := pDir % 2 == 0 ? pDir / 2 : pDir pDir if (pDir == 1 and phigh or pDir == -1 and plow) and array.size(zigzagpivots) >= 1 pivot = array.remove(zigzagpivots,0) pivotbar = array.remove(zigzagpivotbars,0) pivotdir = array.remove(zigzagpivotdirs,0) array.remove(zigzagpivotratios, 0) array.remove(zigzagoscillators, 0) array.remove(zigzagoscillatordirs, 0) array.remove(zigzagtrendbias, 0) array.remove(zigzagdivergence, 0) array.remove(zigzagdoubledivergence, 0) value = pDir == 1 ? phigh : plow bar = pDir == 1 ? phighbar : plowbar useNewValues = value * pivotdir > pivot * pivotdir value := useNewValues ? value : pivot bar := useNewValues ? bar : pivotbar newZG := newZG or useNewValues addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, value, bar, pDir, numberOfPivots, oscHigh, oscLow, directionBias, divergenceOption) if pDir == 1 and plow or pDir == -1 and phigh value = pDir == 1 ? plow : phigh bar = pDir == 1 ? plowbar : phighbar dir = pDir == 1 ? -1 : 1 newZG := true addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, value, bar, dir, numberOfPivots, oscHigh, oscLow, directionBias, divergenceOption) [newZG, doubleZG] draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, zigzagcolor, zigzagwidth, zigzagstyle, showHighLow, showRatios, showDivergence) => if array.size(zigzagpivots) > 2 y1 = array.get(zigzagpivots, idx1) y2 = array.get(zigzagpivots, idx2) x1 = array.get(zigzagpivotbars, idx1) x2 = array.get(zigzagpivotbars, idx2) zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=zigzagcolor, width=zigzagwidth, style=zigzagstyle) currentDir = y1 > y2? 1 : -1 label zlabel = na if(showHighLow or showRatios or showDivergence) dir = array.get(zigzagpivotdirs, idx1) ratio = array.get(zigzagpivotratios, idx1) sentiment = array.get(zigzagdivergence, idx1) [sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(sentiment) [hhllText, labelColor] = switch dir 1 => ["LH", color.orange] 2 => ["HH", color.green] -1 => ["HL", color.lime] -2 => ["LL", color.red] => ["NA", color.silver] labelText = (showHighLow? hhllText : "") + (showHighLow and showRatios? " - " : "") + (showRatios? str.tostring(ratio) : "") + ((showHighLow or showRatios) and showDivergence? " : " : "") + (showDivergence? sentimentSymbol : "") labelStyle = dir >= 0? label.style_label_down : label.style_label_up zlabel := label.new(x=x1, y=y1, yloc=yloc.price, color=showDivergence? sentimentColor : labelColor, style=labelStyle, text=labelText, textcolor=color.black, size = size.small, tooltip=hhllText) if array.size(zigzaglines) > 0 lastLine = array.get(zigzaglines, 0) if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1 line.delete(array.shift(zigzaglines)) label.delete(array.shift(zigzaglabels)) array.unshift(zigzaglines, zline) array.unshift(zigzaglabels, zlabel) if array.size(zigzaglines) > 500 line.delete(array.pop(zigzaglines)) label.delete(array.pop(zigzaglabels)) draw_zg_line2(idx1, idx2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagdivergence, zigzagdoubledivergence, zigzagcolor, zigzagwidth, zigzagstyle, showHighLow, showRatios, showDivergence, showDoubleDivergence, showIndicator) => if array.size(zigzagpivots) > 2 y1 = array.get(zigzagpivots, idx1) y2 = array.get(zigzagpivots, idx2) x1 = array.get(zigzagpivotbars, idx1) x2 = array.get(zigzagpivotbars, idx2) zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=zigzagcolor, width=zigzagwidth, style=zigzagstyle) currentDir = y1 > y2? 1 : -1 label zlabel = na if(showHighLow or showRatios or showDivergence or showIndicator or showDoubleDivergence) dir = array.get(zigzagpivotdirs, idx1) ratio = array.get(zigzagpivotratios, idx1) sentiment = array.get(zigzagdivergence, idx1) doubleDivergence = array.get(zigzagdoubledivergence, idx1) [sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(sentiment) ddLabel = getDoubleDivergenceDetails(doubleDivergence) oscillator = array.get(zigzagoscillators, idx1) [hhllText, labelColor] = switch dir 1 => ["LH", color.orange] 2 => ["HH", color.green] -1 => ["HL", color.lime] -2 => ["LL", color.red] => ["NA", color.silver] labelText = (showHighLow? hhllText : "") + (showHighLow and showRatios? " - " : "") + (showRatios? str.tostring(ratio) : "") + ((showRatios or showHighLow) and showIndicator? " - " : "") + (showIndicator ? str.tostring(oscillator) : "") + ((showHighLow or showRatios or showIndicator) and (showDivergence or showDoubleDivergence)? " : " : "") + (showDivergence? sentimentSymbol : "") + (showDivergence and showDoubleDivergence? "/" : "")+ (showDoubleDivergence? ddLabel : "") labelStyle = dir >= 0? label.style_label_down : label.style_label_up zlabel := label.new(x=x1, y=y1, yloc=yloc.price, color=showDivergence? sentimentColor : labelColor, style=labelStyle, text=labelText, textcolor=color.black, size = size.small, tooltip=hhllText) if array.size(zigzaglines) > 0 lastLine = array.get(zigzaglines, 0) if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1 line.delete(array.shift(zigzaglines)) label.delete(array.shift(zigzaglabels)) array.unshift(zigzaglines, zline) array.unshift(zigzaglabels, zlabel) if array.size(zigzaglines) > 500 line.delete(array.pop(zigzaglines)) label.delete(array.pop(zigzaglabels)) // @function zigzag: Calculates zigzag pivots and generates an array // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param useAlternativeSource : If set uses the source for genrating zigzag. Default is false // @param source : Alternative source used only if useAlternativeSource is set to true. Default is close // @param oscillatorSource : Oscillator source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param divergenceOption : 1 - hidden/regular, 2 - regular, 3 - hidden // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // newPivot : Returns true if new pivot created // doublePivot : Returns true if two new pivots are created on same bar (Happens in case of candles with long wicks and shorter zigzag lengths) export zigzag(int length, simple int numberOfPivots = 20, simple bool useAlternativeSource = false, float source=close, float oscillatorSource = close, float oscillatorHighSource = high, float oscillatorLowSource = close, int directionBias = 1, int divergenceOption=1) => var zigzagpivots = array.new_float(0) var zigzagpivotbars = array.new_int(0) var zigzagpivotdirs = array.new_int(0) var zigzagpivotratios = array.new_float(0) var zigzagoscillators = array.new_float(0) var zigzagoscillatordirs = array.new_int(0) var zigzagtrendbias = array.new_int(0) var zigzagdivergence = array.new_int(0) var zigzagdoubledivergence = array.new_int(0) oscHigh = not useAlternativeSource and oscillatorHighSource!= source? oscillatorHighSource : oscillatorSource oscLow = not useAlternativeSource and oscillatorLowSource != source? oscillatorLowSource : oscillatorSource highSource = useAlternativeSource ? source : high lowSource = useAlternativeSource ? source : low [phigh, plow, phighbar, plowbar] = pivots(length, highSource, lowSource) [newPivot, doublePivot] = zigzagcore(phigh, plow, phighbar, plowbar, numberOfPivots, oscHigh, oscLow, directionBias, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, divergenceOption) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] // @function czigzag: Calculates zigzag pivots and generates an array based on custom high and low source // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param highSource : High Source for prices to calculate zigzag. // @param lowSource : Low source for prices to calculate zigzag. // @param oscillatorHighSource : Oscillator high source for calculating divergence // @param oscillatorLowSource : Oscillator high source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param divergenceOption : 1 - hidden/regular, 2 - regular, 3 - hidden // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // zigzagdoubledivergence : Array of double divergence sentiment at each pivot // newPivot : Returns true if new pivot created // doublePivot : Returns true if two new pivots are created on same bar (Happens in case of candles with long wicks and shorter zigzag lengths) export czigzag(int length, simple int numberOfPivots = 20, float highSource = high, float lowSource = low, float oscillatorHighSource = high, float oscillatorLowSource = low, int directionBias = 1, int divergenceOption=1) => var zigzagpivots = array.new_float(0) var zigzagpivotbars = array.new_int(0) var zigzagpivotdirs = array.new_int(0) var zigzagpivotratios = array.new_float(0) var zigzagoscillators = array.new_float(0) var zigzagoscillatordirs = array.new_int(0) var zigzagtrendbias = array.new_int(0) var zigzagdivergence = array.new_int(0) var zigzagdoubledivergence = array.new_int(0) [phigh, plow, phighbar, plowbar] = pivots(length, highSource, lowSource) [newPivot, doublePivot] = zigzagcore(phigh, plow, phighbar, plowbar, numberOfPivots, oscillatorHighSource, oscillatorLowSource, directionBias, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, divergenceOption) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] // @function drawczigzag: Calculates and draws zigzag pivots and generates an array based on custom high and low source // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param highSource : High Source for prices to calculate zigzag. // @param lowSource : Low source for prices to calculate zigzag. // @param oscillatorHighSource : Oscillator high source for calculating divergence // @param oscillatorLowSource : Oscillator high source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param showHighLow : show highlow label // @param showRatios : show retracement ratios // @param showDivergence : Show divergence on label (Only works if divergence data is available - that is if we pass valid oscillatorSource and directionBias input) // @param showDoubleDivergence : Show double divergence label // @param linecolor : zigzag line color // @param linewidth : zigzag line width // @param linestyle : zigzag line style // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // zigzagdoubledivergence : Array of double divergence sentiment at each pivot // zigzaglines : Returns array of zigzag lines // zigzaglabels : Returns array of zigzag labels export drawczigzag(int length, simple int numberOfPivots = 20, float highSource = high, float lowSource = low, float oscillatorHighSource = high, float oscillatorLowSource = low, int directionBias = 1, simple bool showHighLow=false, simple bool showRatios = false, simple bool showDivergence = false, simple bool showDoubleDivergence = false, simple bool showIndicator = false, color linecolor = color.blue, int linewidth = 1, string linestyle = line.style_solid)=> [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = czigzag(length, numberOfPivots, highSource, lowSource, oscillatorHighSource, oscillatorLowSource, directionBias) var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newPivot) if doublePivot draw_zg_line2(1, 2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagdivergence, zigzagdoubledivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence, showDoubleDivergence, showIndicator) if array.size(zigzagpivots) >= 2 draw_zg_line2(0, 1, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagdivergence, zigzagdoubledivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence, showDoubleDivergence, showIndicator) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, zigzaglines, zigzaglabels] // @function drawczigzag2: Same as drawczigzag. But, returns newPivot and doublePivot bools as well. // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param highSource : High Source for prices to calculate zigzag. // @param lowSource : Low source for prices to calculate zigzag. // @param oscillatorHighSource : Oscillator high source for calculating divergence // @param oscillatorLowSource : Oscillator high source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param showHighLow : show highlow label // @param showRatios : show retracement ratios // @param showDivergence : Show divergence on label (Only works if divergence data is available - that is if we pass valid oscillatorSource and directionBias input) // @param showDoubleDivergence : Show double divergence label // @param linecolor : zigzag line color // @param linewidth : zigzag line width // @param linestyle : zigzag line style // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // zigzagdoubledivergence : Array of double divergence sentiment at each pivot // zigzaglines : Returns array of zigzag lines // zigzaglabels : Returns array of zigzag labels export drawczigzag2(int length, simple int numberOfPivots = 20, float highSource = high, float lowSource = low, float oscillatorHighSource = high, float oscillatorLowSource = low, int directionBias = 1, simple bool showHighLow=false, simple bool showRatios = false, simple bool showDivergence = false, simple bool showDoubleDivergence = false, simple bool showIndicator = false, color linecolor = color.blue, int linewidth = 1, string linestyle = line.style_solid)=> [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = czigzag(length, numberOfPivots, highSource, lowSource, oscillatorHighSource, oscillatorLowSource, directionBias) var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newPivot) if doublePivot draw_zg_line2(1, 2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagdivergence, zigzagdoubledivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence, showDoubleDivergence, showIndicator) if array.size(zigzagpivots) >= 2 draw_zg_line2(0, 1, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagdivergence, zigzagdoubledivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence, showDoubleDivergence, showIndicator) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot, zigzaglines, zigzaglabels] // @function drawzigzag: Calculates and draws zigzag pivots // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param useAlternativeSource: If set uses the source for genrating zigzag. Default is false // @param source : Alternative source used only if useAlternativeSource is set to true. Default is close // @param linecolor : zigzag line color // @param linewidth : zigzag line width // @param linestyle : zigzag line style // @param oscillatorSource : Oscillator source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param showHighLow : show highlow label // @param showRatios : show retracement ratios // @param showDivergence : Show divergence on label (Only works if divergence data is available - that is if we pass valid oscillatorSource and directionBias input) // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // zigzaglines : Returns array of zigzag lines // zigzaglabels : Returns array of zigzag labels export drawzigzag(int length, simple int numberOfPivots = 20, simple bool useAlternativeSource = false, float source=close, color linecolor = color.blue, int linewidth = 1, string linestyle = line.style_solid, float oscillatorSource = close, float oscillatorHighSource = high, float oscillatorLowSource = close, int directionBias = 1, simple bool showHighLow=false, simple bool showRatios = false, simple bool showDivergence = false)=> [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = zigzag(length, numberOfPivots, useAlternativeSource, source, oscillatorSource, oscillatorHighSource, oscillatorLowSource, directionBias) var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newPivot) if doublePivot draw_zg_line(1, 2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence) if array.size(zigzagpivots) >= 2 draw_zg_line(0, 1, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzaglines, zigzaglabels] // ************************************************************* Demonstrating usage examples *************************************************************/ operation = input.string("Draw Zigzag", "Operation", options=["Draw Zigzag", "Get Zigzag"], group="Zigzag", inline="z") zigzagLength = input.int(5, "", group="Zigzag", inline="z") useAlternativeSource = input.bool(false, "Use Alternative Source", group="Alternate Source", inline="s") source = input.source(close, "", group="Alternate Source", inline="s") useDifferentLineStyle = input.bool(false, "Use Different Line Style", group="Line Style", inline="l") linecolor = input.color(color.maroon, "", group="Line Style", inline="l") linewidth = input.int(3, "", group="Line Style", inline="l") linestyle = input.string(line.style_dashed, "", options=[line.style_solid, line.style_dashed, line.style_dotted], group="Line Style", inline="l") showHighLow = input.bool(false, "HHLL", group="Display Labels", inline="lb") showRatios = input.bool(false, "Ratios", group="Display Labels", inline="lb") showOscillator = input.bool(false, "Oscillator", group="Display Labels", inline="lb") showDivergence = input.bool(false, "Divergence", group="Display Labels", inline="lb") showDoubleDivergence = input.bool(false, "Double Divergence", group="Display Labels", inline="lb") if(operation == "Draw Zigzag") rsi = ta.rsi(close, 14) rsiHigh = ta.rsi(high, 14) rsiLow = ta.rsi(low, 14) [supertrend, dir] = ta.supertrend(4, 22) directionBias = int(-dir) if(not useDifferentLineStyle) drawczigzag(zigzagLength, highSource=high, lowSource=low, oscillatorHighSource=rsiHigh, oscillatorLowSource=rsiLow, directionBias = directionBias, showHighLow=showHighLow, showRatios=showRatios, showDivergence=showDivergence, showDoubleDivergence=showDoubleDivergence, showIndicator=showOscillator) else drawczigzag(zigzagLength, highSource=high, lowSource=low, linecolor=linecolor, linewidth = linewidth, linestyle = linestyle, oscillatorHighSource=rsiHigh, oscillatorLowSource=rsiLow, directionBias = directionBias, showHighLow=showHighLow, showRatios=showRatios, showDivergence=showDivergence, showDoubleDivergence=showDoubleDivergence, showIndicator=showOscillator) else // Plain zigzag when nothing is selected if(not useAlternativeSource and not showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = zigzag(zigzagLength) // When using Alternate source else if(useAlternativeSource and not showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = zigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source) // When divergence is included else //Calculating Oscillator and direction bias for divergence rsi = ta.rsi(close, 14) [supertrend, dir] = ta.supertrend(4, 22) directionBias = int(-dir) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzagdoubledivergence, newPivot, doublePivot] = zigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, oscillatorSource=rsi, directionBias = directionBias) false
MathComplexEvaluate
https://www.tradingview.com/script/SI4Lh03O-MathComplexEvaluate/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
11
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description TODO: add library description here library(title='MathComplexEvaluate') //#region -> Imports: import RicardoSantos/DebugConsole/11 as console logger = console.Console.new().init() import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/MathComplexCore/3 as complex import RicardoSantos/MathComplexOperator/2 as complex_op import RicardoSantos/MathComplexExtension/2 as complex_ex import RicardoSantos/MathComplexArray/2 as complex_ar import RicardoSantos/StringEvaluation/1 as str_eval //#endregion //#region -> Helper Constant and Functions: string RGXop = '[-+*/%^]?' string RGXfloat = '((\\.\\d+)|(\\d*\\.\\d+)|(\\d+\\.?))' string RGXreal = '([-+]?'+RGXfloat+'(?:[eE^][-+]?'+RGXfloat+')?)' string RGXrealcomplex = '('+RGXreal+'[ijIJ]?)' string RGXcomplex = RGXop+'('+'('+RGXreal+'[-+]'+RGXreal+'[ijIJ])'+'|'+RGXrealcomplex+')' // is_op () { // @function Check if char is a operator. // @param char string, 1 character string. // @returns bool. is_op (string char) => switch char '+' => true '-' => true '*' => true '/' => true '^' => true '%' => true => false // } // operator () { // @function operation between left and right values. // @param op string, operator string character. // @param left float, left value of operation. // @param right float, right value of operation. operator (string op, TMath.complex left, TMath.complex right) => switch op '+' => complex_op.add(left, right) '-' => complex_op.subtract(left, right) '*' => complex_op.multiply(left, right) '/' => complex_op.divide(left, right) '^' => complex_ex.power(left, right) '%' => complex_op.divide(left, right) // modulo of complex number is sqrt(a^2 + b^2) or abs(a+bi) => complex.nan() // } // operator_precedence () { // @function level of precedence of operator. // @param op string, operator 1 char string. // @returns int. operator_precedence (string op) => switch op '+' => 2 '-' => 2 '*' => 3 '/' => 3 '^' => 4 '%' => 3 => 0 // } //#endregion // eval () { // reference: // https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm // @function evaluate a string with references to a array of arguments. //| @param expression string, arithmetic operations with references to indices in arguments, ex:"0+1*0+2*2+3" arguments[1, 2, 3] //| @param arguments float array, arguments. //| @returns Complex Number, solution. export eval (string expression, array<TMath.complex> arguments) => int _size_a = array.size(id=arguments) if _size_a < 1 runtime.error('MathComplexEvaluate -> eval(): "arguments" is empty.') complex.nan() else string[] _tokens = str_eval.generate_rpn(str_eval.cleanup(expression)) array<TMath.complex> _args = array.copy(arguments) int _size_t = array.size(id=_tokens) if _size_t < 1 runtime.error('MathComplexEvaluate -> eval(): "expression" is empty.') complex.nan() else // calculate solution: TMath.complex _solution = complex.nan() _stack = array.new_int() for _i = 0 to _size_t-1 string _token = array.get(id=_tokens, index=_i) float _number = str.tonumber(_token) if not na(_number)// array.push(id=_stack, value=int(_number)) else if array.size(id=_stack) > 1 // runtime.error('StringEvaluation -> generate_rpn(): insufficient operands!!.\n' + str.tostring(_stack)) // else o2 = array.pop(id=_stack) o1 = array.pop(id=_stack) if is_op(_token) TMath.complex _op = operator(_token, _args.get(o1), _args.get(o2)) _args.push(_op) array.push(id=_stack, value=int(array.size(_args)/2)-1) else runtime.error('MathComplexEvaluate -> eval(): unrecognized operator: (' + _token + ' ).') _solution := _args.pop() _solution // usage: array<TMath.complex> args = array.new<TMath.complex>(1, complex.from(input.string('3.141+1.618i'))) for _i = 0 to 5 args.push(complex.new(math.random(), math.random())) string ev1 = input.string('((0+ 0 *2/1-3)%0)^4') string ev2 = input.string('((0+ 0 *2/1-3)+0)^4') logger.queue_one(str.format('arguments: {0}', complex_ar.to_string(args, '#.##'))) logger.queue_one(str.format('expression using idx: {0} = {1}', ev1, complex.to_string(eval(ev1, args), '#.##'))) logger.queue_one(str.format('expression using idx: {0} = {1}', ev2, complex.to_string(eval(ev2, args), '#.##'))) // } // parse () { // @function Parse a string expression that may contain numbers and complex numbers. // @param expression string . Expression to evaluate, ex:. `"2i*(3+2-3J)-2.0e3+1.0e-15i"`. // @returns Complex number. Solution. export parse (string expression) => string _exp = str.replace_all(expression, ' ', '') array<string> _tokens = array.new<string>() array<string> _unique = array.new<string>() for _i = 0 to 20 string _t = str.match(_exp, RGXcomplex) if _t == 'na' or _t == '' break else // find the tokens that match a number or complex number expression: string _prefix = str.substring(_t, 0, 1) string _op = is_op(_prefix) ? _prefix : '' string _suffix = is_op(_prefix) ? str.substring(_t, 1, str.length(_t)) : str.substring(_t, 0, str.length(_t)) _tokens.push(_suffix) _exp := str.replace(_exp, _t, _op+'na', 0) // populate unique id list of tokens: int _idx = array.indexof(_unique, _suffix) if _idx < 0 _unique.push(_suffix) // replace `na` placeholders with token array indices, // and convert tokens to complex numbers: array<TMath.complex> _args = array.new<TMath.complex>() for _token in _tokens int _idx = array.indexof(_unique, _token) _exp := str.replace(_exp, 'na', str.tostring(_idx, '#'), 0) _args.push(complex.from(_token)) eval(_exp, _args) string str = input.text_area('1i*2+2i/2 + 2-1.0+3.0i') logger.queue_one(complex.to_string(parse(str))) // } logger.update() // // formula: // 1.0+1.0 1.0e1+1.0e1 .0+.0 // +1+1-2+1-1+2-2+1+1+1+1+1*1*1*/1/1+1*2-1/1-+* // -1*1e1i/1.0+1i+1.0*1-.2e-1i // 1i*2+2i/2+2-1.0+3.0i // ..0 1..0 1...0...0.0.000.0...0...00..... // . ++-* // real : 0 -0 .0 -.0 -0.0 0e0 -0e0 -0e-0 0.0e0.0 -0.0e-0.0 00 -00 00e00 -00e-00 00.00e00.00 -00.00e-00.00 // real complex : 0i -0i .0i -.0i -0.0i 0e0i -0e0i -0e-0i 0.0e0.0i -0.0e-0.0i 00i -00i 00e00i -00e-00i 00.00e00.00i -00.00e-00.00i // complex : 0+0i -0-0i .0+.0i -.0-.0i -0.0-0.0i 0e0+0e0i -0e0-0e0i -0e-0-0e-0i 0.0e0.0+0.0e0.0i -0.0e-0.0-0.0e-0.0i // 00+00i -00-00i 00e00+00e00i -00e-00-00e-00i 00.00e00.00+00.00e00.00i -00.00e-00.00-00.00e-00.00i // last = '(([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?)[-+]([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?)[i])|([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?[i]?)' // wOPs = '[-+*/%^]?((([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?)[-+]([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?)[ijIJ])|([-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?))(?:[eE^][-+]?((\.\d+)|(\d*\.\d+)|(\d+\.?)))?[ijIJ]?))'
FunctionGeometricLineDrawings
https://www.tradingview.com/script/ie6MFhIW-FunctionGeometricLineDrawings/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
34
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods to draw geometric objects. library(title='FunctionGeometricLineDrawings') // @function deletes all lines in array. // @param lines line array, array with line objects to delete. // @returns void. export array_delete_all_lines(line[] lines) => int _size = array.size(lines) for _i = 0 to _size-1 line.delete(array.get(lines, _i)) // @function Draw a Triangle with 3 vector2D(x, y) coordinates. // @param sample_x int array, triangle sample data X coordinate values. // @param sample_y float array, triangle sample data Y coordinate values. // @param xloc string, defaultoptions=xloc.bar_index, xloc.bar_time. // @param extend string, default=extend.none, options=(extend.none, extend.right, extend.left, extend.both). // @param color color, default= // @param style options line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both // @param width width in pixels. // @returns line array export triangle (int[] sample_x, float[] sample_y, string xloc=xloc.bar_index, string extend=extend.none, color color=#252525, string style=line.style_solid, int width=1) => //{ int _size_x = array.size(sample_x) int _size_y = array.size(sample_y) // switch (_size_x != 3) => runtime.error('FunctionGeometricLineDrawings -> triangle(): "sample_x" has the wrong size.') (_size_x != _size_y) => runtime.error('FunctionGeometricLineDrawings -> triangle(): "sample_x" and "sample_y" size does not match.') // var line[] _triangle = array.new_line(3) int _x1 = array.get(sample_x, 0), int _x2 = array.get(sample_x, 1), int _x3 = array.get(sample_x, 2) float _y1 = array.get(sample_y, 0), float _y2 = array.get(sample_y, 1), float _y3 = array.get(sample_y, 2) // draw the lines: array.set(_triangle, 0, line.new(x1=_x1, y1=_y1, x2=_x2, y2=_y2, xloc=xloc, extend=extend, color=color, style=style, width=width)) array.set(_triangle, 1, line.new(x1=_x2, y1=_y2, x2=_x3, y2=_y3, xloc=xloc, extend=extend, color=color, style=style, width=width)) array.set(_triangle, 2, line.new(x1=_x3, y1=_y3, x2=_x1, y2=_y1, xloc=xloc, extend=extend, color=color, style=style, width=width)) _triangle //{ usage: show_triangle = input(true) triangle_x1 = input(defval=4) triangle_y1 = input(defval=4.0) triangle_x2 = input(defval=0) triangle_y2 = input(defval=18.0) triangle_x3 = input(defval=8) triangle_y3 = input(defval=15.0) triangle_xloc = input.string(defval=xloc.bar_index, options=[xloc.bar_index, xloc.bar_time]) triangle_xtend = input.string(defval=extend.none, options=[extend.none, extend.right, extend.left, extend.both]) triangle_style = input.string(defval=line.style_solid, options=[line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both]) triangle_width = input.int(2, minval=0) var line[] triangle_lines = array.new_line(3) if show_triangle _adjust_x1 = triangle_xloc == xloc.bar_index ? bar_index - triangle_x1 : timenow + triangle_x1 * 60000 _adjust_x2 = triangle_xloc == xloc.bar_index ? bar_index - triangle_x2 : timenow + triangle_x2 * 60000 _adjust_x3 = triangle_xloc == xloc.bar_index ? bar_index - triangle_x3 : timenow + triangle_x3 * 60000 _X = array.from(_adjust_x1, _adjust_x2, _adjust_x3) _Y = array.from(triangle_y1, triangle_y2, triangle_y3) array_delete_all_lines(triangle_lines) triangle_lines := triangle(_X, _Y, triangle_xloc, triangle_xtend, color.new(#5555ff, 50), triangle_style, triangle_width) //{ remarks: // (x2, y2) // ┐ // ∕ │ // Side1 ∕ │ Side2 // ⁄ │ // └───────┘ // (x1,y1) Side3 (x3, y3) //}}} // @function Draw a Trapezoid with 4 vector2D(x, y) coordinates: // @param sample_x int array, trapezoid sample data X coordinate values. // @param sample_y float array, trapezoid sample data Y coordinate values. // @param xloc string, defaultoptions=xloc.bar_index, xloc.bar_time. // @param extend string, default=extend.none, options=(extend.none, extend.right, extend.left, extend.both). // @param color color, default= // @param style options line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both // @param width width in pixels. // @returns line array export trapezoid (int[] sample_x, float[] sample_y, string xloc=xloc.bar_index, string extend=extend.none, color color=#252525, string style=line.style_solid, int width=1) => //{ int _size_x = array.size(sample_x) int _size_y = array.size(sample_y) // switch (_size_x != 4) => runtime.error('FunctionGeometricLineDrawings -> trapezoid(): "sample_x" has the wrong size.') (_size_x != _size_y) => runtime.error('FunctionGeometricLineDrawings -> trapezoid(): "sample_x" and "sample_y" size does not match.') // var line[] _trapezoid = array.new_line(3) int _x1 = array.get(sample_x, 0), int _x2 = array.get(sample_x, 1), int _x3 = array.get(sample_x, 2), int _x4 = array.get(sample_x, 3) float _y1 = array.get(sample_y, 0), float _y2 = array.get(sample_y, 1), float _y3 = array.get(sample_y, 2), float _y4 = array.get(sample_y, 3) // draw the lines: array.set(_trapezoid, 0, line.new(x1=_x1, y1=_y1, x2=_x2, y2=_y2, xloc=xloc, extend=extend, color=color, style=style, width=width)) array.set(_trapezoid, 1, line.new(x1=_x2, y1=_y2, x2=_x3, y2=_y3, xloc=xloc, extend=extend, color=color, style=style, width=width)) array.set(_trapezoid, 2, line.new(x1=_x3, y1=_y3, x2=_x4, y2=_y4, xloc=xloc, extend=extend, color=color, style=style, width=width)) array.set(_trapezoid, 2, line.new(x1=_x4, y1=_y4, x2=_x1, y2=_y1, xloc=xloc, extend=extend, color=color, style=style, width=width)) _trapezoid //{ usage: show_trapezoid = input(true) trapezoid_x1 = input(defval=15) trapezoid_y1 = input(defval=4.0) trapezoid_x2 = input(defval=10) trapezoid_y2 = input(defval=25.0) trapezoid_x3 = input(defval=5) trapezoid_y3 = input(defval=20.0) trapezoid_x4 = input(defval=2) trapezoid_y4 = input(defval=2.0) trapezoid_xloc = input.string(defval=xloc.bar_index, options=[xloc.bar_index, xloc.bar_time]) trapezoid_xtend = input.string(defval=extend.none, options=[extend.none, extend.right, extend.left, extend.both]) trapezoid_style = input.string(defval=line.style_dashed, options=[line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both]) trapezoid_width = input.int(2, minval=0) var line[] trapezoid_lines = array.new_line(4) if show_trapezoid and barstate.islast and barstate.ishistory[1] _adjust_x1 = trapezoid_xloc == xloc.bar_index ? bar_index - trapezoid_x1 : timenow + trapezoid_x1 * 60000 _adjust_x2 = trapezoid_xloc == xloc.bar_index ? bar_index - trapezoid_x2 : timenow + trapezoid_x2 * 60000 _adjust_x3 = trapezoid_xloc == xloc.bar_index ? bar_index - trapezoid_x3 : timenow + trapezoid_x3 * 60000 _adjust_x4 = trapezoid_xloc == xloc.bar_index ? bar_index - trapezoid_x4 : timenow + trapezoid_x4 * 60000 _X = array.from(_adjust_x1, _adjust_x2, _adjust_x3, _adjust_x4) _Y = array.from(trapezoid_y1, trapezoid_y2, trapezoid_y3, trapezoid_y4) array_delete_all_lines(trapezoid_lines) trapezoid_lines := trapezoid(_X, _Y, trapezoid_xloc, trapezoid_xtend, color.new(#ff5522, 50), trapezoid_style, trapezoid_width) //{ ramarks: // (x2,y2) Side2 (x3, y3) // ┌───────┐ // │ │ // Side1 │ │ Side3 // │ │ // └───────┘ // (x1,y1) Side4 (x4, y4) //}}}
zigzagplus
https://www.tradingview.com/script/OidafFyO-zigzagplus/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
195
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Library dedicated to zigzags and related indicators library("zigzagplus", overlay=true) add_to_array(arr, val, maxItems) => array.push(arr, val) if array.size(arr) > maxItems array.remove(arr, 0) pivots(length, useAlternativeSource, source) => highsource = useAlternativeSource ? source : high lowsource = useAlternativeSource ? source : low float phigh = ta.highestbars(highsource, length) == 0 ? highsource : na float plow = ta.lowestbars(lowsource, length) == 0 ? lowsource : na [phigh, plow, bar_index, bar_index] getSentiment(pDir, oDir, sDir) => sentiment = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3) sentiment getSentimentDetails(sentiment) => sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣' sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I' [sentimentSymbol, sentimentLabel, sentimentColor] addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, value, bar, dir, numberOfPivots, oscillatorSource, directionBias) => newDir = dir oscDir = dir ratio = 1.0 if array.size(zigzagpivots) >= 2 lastPoint = array.get(zigzagpivots, array.size(zigzagpivots)-1) llastPoint = array.get(zigzagpivots, array.size(zigzagpivots)-2) newDir := dir * value > dir * llastPoint ? dir * 2 : dir ratio := math.round(math.abs(value-lastPoint)/math.abs(llastPoint-lastPoint), 2) llastOsc = array.get(zigzagoscillators, array.size(zigzagpivots)-2) oscDir := dir * oscillatorSource[bar_index - bar] > dir * llastOsc ? dir * 2 : dir sentiment = getSentiment(newDir, oscDir, directionBias[bar_index-bar]) add_to_array(zigzagpivots, value, numberOfPivots) add_to_array(zigzagpivotbars, bar, numberOfPivots) add_to_array(zigzagpivotdirs, newDir, numberOfPivots) add_to_array(zigzagpivotratios, ratio, numberOfPivots) add_to_array(zigzagoscillators, oscillatorSource[bar_index - bar], numberOfPivots) add_to_array(zigzagoscillatordirs, oscDir, numberOfPivots) add_to_array(zigzagtrendbias, directionBias[bar_index-bar], numberOfPivots) add_to_array(zigzagdivergence, sentiment, numberOfPivots) zigzagcore(phigh, plow, phighbar, plowbar, numberOfPivots, oscillatorSource, directionBias, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence) => pDir = 1 newZG = false doubleZG = phigh and plow if array.size(zigzagpivots) >= 1 pDir := array.get(zigzagpivotdirs, array.size(zigzagpivots)-1) pDir := pDir % 2 == 0 ? pDir / 2 : pDir pDir if (pDir == 1 and phigh or pDir == -1 and plow) and array.size(zigzagpivots) >= 1 pivot = array.pop(zigzagpivots) pivotbar = array.pop(zigzagpivotbars) pivotdir = array.pop(zigzagpivotdirs) array.pop(zigzagpivotratios) array.pop(zigzagoscillators) array.pop(zigzagoscillatordirs) array.pop(zigzagtrendbias) array.pop(zigzagdivergence) value = pDir == 1 ? phigh : plow bar = pDir == 1 ? phighbar : plowbar useNewValues = value * pivotdir > pivot * pivotdir value := useNewValues ? value : pivot bar := useNewValues ? bar : pivotbar newZG := newZG or useNewValues addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, value, bar, pDir, numberOfPivots, oscillatorSource, directionBias) if pDir == 1 and plow or pDir == -1 and phigh value = pDir == 1 ? plow : phigh bar = pDir == 1 ? plowbar : phighbar dir = pDir == 1 ? -1 : 1 newZG := true addnewpivot(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, value, bar, dir, numberOfPivots, oscillatorSource, directionBias) [newZG, doubleZG] draw_zg_line(ix1, ix2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, zigzagcolor, zigzagwidth, zigzagstyle, showHighLow, showRatios, showDivergence) => idx1 = array.size(zigzagpivots) - ix1 - 1 idx2 = array.size(zigzagpivots) - ix2 - 1 if array.size(zigzagpivots) > 2 y1 = array.get(zigzagpivots, idx1) y2 = array.get(zigzagpivots, idx2) x1 = array.get(zigzagpivotbars, idx1) x2 = array.get(zigzagpivotbars, idx2) zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=zigzagcolor, width=zigzagwidth, style=zigzagstyle) currentDir = y1 > y2? 1 : -1 label zlabel = na if(showHighLow or showRatios or showDivergence) dir = array.get(zigzagpivotdirs, idx1) ratio = array.get(zigzagpivotratios, idx1) sentiment = array.get(zigzagdivergence, idx1) [sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(sentiment) [hhllText, labelColor] = switch dir 1 => ["LH", color.orange] 2 => ["HH", color.green] -1 => ["HL", color.lime] -2 => ["LL", color.red] => ["NA", color.silver] labelText = (showHighLow? hhllText : "") + (showHighLow and showRatios? " - " : "") + (showRatios? str.tostring(ratio) : "") + ((showHighLow or showRatios) and showDivergence? " : " : "") + (showDivergence? sentimentSymbol : "") labelStyle = dir >= 0? label.style_label_down : label.style_label_up zlabel := label.new(x=x1, y=y1, yloc=yloc.price, color=showDivergence? sentimentColor : labelColor, style=labelStyle, text=labelText, textcolor=color.black, size = size.small, tooltip=hhllText) if array.size(zigzaglines) > 0 lastLine = array.get(zigzaglines, 0) if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1 line.delete(array.shift(zigzaglines)) label.delete(array.shift(zigzaglabels)) array.unshift(zigzaglines, zline) array.unshift(zigzaglabels, zlabel) if array.size(zigzaglines) > 500 line.delete(array.pop(zigzaglines)) label.delete(array.pop(zigzaglabels)) // @function zigzag: Calculates zigzag pivots and generates an array // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param useAlternativeSource : If set uses the source for genrating zigzag. Default is false // @param source : Alternative source used only if useAlternativeSource is set to true. Default is close // @param oscillatorSource : Oscillator source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // newPivot : Returns true if new pivot created // doublePivot : Returns true if two new pivots are created on same bar (Happens in case of candles with long wicks and shorter zigzag lengths) export zigzag(int length, simple int numberOfPivots = 20, simple bool useAlternativeSource = false, float source=close, float oscillatorSource = close, int directionBias = 1) => var zigzagpivots = array.new_float(0) var zigzagpivotbars = array.new_int(0) var zigzagpivotdirs = array.new_int(0) var zigzagpivotratios = array.new_float(0) var zigzagoscillators = array.new_float(0) var zigzagoscillatordirs = array.new_int(0) var zigzagtrendbias = array.new_int(0) var zigzagdivergence = array.new_int(0) [phigh, plow, phighbar, plowbar] = pivots(length, useAlternativeSource, source) [newPivot, doublePivot] = zigzagcore(phigh, plow, phighbar, plowbar, numberOfPivots, oscillatorSource, directionBias, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence) pivotsize = array.size(zigzagpivots) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] // @function drawzigzag: Calculates and draws zigzag pivots // @param length : Zigzag Length // @param numberOfPivots : Max number of pivots to return in the array. Default is 20 // @param useAlternativeSource: If set uses the source for genrating zigzag. Default is false // @param source : Alternative source used only if useAlternativeSource is set to true. Default is close // @param linecolor : zigzag line color // @param linewidth : zigzag line width // @param linestyle : zigzag line style // @param oscillatorSource : Oscillator source for calculating divergence // @param directionBias : Direction bias for calculating divergence // @param showHighLow : show highlow label // @param showRatios : show retracement ratios // @param showDivergence : Show divergence on label (Only works if divergence data is available - that is if we pass valid oscillatorSource and directionBias input) // @returns zigzagpivots : Array containing zigzag pivots // zigzagpivotbars : Array containing zigzag pivot bars // zigzagpivotdirs : Array containing zigzag pivot directions (Lower High : 1, Higher High : 2, Lower Low : -2 and Higher Low : -1) // zigzagpivotratios : Array containing zigzag retracement ratios for each pivot // zigzagoscillators : Array of oscillator values at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagoscillatordirs: Array of oscillator directions (HH, HL, LH, LL) at pivots. Will have valid values only if valid oscillatorSource is provided as per input. // zigzagtrendbias : Array of trend bias at pivots. Will have valid value only if directionBias series is sent in input parameters // zigzagdivergence : Array of divergence sentiment at each pivot. Will have valid values only if oscillatorSource and directionBias inputs are provided // zigzaglines : Returns array of zigzag lines // zigzaglabels : Returns array of zigzag labels export drawzigzag(int length, simple int numberOfPivots = 20, simple bool useAlternativeSource = false, float source=close, color linecolor = color.blue, int linewidth = 1, string linestyle = line.style_solid, float oscillatorSource = close, int directionBias = 1, simple bool showHighLow=false, simple bool showRatios = false, simple bool showDivergence = false)=> [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zigzag(length, numberOfPivots, useAlternativeSource, source, oscillatorSource, directionBias) var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newPivot) if doublePivot draw_zg_line(1, 2, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence) if array.size(zigzagpivots) >= 2 draw_zg_line(0, 1, zigzaglines, zigzaglabels, zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagdivergence, linecolor, linewidth, linestyle, showHighLow, showRatios, showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, zigzaglines, zigzaglabels] // ************************************************************* Demonstrating usage examples *************************************************************/ operation = input.string("Draw Zigzag", "Operation", options=["Draw Zigzag", "Get Zigzag"], group="Zigzag", inline="z") zigzagLength = input.int(5, "", group="Zigzag", inline="z") useAlternativeSource = input.bool(false, "Use Alternative Source", group="Alternate Source", inline="s") source = input.source(close, "", group="Alternate Source", inline="s") useDifferentLineStyle = input.bool(false, "Use Different Line Style", group="Line Style", inline="l") linecolor = input.color(color.maroon, "", group="Line Style", inline="l") linewidth = input.int(3, "", group="Line Style", inline="l") linestyle = input.string(line.style_dashed, "", options=[line.style_solid, line.style_dashed, line.style_dotted], group="Line Style", inline="l") showHighLow = input.bool(false, "HHLL", group="Display Labels", inline="lb") showRatios = input.bool(false, "Ratios", group="Display Labels", inline="lb") showDivergence = input.bool(false, "Divergence", group="Display Labels", inline="lb") if(operation == "Draw Zigzag") // Plain zigzag when nothing is selected if(not useAlternativeSource and not useDifferentLineStyle and not showDivergence and not showHighLow and not showRatios) drawzigzag(zigzagLength) // When using Alternate source else if(useAlternativeSource and not useDifferentLineStyle and not showDivergence and not showHighLow and not showRatios) drawzigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source) // When using different line style else if(not useAlternativeSource and useDifferentLineStyle and not showDivergence and not showHighLow and not showRatios) drawzigzag(zigzagLength, linecolor=linecolor, linewidth = linewidth, linestyle = linestyle) // Few options selected - just for example else if(not useAlternativeSource and not useDifferentLineStyle and not showDivergence) drawzigzag(zigzagLength, showHighLow=showHighLow, showRatios=showRatios) // Few options selected - just for example else if(useAlternativeSource and not useDifferentLineStyle and not showDivergence) drawzigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, showHighLow=showHighLow, showRatios=showRatios) // All other cases when divergence is not needed else if not showDivergence drawzigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, linecolor=linecolor, linewidth = linewidth, linestyle = linestyle, showHighLow=showHighLow, showRatios=showRatios) // When showing divergence else //Calculating Oscillator and direction bias for divergence rsi = ta.rsi(close, 14) [supertrend, dir] = ta.supertrend(4, 22) directionBias = int(-dir) if(not useDifferentLineStyle) drawzigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, oscillatorSource=rsi, directionBias = directionBias, showHighLow=showHighLow, showRatios=showRatios, showDivergence=showDivergence) else drawzigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, linecolor=linecolor, linewidth = linewidth, linestyle = linestyle, oscillatorSource=rsi, directionBias = directionBias, showHighLow=showHighLow, showRatios=showRatios, showDivergence=showDivergence) false else // Plain zigzag when nothing is selected if(not useAlternativeSource and not showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zigzag(zigzagLength) // When using Alternate source else if(useAlternativeSource and not showDivergence) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source) // When divergence is included else //Calculating Oscillator and direction bias for divergence rsi = ta.rsi(close, 14) [supertrend, dir] = ta.supertrend(4, 22) directionBias = int(-dir) [zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagpivotratios, zigzagoscillators, zigzagoscillatordirs, zigzagtrendbias, zigzagdivergence, newPivot, doublePivot] = zigzag(zigzagLength, useAlternativeSource=useAlternativeSource, source = source, oscillatorSource=rsi, directionBias = directionBias) false
MLLossFunctions
https://www.tradingview.com/script/IK2w69iH-MLLossFunctions/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
26
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Methods for Loss functions. library("MLLossFunctions") import RicardoSantos/DebugConsole/6 as console [__T, __C] = console.init(25) // reference: // https://kobiso.github.io/research/research-loss-functions/ // https://machinelearningmastery.com/loss-and-loss-functions-for-training-deep-learning-neural-networks/ // @function Mean Squared Error (MSE) " MSE = 1/N * sum[i=1:N]((y - y')^2) ". // @param expects float array, expected values. // @param predicts float array, prediction values. // @returns float export mse (float[] expects, float[] predicts) => //{ int _size_e = array.size(expects) int _size_p = array.size(predicts) switch (_size_e < 1) => runtime.error('MLLossFunctions -> mse(): "expects" has wrong size.') (_size_e != _size_p) => runtime.error('MLLossFunctions -> mse(): "expects" and "predicts" size does not match.') float _sum = 0.0 for _i = 0 to _size_e - 1 _sum += math.pow(array.get(expects, _i) - array.get(predicts, _i), 2.0) _sum / _size_e //{ usage: //{ remarks: //}}} // @function Binary Cross-Entropy Loss (log). // @param expects float array, expected values. // @param predicts float array, prediction values. // @returns float export binary_cross_entropy (float[] expects, float[] predicts) => //{ int _size_e = array.size(expects) int _size_p = array.size(predicts) // switch (_size_e < 1) => runtime.error('MLLossFunctions -> binary_cross_entropy(): "expects" has wrong size.') (_size_e != _size_p) => runtime.error('MLLossFunctions -> binary_cross_entropy(): "expects" and "predicts" size does not match.') // float _sum = 0.0 for _i = 0 to _size_e - 1 float _e = array.get(expects, _i) // y float _p = array.get(predicts, _i)// yhat _sum += _e * math.log(_p) + (1.0 - _e) * math.log(1.0 - _p) 0.0 - ((1.0 / _size_e) * _sum) //{ usage: i1 = array.from(0.19858, 0.28559, 0.51583) i2 = array.from(0.2698, 0.3223, 0.4078) y = array.from(1.0, 0.0, 0.0) // expected i3 = array.from(.5, .7, .2, .3, .5, .6) y3 = array.from(0.0, 1, 0, 0, 0, 0) var float ce1 = binary_cross_entropy(y, i1) var float ce2 = binary_cross_entropy(y, i2) var float ce3 = binary_cross_entropy(y3, i3) // expected: 0.53984624 //https://neptune.ai/blog/cross-entropy-loss-and-its-applications-in-deep-learning console.queue_one(__C, str.format('{0}, {1}, {2}', ce1, ce2, ce3)) //{ remarks: // reference: https://sparrow.dev/binary-cross-entropy/ //}}} console.update(__T, __C)
OteHmacSha256
https://www.tradingview.com/script/s5bVPWvl-OteHmacSha256/
OgahTerkenal
https://www.tradingview.com/u/OgahTerkenal/
8
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © OgahTerkenal ([email protected]) //@version=5 // @description Library to use HMAC SHA-256 by OgahTerkenal library(title="OteHmacSha256", overlay=true) // TABLE OF CONTENTS: // - SECTION (ID: 01) == UTILITY FUNCTION // - SECTION (ID: 02) == EXPORTED FUNCTION // - SECTION (ID: 03) == USAGE EXAMPLE // - SECTION (ID: 04) == REFERENCES // * Use it to quickly jump/find // IMPORTANT NOTE: // - Only ASCII 32 to 126 characters only, outside that might produce // unexpected result. // - Using barstate.islast or anything that prevent this function to run when // script is LOADED is a MUST // - Running this function during load (reload/switch chart/anything else which // will make calculation on historical bar re-iterated) will most likely // causes SCRIPT TIMEOUT // SCRIPT HISTORY: // 2022-09-26: - Update functions in UTILITY FUNCTION to strictly declare // parameter type to prevent compilation error as stated by // @stormRidr // - Re-arranged sections and contents of the script // 2021-12-24: - Initial // == SECTION (ID: 01) == UTILITY FUNCTION == END == XORGate(string a, string b) => if (a != "1" and a != "0") or (b != "1" and b != "0") runtime.error("OTE HMAC SHA-256 LibError at XORGate(): One of the input is not '1' neither '0', input is: a(" + str.tostring(a) + "), b(" + str.tostring(b) + ")") a == b ? "0" : "1" // the actual xor gate should sum the active bits, if it's odd then return true, but since we dealing only 2 this should be enough ANDGate(string a, string b) => if (a != "1" and a != "0") or (b != "1" and b != "0") runtime.error("OTE HMAC SHA-256 LibError at ANDGate(): One of the input is not '1' neither '0', input is: a(" + str.tostring(a) + "), b(" + str.tostring(b) + ")") a == "1" and b == "1" ? "1" : "0" NOTGate(string a) => if a != "1" and a != "0" runtime.error("OTE HMAC SHA-256 LibError at NOTGate(): Input is not '1' neither '0', input is: " + str.tostring(a)) a == "1" ? "0" : "1" binaryRotateRight(string binaryString, int _rotateLen) => len = str.length(binaryString) rotateLen = _rotateLen % len // so when string is rotated the same number as it's own length, the result is same lastIndex = len - 1 startIndex = lastIndex - (rotateLen - 1) endIndex = startIndex + rotateLen str.substring(binaryString, startIndex, endIndex) + str.substring(binaryString, 0, len - rotateLen) binaryShiftRight(string binaryString, int shiftLen) => len = str.length(binaryString) newBinaryString = string("") if shiftLen >= len for i = 1 to len newBinaryString := newBinaryString + "0" else for i = 1 to shiftLen newBinaryString := newBinaryString + "0" newBinaryString := newBinaryString + str.substring(binaryString, 0, len - shiftLen) newBinaryString binaryAddition(string binaryA, string binaryB) => lenA = str.length(binaryA) lenB = str.length(binaryB) if lenA != lenB runtime.error("OTE HMAC SHA-256 LibError at binaryAddition(): Length of A (" + str.tostring(lenA) + ") is not equal to length of B (" + str.tostring(lenB) + "), input [A, B] is: [" + binaryA + ", " + binaryB + "]") "" else lastCharIndex = lenA - 1 prevRemainder = "0" newBinary = "" for i = lastCharIndex to 0 a = str.substring(binaryA, i, i + 1) b = str.substring(binaryB, i, i + 1) // Main Logic Table // | a | b | prevRemainder | result | remainder | // | 0 | 0 | 0 | 0 | 0 | // | 0 | 0 | 1 | 1 | 0 | // | 0 | 1 | 0 | 1 | 0 | // | 0 | 1 | 1 | 0 | 1 | // | 1 | 0 | 0 | 1 | 0 | // | 1 | 0 | 1 | 0 | 1 | // | 1 | 1 | 0 | 0 | 1 | // | 1 | 1 | 1 | 1 | 1 | result = a == "0" and b == "0" and prevRemainder == "0" ? "0" : a == "0" and b == "0" and prevRemainder == "1" ? "1" : a == "0" and b == "1" and prevRemainder == "0" ? "1" : a == "0" and b == "1" and prevRemainder == "1" ? "0" : a == "1" and b == "0" and prevRemainder == "0" ? "1" : a == "1" and b == "0" and prevRemainder == "1" ? "0" : a == "1" and b == "1" and prevRemainder == "0" ? "0" : a == "1" and b == "1" and prevRemainder == "1" ? "1" : "" remainder = a == "0" and b == "0" and prevRemainder == "0" ? "0" : a == "0" and b == "0" and prevRemainder == "1" ? "0" : a == "0" and b == "1" and prevRemainder == "0" ? "0" : a == "0" and b == "1" and prevRemainder == "1" ? "1" : a == "1" and b == "0" and prevRemainder == "0" ? "0" : a == "1" and b == "0" and prevRemainder == "1" ? "1" : a == "1" and b == "1" and prevRemainder == "0" ? "1" : a == "1" and b == "1" and prevRemainder == "1" ? "1" : "" if result == "" or remainder == "" runtime.error("OTE HMAC SHA-256 LibError at binaryAddition(): Logic table for result not found for a: " + a + ", b: " + b + ", prevRemainder: " + prevRemainder) newBinary := result + newBinary prevRemainder := remainder newBinary intToBinary(int _n, int len) => s = string("") n = int(_n) while n > 0 s := ((n % 2) == 0 ? "0" : "1") + s n := int(n / 2) if str.length(s) < len for i = 1 to len - str.length(s) s := "0" + s s strBinaryToInt(string sb) => len = str.length(sb) lastIndex = len - 1 int pow = 0 int sum = 0 for i = lastIndex to 0 b = str.substring(sb, i, i + 1) if b != "1" and b != "0" runtime.error("OTE HMAC SHA-256 LibError at strBinaryToInt(): Cannot calculate bit (" + str.tostring(b) + ") in input: " + str.tostring(sb)) sum := sum + (b == "1" ? int(math.pow(2, pow)) : 0) pow := pow + 1 sum charToAsciiBinary(string c) => c == " " ? "00100000" : c == "!" ? "00100001" : c == "\"" ? "00100010" : c == "#" ? "00100011" : c == "$" ? "00100100" : c == "%" ? "00100101" : c == "&" ? "00100110" : c == "'" ? "00100111" : c == "(" ? "00101000" : c == ")" ? "00101001" : c == "*" ? "00101010" : c == "+" ? "00101011" : c == "," ? "00101100" : c == "-" ? "00101101" : c == "." ? "00101110" : c == "/" ? "00101111" : c == "0" ? "00110000" : c == "1" ? "00110001" : c == "2" ? "00110010" : c == "3" ? "00110011" : c == "4" ? "00110100" : c == "5" ? "00110101" : c == "6" ? "00110110" : c == "7" ? "00110111" : c == "8" ? "00111000" : c == "9" ? "00111001" : c == ":" ? "00111010" : c == ";" ? "00111011" : c == "<" ? "00111100" : c == "=" ? "00111101" : c == ">" ? "00111110" : c == "?" ? "00111111" : c == "@" ? "01000000" : c == "A" ? "01000001" : c == "B" ? "01000010" : c == "C" ? "01000011" : c == "D" ? "01000100" : c == "E" ? "01000101" : c == "F" ? "01000110" : c == "G" ? "01000111" : c == "H" ? "01001000" : c == "I" ? "01001001" : c == "J" ? "01001010" : c == "K" ? "01001011" : c == "L" ? "01001100" : c == "M" ? "01001101" : c == "N" ? "01001110" : c == "O" ? "01001111" : c == "P" ? "01010000" : c == "Q" ? "01010001" : c == "R" ? "01010010" : c == "S" ? "01010011" : c == "T" ? "01010100" : c == "U" ? "01010101" : c == "V" ? "01010110" : c == "W" ? "01010111" : c == "X" ? "01011000" : c == "Y" ? "01011001" : c == "Z" ? "01011010" : c == "[" ? "01011011" : c == "\\" ? "01011100" : c == "]" ? "01011101" : c == "^" ? "01011110" : c == "_" ? "01011111" : c == "`" ? "01100000" : c == "a" ? "01100001" : c == "b" ? "01100010" : c == "c" ? "01100011" : c == "d" ? "01100100" : c == "e" ? "01100101" : c == "f" ? "01100110" : c == "g" ? "01100111" : c == "h" ? "01101000" : c == "i" ? "01101001" : c == "j" ? "01101010" : c == "k" ? "01101011" : c == "l" ? "01101100" : c == "m" ? "01101101" : c == "n" ? "01101110" : c == "o" ? "01101111" : c == "p" ? "01110000" : c == "q" ? "01110001" : c == "r" ? "01110010" : c == "s" ? "01110011" : c == "t" ? "01110100" : c == "u" ? "01110101" : c == "v" ? "01110110" : c == "w" ? "01110111" : c == "x" ? "01111000" : c == "y" ? "01111001" : c == "z" ? "01111010" : c == "{" ? "01111011" : c == "|" ? "01111100" : c == "}" ? "01111101" : c == "~" ? "01111110" : na strToBinary(string s) => sb = "" for i = 0 to str.length(s) - 1 c = str.substring(s, i, i + 1) b = charToAsciiBinary(c) if na(b) runtime.error("OTE HMAC SHA-256 LibError at strToBinary(): Character (" + str.tostring(c) + ") does not exist in pre-registered ASCII binary.") sb := sb + b sb binaryToHex(string b) => b == "0000" ? "0" : b == "0001" ? "1" : b == "0010" ? "2" : b == "0011" ? "3" : b == "0100" ? "4" : b == "0101" ? "5" : b == "0110" ? "6" : b == "0111" ? "7" : b == "1000" ? "8" : b == "1001" ? "9" : b == "1010" ? "a" : b == "1011" ? "b" : b == "1100" ? "c" : b == "1101" ? "d" : b == "1110" ? "e" : b == "1111" ? "f" : na strBinaryToStrHex(string s) => if str.length(s) % 4 != 0 runtime.error("OTE HMAC SHA-256 LibError at strBinaryToStrHex(): Binary string is not divisible by 4, input is: " + str.tostring(s)) sh = "" for i = 0 to str.length(s) - 1 by 4 b = str.substring(s, i, i + 4) h = binaryToHex(b) if na(h) runtime.error("OTE HMAC SHA-256 LibError at strBinaryToStrHex(): Binary sequence (" + str.tostring(b) + ") does not exist in pre-registered hex.") sh := sh + h sh // == SECTION (ID: 01) == UTILITY FUNCTION == END == // == SECTION (ID: 02) == EXPORTED FUNCTION == START == // @function HMAC SHA-256 // @param string msg String to be hashed // @returns [string, array] Return a hashed string in hex format and an array of 8 32 bits integer export hmac_sha256(string msg) => // == Initialize first hash value == h0 = "01101010000010011110011001100111" // 0x6a09e667 h1 = "10111011011001111010111010000101" // 0xbb67ae85 h2 = "00111100011011101111001101110010" // 0x3c6ef372 h3 = "10100101010011111111010100111010" // 0xa54ff53a h4 = "01010001000011100101001001111111" // 0x510e527f h5 = "10011011000001010110100010001100" // 0x9b05688c h6 = "00011111100000111101100110101011" // 0x1f83d9ab h7 = "01011011111000001100110100011001" // 0x5be0cd19 // == Initialize array of round constants == arr_k = array.new_string() array.push(arr_k, "01000010100010100010111110011000") // 0x428a2f98 array.push(arr_k, "01110001001101110100010010010001") // 0x71374491 array.push(arr_k, "10110101110000001111101111001111") // 0xb5c0fbcf array.push(arr_k, "11101001101101011101101110100101") // 0xe9b5dba5 array.push(arr_k, "00111001010101101100001001011011") // 0x3956c25b array.push(arr_k, "01011001111100010001000111110001") // 0x59f111f1 array.push(arr_k, "10010010001111111000001010100100") // 0x923f82a4 array.push(arr_k, "10101011000111000101111011010101") // 0xab1c5ed5 array.push(arr_k, "11011000000001111010101010011000") // 0xd807aa98 array.push(arr_k, "00010010100000110101101100000001") // 0x12835b01 array.push(arr_k, "00100100001100011000010110111110") // 0x243185be array.push(arr_k, "01010101000011000111110111000011") // 0x550c7dc3 array.push(arr_k, "01110010101111100101110101110100") // 0x72be5d74 array.push(arr_k, "10000000110111101011000111111110") // 0x80deb1fe array.push(arr_k, "10011011110111000000011010100111") // 0x9bdc06a7 array.push(arr_k, "11000001100110111111000101110100") // 0xc19bf174 array.push(arr_k, "11100100100110110110100111000001") // 0xe49b69c1 array.push(arr_k, "11101111101111100100011110000110") // 0xefbe4786 array.push(arr_k, "00001111110000011001110111000110") // 0x0fc19dc6 array.push(arr_k, "00100100000011001010000111001100") // 0x240ca1cc array.push(arr_k, "00101101111010010010110001101111") // 0x2de92c6f array.push(arr_k, "01001010011101001000010010101010") // 0x4a7484aa array.push(arr_k, "01011100101100001010100111011100") // 0x5cb0a9dc array.push(arr_k, "01110110111110011000100011011010") // 0x76f988da array.push(arr_k, "10011000001111100101000101010010") // 0x983e5152 array.push(arr_k, "10101000001100011100011001101101") // 0xa831c66d array.push(arr_k, "10110000000000110010011111001000") // 0xb00327c8 array.push(arr_k, "10111111010110010111111111000111") // 0xbf597fc7 array.push(arr_k, "11000110111000000000101111110011") // 0xc6e00bf3 array.push(arr_k, "11010101101001111001000101000111") // 0xd5a79147 array.push(arr_k, "00000110110010100110001101010001") // 0x06ca6351 array.push(arr_k, "00010100001010010010100101100111") // 0x14292967 array.push(arr_k, "00100111101101110000101010000101") // 0x27b70a85 array.push(arr_k, "00101110000110110010000100111000") // 0x2e1b2138 array.push(arr_k, "01001101001011000110110111111100") // 0x4d2c6dfc array.push(arr_k, "01010011001110000000110100010011") // 0x53380d13 array.push(arr_k, "01100101000010100111001101010100") // 0x650a7354 array.push(arr_k, "01110110011010100000101010111011") // 0x766a0abb array.push(arr_k, "10000001110000101100100100101110") // 0x81c2c92e array.push(arr_k, "10010010011100100010110010000101") // 0x92722c85 array.push(arr_k, "10100010101111111110100010100001") // 0xa2bfe8a1 array.push(arr_k, "10101000000110100110011001001011") // 0xa81a664b array.push(arr_k, "11000010010010111000101101110000") // 0xc24b8b70 array.push(arr_k, "11000111011011000101000110100011") // 0xc76c51a3 array.push(arr_k, "11010001100100101110100000011001") // 0xd192e819 array.push(arr_k, "11010110100110010000011000100100") // 0xd6990624 array.push(arr_k, "11110100000011100011010110000101") // 0xf40e3585 array.push(arr_k, "00010000011010101010000001110000") // 0x106aa070 array.push(arr_k, "00011001101001001100000100010110") // 0x19a4c116 array.push(arr_k, "00011110001101110110110000001000") // 0x1e376c08 array.push(arr_k, "00100111010010000111011101001100") // 0x2748774c array.push(arr_k, "00110100101100001011110010110101") // 0x34b0bcb5 array.push(arr_k, "00111001000111000000110010110011") // 0x391c0cb3 array.push(arr_k, "01001110110110001010101001001010") // 0x4ed8aa4a array.push(arr_k, "01011011100111001100101001001111") // 0x5b9cca4f array.push(arr_k, "01101000001011100110111111110011") // 0x682e6ff3 array.push(arr_k, "01110100100011111000001011101110") // 0x748f82ee array.push(arr_k, "01111000101001010110001101101111") // 0x78a5636f array.push(arr_k, "10000100110010000111100000010100") // 0x84c87814 array.push(arr_k, "10001100110001110000001000001000") // 0x8cc70208 array.push(arr_k, "10010000101111101111111111111010") // 0x90befffa array.push(arr_k, "10100100010100000110110011101011") // 0xa4506ceb array.push(arr_k, "10111110111110011010001111110111") // 0xbef9a3f7 array.push(arr_k, "11000110011100010111100011110010") // 0xc67178f2 // == Pre-processing == preProcessedMsg = strToBinary(msg) + "1" // append 1 bit to the end of original message L = str.length(preProcessedMsg) - 1 // obtain the original message bit count // append 0 bit to bits string, until the length is the multiple of 512 bits - 64 bits while ((str.length(preProcessedMsg) % 512)) != 448 preProcessedMsg := preProcessedMsg + "0" preProcessedMsg := preProcessedMsg + intToBinary(L, 64) // append 64 bits of L // break message into 512-bit chunks arr_mainChunk = array.new_string() for i = 0 to str.length(preProcessedMsg) - 1 by 512 array.push(arr_mainChunk, str.substring(preProcessedMsg, i, i + 512)) // == Processing hash == // for each chunk in main chunk // break each chunk into smaller 32 bits chunk (sub-chunk) // add additional 32 bits chunks of 0 into sub-chunk list // for each additional chunk in sub-chunk // perform 1st hash computation // create working variable // for each chunk in sub-chunk // perform compression algorithm // modify initial hash value to be used as next iteration working variable for n = 0 to array.size(arr_mainChunk) - 1 mainChunk = array.get(arr_mainChunk, n) // get current main chunk // break main chunk into sub-chunk arr_subChunk = array.new_string() for i = 0 to 511 by 32 array.push(arr_subChunk, str.substring(mainChunk, i, i + 32)) // add additional sub-chunk for i = 1 to 48 array.push(arr_subChunk, "00000000000000000000000000000000") // perform hash computation for each additional sub-chunk for i = 16 to 63 prev15SubChunk = array.get(arr_subChunk, i - 15) // store for faster access s0_0 = binaryRotateRight(prev15SubChunk, 7) // calculate logic gate later with s1 so we only do 1 loop s0_1 = binaryRotateRight(prev15SubChunk, 18) // calculate logic gate later with s1 so we only do 1 loop s0_2 = binaryShiftRight(prev15SubChunk, 3) // calculate logic gate later with s1 so we only do 1 loop prev02SubChunk = array.get(arr_subChunk, i - 2) // store for faster access s1_0 = binaryRotateRight(prev02SubChunk, 17) // calculate logic gate later with s0 so we only do 1 loop s1_1 = binaryRotateRight(prev02SubChunk, 19) // calculate logic gate later with s0 so we only do 1 loop s1_2 = binaryShiftRight(prev02SubChunk, 10) // calculate logic gate later with s0 so we only do 1 loop s0 = "" s1 = "" for j = 31 to 0 s0 := XORGate(XORGate(str.substring(s0_0, j, j + 1), str.substring(s0_1, j, j + 1)), str.substring(s0_2, j, j + 1)) + s0 s1 := XORGate(XORGate(str.substring(s1_0, j, j + 1), str.substring(s1_1, j, j + 1)), str.substring(s1_2, j, j + 1)) + s1 array.set(arr_subChunk, i, binaryAddition(binaryAddition(binaryAddition(array.get(arr_subChunk, i - 16), s0), array.get(arr_subChunk, i - 7)), s1)) // create working variable a = h0 b = h1 c = h2 d = h3 e = h4 f = h5 g = h6 h = h7 // perform compression computation for each sub-chunk for i = 0 to 63 S1_0 = binaryRotateRight(e, 6) // calculate logic gate later with ch, S0, and maj so we only do 1 loop S1_1 = binaryRotateRight(e, 11) // calculate logic gate later with ch, S0, and maj so we only do 1 loop S1_2 = binaryRotateRight(e, 25) // calculate logic gate later with ch, S0, and maj so we only do 1 loop S0_0 = binaryRotateRight(a, 2) // calculate logic gate later with ch, S1, and maj so we only do 1 loop S0_1 = binaryRotateRight(a, 13) // calculate logic gate later with ch, S1, and maj so we only do 1 loop S0_2 = binaryRotateRight(a, 22) // calculate logic gate later with ch, S1, and maj so we only do 1 loop S1 = "" ch = "" S0 = "" maj = "" for j = 0 to 31 S1 := S1 + XORGate(XORGate(str.substring(S1_0, j, j + 1), str.substring(S1_1, j, j + 1)), str.substring(S1_2, j, j + 1)) ch := ch + XORGate(ANDGate(str.substring(e, j, j + 1), str.substring(f, j, j + 1)), ANDGate(NOTGate(str.substring(e, j, j + 1)), str.substring(g, j, j + 1))) S0 := S0 + XORGate(XORGate(str.substring(S0_0, j, j + 1), str.substring(S0_1, j, j + 1)), str.substring(S0_2, j, j + 1)) maj := maj + XORGate(XORGate(ANDGate(str.substring(a, j, j + 1), str.substring(b, j, j + 1)), ANDGate(str.substring(a, j, j + 1), str.substring(c, j, j + 1))), ANDGate(str.substring(b, j, j + 1), str.substring(c, j, j + 1))) temp1 = binaryAddition(binaryAddition(binaryAddition(binaryAddition(h, S1), ch), array.get(arr_k, i)), array.get(arr_subChunk, i)) temp2 = binaryAddition(S0, maj) h := g g := f f := e e := binaryAddition(d, temp1) d := c c := b b := a a := binaryAddition(temp1, temp2) // modify initial hash value to be used as next iteration working variable h0 := binaryAddition(h0, a) h1 := binaryAddition(h1, b) h2 := binaryAddition(h2, c) h3 := binaryAddition(h3, d) h4 := binaryAddition(h4, e) h5 := binaryAddition(h5, f) h6 := binaryAddition(h6, g) h7 := binaryAddition(h7, h) // == Concatenating hash == // convert h0 - h7 from binary string to hex decimal, then concatenate hashMsg = strBinaryToStrHex(h0) + strBinaryToStrHex(h1) + strBinaryToStrHex(h2) + strBinaryToStrHex(h3) + strBinaryToStrHex(h4) + strBinaryToStrHex(h5) + strBinaryToStrHex(h6) + strBinaryToStrHex(h7) // convert h0 - h7 from binary string to int, then append to array arr_h = array.new_int() array.push(arr_h, strBinaryToInt(h0)) array.push(arr_h, strBinaryToInt(h1)) array.push(arr_h, strBinaryToInt(h2)) array.push(arr_h, strBinaryToInt(h3)) array.push(arr_h, strBinaryToInt(h4)) array.push(arr_h, strBinaryToInt(h5)) array.push(arr_h, strBinaryToInt(h6)) array.push(arr_h, strBinaryToInt(h7)) [hashMsg, arr_h] // == SECTION (ID: 02) == EXPORTED FUNCTION == END == // // == SECTION (ID: 03) == USAGE EXAMPLE == START == // // function to split hash with space // splitWithSpace(s, len) => // string new_s = "" // for i = 0 to str.length(s) - 1 // c = str.substring(s, i, i + 1) // new_s := new_s + (i % len == 0 and i != 0 ? " " : "") + c // new_s // // input // inputSecretKey = input.string("6a09e667bb67ae853c6ef372a54ff53a510e527f9b05688c1f83d9ab5be0cd19") // // using time as a salt // inputMsg = inputSecretKey// + str.tostring(time) // // prepare variable // hashMsg = "" // arr_h = array.new_int() // if barstate.islast // [_hashMsg, _arr_h] = hmac_sha256(inputMsg) // hashMsg := _hashMsg // arr_h := array.copy(_arr_h) // // output to table // var logTable = table.new(position=position.bottom_right, columns=2, rows=10, bgcolor=color.white, border_width=1, border_color=color.silver) // if barstate.islast // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=0, text="input") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=1, text="hash") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=2, text="h0") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=3, text="h1") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=4, text="h2") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=5, text="h3") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=6, text="h4") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=7, text="h5") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=8, text="h6") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=0, row=9, text="h7") // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=0, text=inputMsg) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=1, text=splitWithSpace(hashMsg, 8)) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=2, text=str.tostring( array.get(arr_h, 0) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=3, text=str.tostring( array.get(arr_h, 1) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=4, text=str.tostring( array.get(arr_h, 2) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=5, text=str.tostring( array.get(arr_h, 3) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=6, text=str.tostring( array.get(arr_h, 4) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=7, text=str.tostring( array.get(arr_h, 5) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=8, text=str.tostring( array.get(arr_h, 6) )) // table.cell(table_id=logTable, text_size=size.auto, text_halign=text.align_left, column=1, row=9, text=str.tostring( array.get(arr_h, 7) )) // // output to plot // plot(title="h0", series=barstate.islast ? array.get(arr_h, 0) : na, color=color.new(#f23645, 0), style=plot.style_circles) // plot(title="h1", series=barstate.islast ? array.get(arr_h, 1) : na, color=color.new(#ff9800, 0), style=plot.style_circles) // plot(title="h2", series=barstate.islast ? array.get(arr_h, 2) : na, color=color.new(#ffeb3b, 0), style=plot.style_circles) // plot(title="h3", series=barstate.islast ? array.get(arr_h, 3) : na, color=color.new(#4caf50, 0), style=plot.style_circles) // plot(title="h4", series=barstate.islast ? array.get(arr_h, 4) : na, color=color.new(#089981, 0), style=plot.style_circles) // plot(title="h5", series=barstate.islast ? array.get(arr_h, 5) : na, color=color.new(#00bcd4, 0), style=plot.style_circles) // plot(title="h6", series=barstate.islast ? array.get(arr_h, 6) : na, color=color.new(#2962ff, 0), style=plot.style_circles) // plot(title="h7", series=barstate.islast ? array.get(arr_h, 7) : na, color=color.new(#673ab7, 0), style=plot.style_circles) // // by using plot, you can call the variable for the alert message body // // and on your server/client/whatever side sequentially convert each value // // to hex and concatenate to form the hash string. // // // // below is full scenario example assuming input hash (unsalted) is: // // 6a09e667bb67ae853c6ef372a54ff53a510e527f9b05688c1f83d9ab5be0cd19 // // // // Example Alert Message Body: // // {"key": [ {{plot("h0")}}, {{plot("h1")}}, {{plot("h2")}}, {{plot("h3")}}, {{plot("h4")}}, {{plot("h5")}}, {{plot("h6")}}, {{plot("h7")}} ]} // // Which lead to JSON message: // // {"key": [ 2076858297, 2282410289, 2130471305, 1905036923, 413802551, 286061022, 208206988, 4013625551 ]} // // Example in receiver's side (using javascript): // // let tvAlert = JSON.parse(jsonMessageReceivedFromTradingView) // // let hash = tvAlert.key[0].toString(16) + tvAlert.key[1].toString(16) + tvAlert.key[2].toString(16) + tvAlert.key[3].toString(16) + tvAlert.key[4].toString(16) + tvAlert.key[5].toString(16) + tvAlert.key[6].toString(16) + tvAlert.key[7].toString(16) // // == SECTION (ID: 03) == USAGE EXAMPLE == END == // == SECTION (ID: 04) == REFERENCES == START == // - https://medium.com/@domspaulo/python-implementation-of-sha-256-from-scratch-924f660c5d57 // - Original Pseudocode for SHA-256 // Retrieved from: https://en.wikipedia.org/wiki/SHA-2#Pseudocode // On: 2021-12-04, 00:04 GMT+7 // // // // Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 232 // Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63 // Note 3: The compression function uses 8 working variables, a through h // Note 4: Big-endian convention is used when expressing the constants in this pseudocode, // and when parsing message block data from bytes to words, for example, // the first word of the input message "abc" after padding is 0x61626380 // // Initialize hash values: // (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): // h0 := 0x6a09e667 // h1 := 0xbb67ae85 // h2 := 0x3c6ef372 // h3 := 0xa54ff53a // h4 := 0x510e527f // h5 := 0x9b05688c // h6 := 0x1f83d9ab // h7 := 0x5be0cd19 // // Initialize array of round constants: // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): // k[0..63] := // 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, // 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, // 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, // 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, // 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, // 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, // 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, // 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 // // Pre-processing (Padding): // begin with the original message of length L bits // append a single '1' bit // append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K + 64 is a multiple of 512 // append L as a 64-bit big-endian integer, making the total post-processed length a multiple of 512 bits // // Process the message in successive 512-bit chunks: // break message into 512-bit chunks // for each chunk // create a 64-entry message schedule array w[0..63] of 32-bit words // (The initial values in w[0..63] don't matter, so many implementations zero them here) // copy chunk into first 16 words w[0..15] of the message schedule array // // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array: // for i from 16 to 63 // s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3) // s1 := (w[i- 2] rightrotate 17) xor (w[i- 2] rightrotate 19) xor (w[i- 2] rightshift 10) // w[i] := w[i-16] + s0 + w[i-7] + s1 // // Initialize working variables to current hash value: // a := h0 // b := h1 // c := h2 // d := h3 // e := h4 // f := h5 // g := h6 // h := h7 // // Compression function main loop: // for i from 0 to 63 // S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25) // ch := (e and f) xor ((not e) and g) // temp1 := h + S1 + ch + k[i] + w[i] // S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22) // maj := (a and b) xor (a and c) xor (b and c) // temp2 := S0 + maj // // h := g // g := f // f := e // e := d + temp1 // d := c // c := b // b := a // a := temp1 + temp2 // // Add the compressed chunk to the current hash value: // h0 := h0 + a // h1 := h1 + b // h2 := h2 + c // h3 := h3 + d // h4 := h4 + e // h5 := h5 + f // h6 := h6 + g // h7 := h7 + h // // Produce the final hash value (big-endian): // digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7 // == SECTION (ID: 04) == REFERENCES == END ==
MultiUsage_Library
https://www.tradingview.com/script/bwDeNkg3-MultiUsage-Library/
MoonKoder
https://www.tradingview.com/u/MoonKoder/
8
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TitinhoAmorim //@version=5 library("MultiUse_Library", overlay = true) // @BULLISH ENGULFING CANDLE DETECTOR // Checks if Bullish Engulfing Candle Found // { // @INPUT PARAMETERS // bool DetectEngulf (TRUE if wants to detect engulfing candles) // (FALSE if doesn't to detect engulfing candles) // bool EngulfLastWick (TRUE if current close must engulf last wick) // (FALSE if current close mustn't engulf last wick) // @OUTPUT PARAMETERS // isBullishEC (TRUE if Bullish Engulfing Candle is detected // (FALSE if Bullish Engulfing Candle isn't detected) export BullEC(bool DetectEngulf, bool EngulfLastWick) => NormalBullEC = (open[1] > close[1]) and (close[0] > open[0]) and (close[0] > open[1]) WickBullEC = (open[1] > close[1]) and (close[0] > open[0]) and (close[0] > high[1]) isBullishEC = (DetectEngulf == true) ? (EngulfLastWick == false) ? WickBullEC : NormalBullEC : na // } // @BEARISH ENGULFING CANDLE DETECTOR // Checks if Bearish Engulfing Candle Found // { // @INPUT PARAMETERS // bool DetectEngulf (TRUE if wants to detect engulfing candles) // (FALSE if doesn't to detect engulfing candles) // bool EngulfLastWick (TRUE if current close must engulf last wick) // (FALSE if current close mustn't engulf last wick) // @OUTPUT PARAMETERS // isBearishEC (TRUE if Bearish Engulfing Candle is detected // (FALSE if Bearish Engulfing Candle isn't detected) export BearEC(bool DetectEngulf, bool EngulfLastWick) => NormalBearEC = (open[1] < close[1]) and (close[0] < open[0]) and (close[0] < open[1]) WickBearEC = (open[1] < close[1]) and (close[0] < open[0]) and (close[0] < low[1]) isBearishEC = (DetectEngulf == true) ? (EngulfLastWick == false) ? WickBearEC : NormalBearEC : na // }
LibraryCheckNthBar
https://www.tradingview.com/script/01u8W9QY-LibraryCheckNthBar/
LonesomeTheBlue
https://www.tradingview.com/u/LonesomeTheBlue/
118
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © LonesomeTheBlue //@version=5 // @description TODO: add library description here library("LibraryCheckNthBar") // @function this function can be used if current bar is in last Nth bar // @param UTC is UTC of the chart // @param prd is the length of last Nth bar // @returns true if the current bar is in N bar export canwestart(float UTC, int prd) => // get GMT time int timenow_ = timenow + math.round(UTC * 3600000) int time_ = time + math.round(UTC * 3600000) // calculate D/H/M/S for the bar which we are on and time now int daynow_ = math.floor((timenow_ + 86400000 * 3) / 86400000) % 7 int day_ = math.floor((time_ + 86400000 * 3) / 86400000) % 7 int hournow_ = math.floor(timenow_ / 3600000) % 24 int hour_ = math.floor(time_ / 3600000) % 24 int minutenow_ = math.floor(timenow_ / 60000) % 60 int minute_ = math.floor(time_ / 60000) % 60 int secondnow_ = math.floor(timenow_ / 60000) % 60 int second_ = math.floor(time_ / 60000) % 60 int hmstime_ = hour_ * 3600000 + minute_ * 60000 + second_ * 1000 int hmstimenow_ = hournow_ * 3600000 + minutenow_ * 60000 + secondnow_ * 1000 var int starttime = na if na(starttime) or time_ < nz(starttime) // bar_index > prd and if timeframe.isdaily starttime := timenow_ - timeframe.multiplier * prd * 86400000 // 1 day = 86400000 starttime //if day_ == daynow_ // session day // diff = time_ - time_[prd] // starttime := timenow_ - diff //if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend // diff = time_[1] - time_[prd + 1] + (daynow_ - day_[1]) * 86400000 // starttime := timenow_ - diff if timeframe.isintraday if day_ == daynow_ and day_[1] == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] <= hmstimenow_ // in session diff = time_[1] - time_[prd + 1] + math.round(UTC * 3600000) starttime := timenow_ - diff starttime if day_ != daynow_ and day_[1] == daynow_ and hmstime_ < hmstimenow_ and hmstime_[1] <= hmstimenow_ // in same day and after session diff = time_[1] - time_[prd + 1] + hmstimenow_ - hmstime_[1] + math.round(UTC * 3600000) starttime := timenow_ - diff starttime if day_ == daynow_ and day_[1] + 1 == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // in week (not first day) and before session diff = time_[1] - time_[prd + 1] + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff starttime if day_ == daynow_ and day_[1] > daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // the day after weekend before session diff = time_[1] - time_[prd + 1] + 2 * 86400000 + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff starttime if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend diff = time_[1] - time_[prd + 1] + (daynow_ - day_[1] - 1) * 86400000 + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff starttime if timeframe.isweekly starttime := timenow_ - timeframe.multiplier * prd * 604800000 // 1 week = 604800000ms starttime if timeframe.ismonthly starttime := timenow_ - timeframe.multiplier * prd * 2629743000 // 1 month = 2629743000ms starttime ret_ = not na(starttime) and time >= starttime ret_
GenericTA
https://www.tradingview.com/script/Gz4OuW86-GenericTA/
BillionaireLau
https://www.tradingview.com/u/BillionaireLau/
13
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © BillionaireLau //@version=5 // @description TODO: add library description here library("GenericTA") tf_cv(fx, range_reso) => returning_function = request.security(syminfo.tickerid, range_reso, fx) returning_function //Section 1: Functions //List of indicators //ema_cross //f_highest //f_lowest //macd //src = input(title="Source", defval=close) fast_length = input(title="Fast Length", defval=12) slow_length = input(title="Slow Length", defval=26) signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9) sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"]) //sar(float start, float increment, float maximum) //start = input(0.01,group="SAR settings") increment = input(0.01,group="SAR settings") maximum = input(0.4, 'Max Value',group="SAR settings") //supertrend(float Factor, simple int Pd) //Factor=input(3,title="[ST] Factor", minval=1,maxval = 100, type=input.float) Pd=input(7, title="[ST] PD", minval=1,maxval = 100) //Section 2: Bunch of copy-and-paste trading-conditions // Type A -- restricting trading range // Trading zone (above/below) (within/outside) a percentage-based volatility band around an EMA //Type B -- Lines crossing over / under triggers // MACDs (could multiple uses) //Typc C -- regression // Logarithmic regression // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export fun(float x) => //TODO : add function body and return value here x export f_highest(float _source, int _length) => float _return = _source if _length >= 1 and _length <= 5000 for _i = 0 to math.max(0, _length-1) _return := math.max(_source[_i], _return) _return export f_lowest(float _source, int _length) => float _return = _source if _length >= 1 and _length <= 5000 for _i = 0 to math.max(0, _length-1) _return := math.min(_source[_i], _return) _return //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// src_macd = input(title="Source", defval=close) fast_length_macd = input(title="Fast Length", defval=12) slow_length_macs = input(title="Slow Length", defval=26) signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9) sma_source_macd = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"]) export macd(float _source, int _lenFast, int _lenSlow, int _lenSingal, string _type_of_ma) => fast_ma = _type_of_ma == "SMA" ? ta.sma(_source, _lenFast) : ta.ema(_source, _lenFast) slow_ma = _type_of_ma == "SMA" ? ta.sma(_source, _lenSlow) : ta.ema(_source, _lenSlow) macd = fast_ma - slow_ma signal = _type_of_ma == "SMA" ? ta.sma(macd, _lenSingal) : ta.ema(macd, _lenSingal) hist = macd - signal [macd, signal,hist] /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// start_sar = input(0.01,group="SAR settings") increment_sar = input(0.01,group="SAR settings") maximum_sar = input(0.4, 'Max Value',group="SAR settings") // @function you need to add the following inputs function to your script also:start = input(0.01,group="SAR settings") increment = input(0.01,group="SAR settings") maximum = input(0.4, 'Max Value',group="SAR settings") // @param // @ export sar(float start, float increment, float maximum) => var bool uptrend = na var float EP = na var float SAR = na var float AF = start var float nextBarSAR = na if bar_index > 0 firstTrendBar = false SAR := nextBarSAR if bar_index == 1 float prevSAR = na float prevEP = na lowPrev = low[1] highPrev = high[1] closeCur = close closePrev = close[1] if closeCur > closePrev uptrend := true EP := high prevSAR := lowPrev prevEP := high prevEP else uptrend := false EP := low prevSAR := highPrev prevEP := low prevEP firstTrendBar := true SAR := prevSAR + start * (prevEP - prevSAR) SAR if uptrend if SAR > low firstTrendBar := true uptrend := false SAR := math.max(EP, high) EP := low AF := start AF else if SAR < high firstTrendBar := true uptrend := true SAR := math.min(EP, low) EP := high AF := start AF if not firstTrendBar if uptrend if high > EP EP := high AF := math.min(AF + increment, maximum) AF else if low < EP EP := low AF := math.min(AF + increment, maximum) AF if uptrend SAR := math.min(SAR, low[1]) if bar_index > 1 SAR := math.min(SAR, low[2]) SAR else SAR := math.max(SAR, high[1]) if bar_index > 1 SAR := math.max(SAR, high[2]) SAR nextBarSAR := SAR + AF * (EP - SAR) nextBarSAR [SAR, uptrend] // @function you need to add the following inputs function to your script also://Factor=input(3,title="[ST] Factor", minval=1,maxval = 100, type=input.float) Pd=input(7, title="[ST] PD", minval=1,maxval = 100) // @param // @ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Factor_st =input.int(3,title="[ST] Factor", minval=1,maxval = 100) Pd_st =input.int(7, title="[ST] PD", minval=1,maxval = 100) export supertrend(float Factor, simple int Pd) => Up=hl2-(Factor*ta.atr(Pd)) Dn=hl2+(Factor*ta.atr(Pd)) TrendUp = 0.0 TrendUp := close[1]>TrendUp[1] ? math.max(Up,TrendUp[1]) : Up TrendDown = 0.0 TrendDown := close[1]<TrendDown[1]? math.min(Dn,TrendDown[1]) : Dn Trend = 0.0 Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1) Tsl = Trend==1? TrendUp: TrendDown S_Buy = Trend == 1 ? 1 : 0 S_Sell = Trend != 1 ? 1 : 0 [Trend, Tsl] //Type C: Regression /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// export log_regress(int[] _t_axis, float[] _x_axis, float _exp) => int _size_y = array.size(_x_axis) int _size_x = array.size(_t_axis) float[] _y_array = array.new_float(_size_y) float[] _x_array = array.new_float(_size_x) for _i = 0 to _size_y - 1 array.set(_y_array, _i, math.log(array.get(_x_axis, _i))) array.set(_x_array, _i, math.log(array.get(_t_axis, _i))) float _sum_x = array.sum(_x_array) float _sum_y = array.sum(_y_array) float _sum_xy = 0.0 float _sum_x2 = 0.0 float _sum_y2 = 0.0 if _size_y == _size_x for _i = 0 to _size_y - 1 float _x_i = nz(array.get(_x_array, _i)) float _y_i = nz(array.get(_y_array, _i)) _sum_xy := _sum_xy + _x_i * _y_i _sum_x2 := _sum_x2 + math.pow(_x_i, _exp) _sum_y2 := _sum_y2 + math.pow(_y_i, _exp) _sum_y2 float _a = (_sum_y * _sum_x2 - _sum_x * _sum_xy) / (_size_x * _sum_x2 - math.pow(_sum_x, _exp)) float _b = (_size_x * _sum_xy - _sum_x * _sum_y) / (_size_x * _sum_x2 - math.pow(_sum_x, _exp)) float[] _f = array.new_float() for _i = 0 to _size_y - 1 float _vector = _a + _b * array.get(_x_array, _i) array.push(_f, _vector) _slope = 1.2*(array.get(_f, 0) - array.get(_f, _size_y - 1)) / (array.get(_x_array, 0) - array.get(_x_array, _size_x - 1)) _y_mean = array.avg(_y_array) float _SS_res = 0.0 float _SS_tot = 0.0 for _i = 0 to _size_y - 1 float _f_i = array.get(_f, _i) float _y_i = array.get(_y_array, _i) _SS_res := _SS_res + math.pow(_f_i - _y_i, _exp) _SS_tot := _SS_tot + math.pow(_y_mean - _y_i, _exp) _SS_tot _r_sq = 1 - _SS_res / _SS_tot float _sq_err_sum = 0 for _i = 0 to _size_y - 1 _sq_err_sum += math.pow(array.get(_f, _i) - array.get(_y_array, _i), _exp) _dev = math.sqrt(_sq_err_sum / _size_y) [_f, _slope, _r_sq, _dev]
CandleEvaluation
https://www.tradingview.com/script/vhJwIsNM-CandleEvaluation/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
128
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © SimpleCryptoLife //@version=5 // @description Functions to evaluate bullish and bearish, engulfing, and outsized candles. They are different from the built-in indicators from TradingView in that // these functions don't evaluate classical patterns composed of multiple candles, and they reflect my own understanding of what is "bullish" and bearish", "engulfing", and "outsized". library("CandleEvaluation", overlay=true) var string errorTextLibraryName = "SimpleCryptoLife/CandleEvaluation" // ------------------------------------------// // BULLISH & BEARISH CANDLES // // ------------------------------------------// // @function isBullishBearishCandle() determines if the current candle is bullish or bearish according to the length of the wicks and the open and close. // @param int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar. // @returns Two values, true or false, for whether it's a bullish or bearish candle respectively. export isBullishBearishCandle(int _barsBack = 0) => var string _errorTextFunctionName = "isBullishBearishCandle()" if _barsBack < 0 runtime.error("Parameter _barsBack is less than zero. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _i = _barsBack // It's just shorter, for readability float _higherOfOpenClose = open[_i] > close[_i] ? open[_i] : open[_i] <= close[_i] ? close[_i] : na, float _lowerOfOpenClose = open[_i] <= close[_i] ? open[_i] : open[_i] > close[_i] ? close[_i] : na float _upperWick = high[_i] - _higherOfOpenClose, float _lowerWick = _lowerOfOpenClose - low[_i] float _body = math.abs(open[_i]-close[_i]) bool _isUpperWickBigger = _upperWick > (_body + _lowerWick) // If the upper wick is larger than the body + lower wick, it’s a bearish candle. bool _isLowerWickBigger = _lowerWick > (_body + _upperWick) // If the lower wick is larger than the body + upper wick, it’s a bullish candle. bool _isGreenCandle = close[_i] >= open[_i] bool _isRedCandle = close[_i] < open[_i] bool _noWickBigger = not _isUpperWickBigger and not _isLowerWickBigger bool _isBullishCandle = _isLowerWickBigger or (_noWickBigger and _isGreenCandle) // If neither wick is larger, go by colour. bool _isBearishCandle = _isUpperWickBigger or (_noWickBigger and _isRedCandle) [_isBullishCandle,_isBearishCandle] // DEMO [isBullishCandle,isBearishCandle] = isBullishBearishCandle() bool inputColourBullishAndBearishCandles = input.bool(defval=true, title="Colour Bullish and Bearish Candles", group="isBullishBearishCandle()") color demoBarColor = not inputColourBullishAndBearishCandles ? color.gray : isBullishCandle ? color.green : isBearishCandle ? color.red : color.yellow barcolor(demoBarColor) alertcondition(isBullishCandle,".isBullishCandle", "A bullish candle has printed. Library: SimpleCryptoLife/CandleEvaluation") alertcondition(isBearishCandle,".isBearishCandle", "A bearish candle has printed. Library: SimpleCryptoLife/CandleEvaluation") // ------------------------------------------// // TRIPLE BULL/BEAR CANDLES // // ------------------------------------------// // @function isTripleBull() Tells you whether a candle is a "Triple Bull" - that is, one which is bullish in three ways: // It closes higher than it opens; it closes higher than the body of the previous candle; and the High is above the High of the previous candle. // @param int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar. // @returns True or false. export isTripleBull(int _barsBack = 0) => var string _errorTextFunctionName = "isTripleBull()" if _barsBack < 0 runtime.error("Parameter _barsBack is less than zero. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _i0 = _barsBack, int _i1 = _barsBack+1 // Get the equivalents of [0] and [1] bool _1 = close[_i0] > open[_i0] // This is an up candle bool _2 = (close[_i0] > open[_i1]) and (close[_i0] > close[_i1]) // We closed higher than the body of the previous candle bool _3 = high[_i0] > high[_i1] // The High is higher than the previous High bool _result = _1 and _2 and _3 // @function isTripleBear() Tells you whether a candle is a "Triple Bear" - that is, one which is bearish in three ways: // It closes lower than it opens; it closes lower than the body of the previous candle; and the Low is below the Low of the previous candle. // @param int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar. // @returns True or false. export isTripleBear(int _barsBack = 0) => var string _errorTextFunctionName = "isTripleBear()" if _barsBack < 0 runtime.error("Parameter _barsBack is less than zero. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _i0 = _barsBack, int _i1 = _barsBack+1 // Get the equivalents of [0] and [1] bool _1 = close[_i0] < open[_i0] // This is a down candle bool _2 = (close[_i0] < open[_i1]) and (close[_i0] < close[_i1]) // We closed lower than the body of the previous candle bool _3 = low[_i0] < low[_i1] // The Low is lower than the previous Low bool _result = _1 and _2 and _3 // DEMO isTripleBullCandle = isTripleBull() isTripleBearCandle = isTripleBear() bool inputShowTripleBull = input.bool(defval=true, title="Show Triple Bull Candles", group="isTripleBull()") tripleBullPlot = isTripleBullCandle and inputShowTripleBull ? low : na plotshape(tripleBullPlot, title="Triple Bullish candle", style=shape.labelup, text="T+", textcolor=color.white, location=location.absolute, color=color.blue, size=size.small) bool inputShowTripleBear = input.bool(defval=true, title="Show Triple Bear Candles", group="isTripleBear()") tripleBearPlot = isTripleBearCandle and inputShowTripleBear ? high : na plotshape(tripleBearPlot, title="Triple Bearish candle", style=shape.labeldown, text="T-", textcolor=color.white, location=location.absolute, color=color.orange, size=size.small) alertcondition(isTripleBullCandle,".isTripleBullCandle", "A Triple Bullish candle has printed. Library: SimpleCryptoLife/CandleEvaluation") alertcondition(isTripleBearCandle,".isTripleBearCandle", "A Triple Bearish candle has printed. Library: SimpleCryptoLife/CandleEvaluation") // ------------------------------------------// // BIG BODY CANDLE // // ------------------------------------------// // @function isBigBodyCandle() Tells you if the current candle has a larger than average body size. // @param int _length - The length of the sma to calculate the average // @param float _percent - The percentage of the average that the candle body has to be to count as "big". E.g. 100 means it has to be just larger than the average, 200 means it has to be twice as large. // @returns True or false export isBigBody(int _length = 20, float _percent = 100) => var string _errorTextFunctionName = "isBigBody()" if _length < 2 or _length > 200 runtime.error("Parameter _length is too small or too large. Default is 20. Min: 2. Max: 200. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _percent < 10 or _percent > 1000 runtime.error("Parameter _percent is too small or too large. Default is 100. Min: 10. Max: 1000. [Error002" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _numBars = bar_index < _length ? bar_index + 1 : _length // If we haven't had that many bars yet just use what we have float _bodySize = math.abs(open-close) // Get the size of the candle body float _bodyPercent = (_bodySize/open)/100 // TODO: Turn it into a percentage of its absolute price, otherwise for crypto assets which move in price fast, it ceases to make sense. _simpleMovingAverage = ta.sma(_bodyPercent,_numBars) bool isBig = _bodyPercent > (_simpleMovingAverage * (_percent/100)) isBig // DEMO float inputBigBodyPercent = input.float(defval=100, minval=10, maxval=1000, step=10, title="% of Average That Counts as Big", group="isBigBodyCandle()") isBigBodyCandle = isBigBody(_percent = inputBigBodyPercent) bool inputShowBigCandles = input.bool(defval=true, title="Colour Big Candles") color bigBarColour = isBigBodyCandle and inputShowBigCandles ? color.new(color.yellow,80) : na bgcolor(bigBarColour) alertcondition(isBigBodyCandle,".isBigBodyCandle", "A big bodied candle has printed. Library: SimpleCryptoLife/CandleEvaluation") // ==================================== // ENGULFING CANDLES // ==================================== // @function isBullishEngulfing() Tells you if the current candle is a bullish engulfing candle. // @param int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar. // @param int _atrFraction The denominator for the ATR fraction, which is the small amount by which the open can be different from the previous close. // @returns True or false // Clean logic doesn't work because the open is sometimes not EXACTLY the same as the close. So we need to add a tiny ATR % filter. export isBullishEngulfing(int _barsBack = 0, int _atrFraction = 20) => var string _errorTextFunctionName = "isBullishEngulfing()" if _barsBack < 0 runtime.error("Parameter _barsBack is less than zero. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _atrFraction < 5 or _atrFraction > 100 runtime.error("Parameter _atrFraction is too big or too small. Default value is 20. Min: 5. Max: 100. [Error002" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _index0 = _barsBack, int _index1 = _barsBack+1 // Get the equivalents of [0] and [1] bool _1 = close[_index1] < open[_index1] // Previous candle was a down candle bool _2 = (close[_index0] > open[_index1]) and (close[_index0] > close[_index1]) // We closed above the previous candle body bool _3 = open[_index0] < (close[_index1] + (ta.atr(14)/_atrFraction)) // We opened not more than a tiny amount above the previous close bool _result = _1 and _2 and _3 // @function isBearishEngulfing() Tells you if the current candle is a bearish engulfing candle. // @param int _barsBack How many bars back is the candle you want to evaluate. By default this is 0, i.e., the current bar. // @param int _atrFraction The denominator for the ATR fraction, which is the small amount by which the open can be different from the previous close. // @returns True or false export isBearishEngulfing(int _barsBack = 0, int _atrFraction = 20) => var string _errorTextFunctionName = "isBearishEngulfing()" if _barsBack < 0 runtime.error("Parameter _barsBack is less than zero. [Error001" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _atrFraction < 5 or _atrFraction > 100 runtime.error("Parameter _atrFraction is too big or too small. Default value is 20. Min: 5. Max: 100. [Error002" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") int _index0 = _barsBack, int _index1 = _barsBack+1 // Get the equivalents of [0] and [1] bool _1 = close[_index1] > open[_index1] // Previous candle was an up candle bool _2 = (close[_index0] < open[_index1]) and (close[_index0] < close[_index1]) // We closed below the previous candle body bool _3 = open[_index0] > (close[_index1] - (ta.atr(14)/_atrFraction)) // We opened not more than a tiny amount below the previous close bool _result = _1 and _2 and _3 // DEMO int barsBack = 0 bool isBullishEngulfingCandle = isBullishEngulfing(barsBack) bool isBearishEngulfingCandle = isBearishEngulfing(barsBack) float atr14 = ta.atr(14) inputShowBullishEngulfing = input.bool(defval=true, title="Show Bullish Engulfing Candles", group="isBullishEngulfing\(\)") inputShowBearishEngulfing = input.bool(defval=true, title="Show Bearish Engulfing Candles", group="isBearishEngulfing\(\)") var int offset = 0 // offset := 0 - barsBack // This would display the labels in the right places regardless of how many bars back you go. isBullishEngulfingPlot = isBullishEngulfingCandle and inputShowBullishEngulfing ? low - atr14/2 : na plotshape(isBullishEngulfingPlot, title="Bullish engulfing candle", style=shape.labelup, text="BE", textcolor=color.white, location=location.absolute, color=color.green, size=size.small, offset=offset) isBearishEngulfingPlot = isBearishEngulfingCandle and inputShowBearishEngulfing ? high + atr14/2 : na plotshape(isBearishEngulfingPlot, title="Bearish engulfing candle", style=shape.labeldown, text="BE", textcolor=color.white, location=location.absolute, color=color.red, size=size.small, offset=offset) alertcondition(isBullishEngulfingCandle,".isBullishEngulfingCandle", "A Bullish Engulfing candle has printed. Library: SimpleCryptoLife/CandleEvaluation") alertcondition(isBearishEngulfingCandle,".isBearishEngulfingCandle", "A Bearish Engulfing candle has printed. Library: SimpleCryptoLife/CandleEvaluation") // ==================================== // AVERAGE WICK SIZE // ==================================== // @function f_wickSize() - A function to get the average size of upper and lower wicks over time. This can be more useful than the standard ATR in evaluating the spikiness of an asset or in calculating stops. // @param float _open - The Open of the candle. Defaults to the Open on the chart timeframe. Included for HTF compatibility. // @param float _high - The High of the candle. Defaults to the High on the chart timeframe. Included for HTF compatibility. // @param float _low - The Low of the candle. Defaults to the Low on the chart timeframe. Included for HTF compatibility. // @param float _close - The Close of the candle. Defaults to the Close on the chart timeframe. Included for HTF compatibility. // @param float _ohlc4 - The OHLC4 of the candle. Defaults to the OHLC4 on the chart timeframe. Included for HTF compatibility. // @param int _length - The length for the RMA of wicks. // @param int _length2 - The length for the EMA of OHLC4. // @returns Two floats for the absolute values of the average upper and lower candle wicks. f_rma(_source, _length) => // SMA function from the Pine docs. We can't use the built-in functions because we want to change the length dynamically. _sum_sma = 0.0 int _lengthAdjusted = _length < 1 ? 1 : _length for i = 0 to _lengthAdjusted - 1 _sum_sma := _sum_sma + _source[i] / _lengthAdjusted // RMA function from the Pine docs _alpha = 1/_lengthAdjusted _sum = 0.0 _sum := na(_sum[1]) ? _sum_sma : _alpha * _source + (1 - _alpha) * nz(_sum[1]) f_ema(_source,_length) => _alpha = (2 / (_length + 1)), var float _ema = 0.0, _ema := na(_ema[1]) ? _source : _alpha * _source + (1 - _alpha) * nz(_ema[1]) // Function taken from the Pine docs for ema(). export f_wickSize(float _open=open, float _high=high, float _low=low, float _close=close, float _ohlc4=ohlc4, int _length=8, int _length2=8) => // Get the current upper and lower wick size float _higherOC = math.max(_open,_close) float _lowerOC = math.min(_open,_close) float _upperWick = _high - _higherOC float _lowerWick = _lowerOC - _low // Get the wick size as a fraction of OHLC4. // We use fractions because if an asset moves a large absolute amount, e.g., crypt on a weekly chart, the absolute values are not really relevant any more. // Fractions also aren't a perfect solution, but they're much better. The averages ensure the values catch up reasonably quickly. float _upperWickFraction = (_upperWick/_ohlc4) float _lowerWickFraction = (_lowerWick/_ohlc4) // Get the average of the fraction int _lengthAdjusted = bar_index < 1 ? 1 : bar_index <_length ? bar_index : _length float _averageUpperWickFraction = f_rma(_upperWickFraction, _lengthAdjusted) float _averageLowerWickFraction = f_rma(_lowerWickFraction, _lengthAdjusted) // Get the average of OHLC4 int _lengthAdjusted2 = bar_index < 1 ? 1 : bar_index <_length2 ? bar_index : _length2 float _averageOHLC4 = f_ema(_ohlc4, _lengthAdjusted2) // Convert the fraction back to an absolute value float _averageUpperWick = _averageUpperWickFraction * _averageOHLC4 float _averageLowerWick = _averageLowerWickFraction * _averageOHLC4 [_averageUpperWick, _averageLowerWick] // DEMO in_wickRMALength = input.int(title="Wick RMA Length", group="f_wickSize()", defval=21, minval=5, step=5, maxval=200) in_OHLC4Length = input.int(title="OHLC4 RMA Length", defval=8, minval=2, maxval=200) in_showWickSize = input.bool(title="Show Average Wick Size", defval=true) [averageUpperWick, averageLowerWick] = f_wickSize(_open=open, _high=high, _low=low, _close=close, _ohlc4=ohlc4, _length=in_wickRMALength, _length2=in_OHLC4Length) plot(in_showWickSize ? high+averageUpperWick : na, title="averageUpperWick", linewidth=1, color=color.green) plot(in_showWickSize ? low-averageLowerWick : na, title="averageLowerWick", linewidth=1, color=color.red) // END
assert
https://www.tradingview.com/script/Ddd3hMq8-assert/
GeoffHammond
https://www.tradingview.com/u/GeoffHammond/
21
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Geoff Hammond //@version=5 // @description Production ready assertions and auto-reporting for unit testing pine scripts library("assert") // ▄▀█ █▀ █▀ █▀▀ █▀█ ▀█▀ █ █▀█ █▄ █ █ █ █▄▄ █▀█ ▄▀█ █▀█ █▄█ // █▀█ ▄█ ▄█ ██▄ █▀▄ █ █ █▄█ █ ▀█ █▄▄ █ █▄█ █▀▄ █▀█ █▀▄ █ // @TODO: compact report. // ██╗ ██╗███████╗██╗ ██████╗ ███████╗██████╗ ██████╗ // ██║ ██║██╔════╝██║ ██╔══██╗██╔════╝██╔══██╗██╔════╝ // ███████║█████╗ ██║ ██████╔╝█████╗ ██████╔╝╚█████╗ // ██╔══██║██╔══╝ ██║ ██╔═══╝ ██╔══╝ ██╔══██╗ ╚═══██╗ // ██║ ██║███████╗███████╗██║ ███████╗██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ // COPY THESE HELPERS INTO YOUR SCRIPT // __ASSERTS = assert.init() // // unittest_your_script(string[] case) => // case = assert.new_case(case, 'Test Case') // // // Your case assertions go here // assert.equal(1, 1, case, 'For example, one does equal one!') // // unittest(bool verbose = false) => // var bool result = na // if assert.once() // unittest_your_script(__ASSERTS) // result := assert.report(__ASSERTS, verbose) // result // // result = unittest() // QUICK REFERENCE // case = assert.init() // // new_case(case, 'Asserts for floats and ints') // assert.equal(a, b, case, 'a == b') // assert.not_equal(a, b, case, 'a != b') // assert.nan(a, case, 'a == na') // assert.not_nan(a, case, 'a != na') // assert.is_in(a, b, case, 'a in b[]') // assert.is_not_in(a, b, case, 'a not in b[]') // assert.array_equal(a, b, case, 'a[] == b[]') // // new_case(case, 'Asserts for ints only') // assert.int_in(a, b, case, 'a in b[]') // assert.int_not_in(a, b, case, 'a not in b[]') // assert.int_array_equal(a, b, case, 'a[] == b[]') // // new_case(case, 'Asserts for bools only') // assert.is_true(a, case, 'a == true') // assert.is_false(a, case, 'a == false') // assert.bool_equal(a, b, case, 'a == b') // assert.bool_not_equal(a, b, case, 'a != b') // assert.bool_nan(a, case, 'a == na') // assert.bool_not_nan(a, case, 'a != na') // assert.bool_array_equal(a, b, case, 'a[] == b[]') // // new_case(case, 'Asserts for strings only') // assert.str_equal(a, b, case, 'a == b') // assert.str_not_equal(a, b, case, 'a != b') // assert.str_nan(a, case, 'a == na') // assert.str_not_nan(a, case, 'a != na') // assert.str_in(a, b, case, 'a in b[]') // assert.str_not_in(a, b, case, 'a not in b[]') // assert.str_array_equal(a, b, case, 'a[] == b[]') // // new_case(case, 'Asserts for colors only') // assert.color_equal(#000000, #000000, case, 'black == black') // assert.color_not_equal(#000000, #FFFFFF, case, 'black != white') // // assert.report(case) // ██████╗ ██╗ █████╗ ██████╗ █████╗ ██╗ ██████╗ // ██╔════╝ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██╔════╝ // ██║ ██╗ ██║ ██║ ██║ ██████╦╝ ███████║ ██║ ╚█████╗ // ██║ ╚██╗ ██║ ██║ ██║ ██╔══██╗ ██╔══██║ ██║ ╚═══██╗ // ╚██████╔╝ ███████╗ ╚█████╔╝ ██████╦╝ ██║ ██║ ███████╗ ██████╔╝ // ╚═════╝ ╚══════╝ ╚════╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ var FORMAT_COLOR_STRING = '[r:{0} g:{1} b:{2}]' var FORMAT_ARRAY_STRING = '{0} (+{1})' var FORMAT_SINGLE = '[ {0} ] {1}: "{2}" {3}.' var FORMAT_DOUBLE = '[ {0} ] {1}: "{2}" {3} "{4}".' var FORMAT_REPORT_HEADER = 'Unit Test {0} ({1}/{2}):' var EQUAL = 'is equal to' var NOT_EQUAL = 'is not equal to' var GREATER = 'is greater than' var LESSER = 'is lesser than' var GREATER_OR_EQUAL = 'is greater than or equal to' var LESSER_OR_EQUAL = 'is lesser than or equal to' var TRUE = 'is true' var NOT_TRUE = 'is not true' var FALSE = 'is false' var NOT_FALSE = 'is not false' var NAN = 'is NaN' var NOT_NAN = 'is not NaN' var IN = 'is in' var NOT_IN = 'is not in' var DEFAULT_CASE = 'Unit Test' // ███████╗ ██╗ ██╗ ███╗ ██╗ █████╗ ████████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ // ██╔════╝ ██║ ██║ ████╗ ██║ ██╔══██╗ ╚══██╔══╝ ██║ ██╔══██╗ ████╗ ██║ ██╔════╝ // █████╗ ██║ ██║ ██╔██╗██║ ██║ ╚═╝ ██║ ██║ ██║ ██║ ██╔██╗██║ ╚█████╗ // ██╔══╝ ██║ ██║ ██║╚████║ ██║ ██╗ ██║ ██║ ██║ ██║ ██║╚████║ ╚═══██╗ // ██║ ╚██████╔╝ ██║ ╚███║ ╚█████╔╝ ██║ ██║ ╚█████╔╝ ██║ ╚███║ ██████╔╝ // ╚═╝ ╚═════╝ ╚═╝ ╚══╝ ╚════╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚══╝ ╚═════╝ array_get(arr, offset) => if offset < array.size(arr) array.get(arr, offset) else na array_trim_end(arr, size) => if array.size(arr) > size for i = array.size(arr) - 1 to size array.remove(arr, i) tuple_push(tuples, a, b) => array.push(tuples, a), array.push(tuples, b) tuple_pop(tuples) => b = array.pop(tuples), a = array.pop(tuples), [a, b] tuple_set(tuples, offset, a, b) => array.set(tuples, offset * 2, a), array.set(tuples, (offset * 2) + 1, b) tuple_get(tuples, offset) => [array_get(tuples, offset * 2), array_get(tuples, (offset * 2) + 1)] tuple_size(tuples) => math.floor(array.size(tuples) / 2) tuple_last(tuples) => tuple_get(tuples, tuple_size(tuples) - 1) tuple_remove(tuples, offset) => array.remove(tuples, offset * 2), array.remove(tuples, offset * 2) tuple_trim(tuples, size) => array_trim_end(tuples, math.round(size * 2)) str_increment(string value) => str.tostring(math.round(str.tonumber(value)) + 1) str_decrement(string value) => str.tostring(math.round(str.tonumber(value)) - 1) color_tostring(color _color) => str.format(FORMAT_COLOR_STRING, color.r(_color), color.g(_color), color.b(_color)) array_tostring(id, int limit = 20) => array.size(id) > limit ? str.format(FORMAT_ARRAY_STRING, str.tostring(array.slice(id, 0, limit)), array.size(id) - limit) : str.tostring(id) // █████╗ ██████╗ ██████╗ ███████╗ ██████╗ ████████╗ // ██╔══██╗ ██╔════╝ ██╔════╝ ██╔════╝ ██╔══██╗ ╚══██╔══╝ // ███████║ ╚█████╗ ╚█████╗ █████╗ ██████╔╝ ██║ // ██╔══██║ ╚═══██╗ ╚═══██╗ ██╔══╝ ██╔══██╗ ██║ // ██║ ██║ ██████╔╝ ██████╔╝ ███████╗ ██║ ██║ ██║ // ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ append_single(string[] case, string name, a, bool result, string pass, string fail) => group = array.get(case, 0), count = str_increment(array.get(case, 1)), array.set(case, 1, count) msg = str.format(FORMAT_SINGLE, group, str.length(name) ? name : '#' + count, a, result ? pass : fail) tuple_push(case, msg, result ? '.' : 'x') result append_double(string[] case, string name, a, b, bool result, string pass, string fail) => group = array.get(case, 0), count = str_increment(array.get(case, 1)), array.set(case, 1, count) msg = str.format(FORMAT_DOUBLE, group, str.length(name) ? name : '#' + count, a, result ? pass : fail, b) tuple_push(case, msg, result ? '.' : 'x') result assert_equal(a, b, string[] case, string name = '') => append_double(case, name, a, b, a == b, EQUAL, NOT_EQUAL) assert_not_equal(a, b, string[] case, string name = '') => append_double(case, name, a, b, a != b, NOT_EQUAL, EQUAL) assert_greater(a, b, string[] case, string name = '') => append_double(case, name, a, b, a > b, GREATER, LESSER) assert_lesser(a, b, string[] case, string name = '') => append_double(case, name, a, b, a < b, LESSER, GREATER) assert_greater_or_equal(a, b, string[] case, string name = '') => append_double(case, name, a, b, a >= b, GREATER_OR_EQUAL, LESSER_OR_EQUAL) assert_lesser_or_equal(a, b, string[] case, string name = '') => append_double(case, name, a, b, a <= b, LESSER_OR_EQUAL, GREATER_OR_EQUAL) assert_true(a, string[] case, string name = '') => append_single(case, name, str.tostring(a), a == true, TRUE, NOT_TRUE) assert_false(a, string[] case, string name = '') => append_single(case, name, str.tostring(a), a == false, FALSE, NOT_FALSE) assert_nan(a, string[] case, string name = '') => append_single(case, name, a, na(a), NAN, NOT_NAN) assert_not_nan(a, string[] case, string name = '') => append_single(case, name, a, not na(a), NOT_NAN, NAN) assert_in(a, b, string[] case, string name = '') => append_double(case, name, a, array_tostring(b), array.includes(b, a), IN, NOT_IN) assert_not_in(a, b, string[] case, string name = '') => append_double(case, name, a, array_tostring(b), not array.includes(b, a), NOT_IN, IN) assert_array_equal(a, b, string[] case, string name = '') => size = array.size(a) equal = size == array.size(b) if equal and size for i = 0 to size - 1 if array.get(a, i) != array.get(b, i) equal := false break append_double(case, name, array_tostring(a, 10), array_tostring(b, 10), equal, EQUAL, NOT_EQUAL) process_results(string[] case, bool clear = true) => results = array.size(case) > 2 ? array.slice(case, 2, array.size(case)) : array.new_string() total = tuple_size(case) - 1 pass = array.new_string() fail = array.new_string() if total for i = 0 to total - 1 [msg, result] = tuple_get(results, i) if result == '.' tuple_push(pass, msg, result) else if result == 'x' tuple_push(fail, msg, result) pass_count = tuple_size(pass) fail_count = tuple_size(fail) if clear array.clear(case) tuple_push(case, DEFAULT_CASE, '0') [total, pass_count, fail_count, pass, fail] // ██╗ ██╗ ██████╗ ██████╗ █████╗ ██████╗ ██╗ ██╗ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚██╗ ██╔╝ // ██║ ██║ ██████╦╝ ██████╔╝ ███████║ ██████╔╝ ╚████╔╝ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██║ ██╔══██╗ ╚██╔╝ // ███████╗ ██║ ██████╦╝ ██║ ██║ ██║ ██║ ██║ ██║ ██║ // ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ // @function Restrict execution to only happen once. Usage: if assert.once()\n happens_once() // @returns bool, true on first execution within scope, false subsequently export once() => varip pending = true if pending pending := false true else false // @function Restrict execution to happen a set number of times. Usage: if assert.only(5)\n happens_five_times() // @param repeat int, the number of times to return true // @returns bool, true for the set number of times within scope, false subsequently export only(int repeat = 1) => var done = 0 if done < repeat done += 1 true else false // @function Initialises the asserts array // @returns string[], tuple based array to contain all unit test results and current case details (__ASSERTS) export init() => array.from(DEFAULT_CASE, '0') // @function Numeric assert equal. Usage: assert.equal(1, 1, case, 'one == one') // @param a float, numeric value "a" to compare equal to "b" // @param b float, numeric value "b" to compare equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export equal(float a, float b, string[] case, string name = '') => assert_equal(a, b, case, name) // @function Numeric assert not equal. Usage: assert.not_equal(1, 2, case, 'one != two') // @param a float, numeric value "a" to compare not equal "b" // @param b float, numeric value "b" to compare not equal "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export not_equal(float a, float b, string[] case, string name = '') => assert_not_equal(a, b, case, name) // @function Numeric assert greater than. Usage: assert.greater(2, 1, case, 'two > one') // @param a float, numeric value "a" to compare greater than "b" // @param b float, numeric value "b" to compare lesser than "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export greater(float a, float b, string[] case, string name = '') => assert_greater(a, b, case, name) // @function Numeric assert lesser than. Usage: assert.not_equal(1, 2, case, 'one < two') // @param a float, numeric value "a" to compare lesser than "b" // @param b float, numeric value "b" to compare greater than "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export lesser(float a, float b, string[] case, string name = '') => assert_lesser(a, b, case, name) // @function Numeric assert greater than or equal to. Usage: assert.greater(2, 1, case, 'two >= one') // @param a float, numeric value "a" to compare greater or equal to "b" // @param b float, numeric value "b" to compare lesser than or equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export greater_or_equal(float a, float b, string[] case, string name = '') => assert_greater_or_equal(a, b, case, name) // @function Numeric assert lesser than or equal to. Usage: assert.not_equal(1, 2, case, 'one <= two') // @param a float, numeric value "a" to compare lesser than or equal to "b" // @param b float, numeric value "b" to compare greater than or equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export lesser_or_equal(float a, float b, string[] case, string name = '') => assert_lesser_or_equal(a, b, case, name) // @function Numeric assert is NaN. Usage: assert.nan(float(na), case, 'number is NaN') // @param a float, numeric value "a" to check is NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export nan(float a, string[] case, string name = '') => assert_nan(a, case, name) // @function Numeric assert is not NaN. Usage: assert.not_nan(1, case, 'number is not NaN') // @param a float, numeric value "a" to check is not NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export not_nan(float a, string[] case, string name = '') => assert_not_nan(a, case, name) // @function Numeric assert value in float array. Usage: assert.is_in(1, array.from(1.0), case, '1 is in [1.0]') // @param a float, numeric value "a" to check is in array "b" // @param b float[], array "b" to check contains "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export is_in(float a, float[] b, string[] case, string name = '') => assert_in(a, b, case, name) // @function Numeric assert value not in float array. Usage: assert.is_not_in(2, array.from(1.0), case, '2 is not in [1.0]') // @param a float, numeric value "a" to check is not in array "b" // @param b float[], array "b" to check does not contain "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export is_not_in(float a, float[] b, string[] case, string name = '') => assert_not_in(a, b, case, name) // @function Float assert arrays are equal. Usage: assert.array_equal(array.from(1.0), array.from(1.0), case, '[1.0] == [1.0]') // @param a float[], array "a" to check is identical to array "b" // @param b float[], array "b" to check is identical to array "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export array_equal(float[] a, float[] b, string[] case, string name = '') => assert_array_equal(a, b, case, name) // @function Integer assert value in integer array. Usage: assert.int_in(1, array.from(1), case, '1 is in [1]') // @param a int, value "a" to check is in array "b" // @param b int[], array "b" to check contains "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export int_in(int a, int[] b, string[] case, string name = '') => assert_in(a, b, case, name) // @function Integer assert value not in integer array. Usage: assert.int_not_in(2, array.from(1), case, '2 is not in [1]') // @param a int, value "a" to check is not in array "b" // @param b int[], array "b" to check does not contain "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export int_not_in(int a, int[] b, string[] case, string name = '') => assert_not_in(a, b, case, name) // @function Integer assert arrays are equal. Usage: assert.int_array_equal(array.from(1), array.from(1), case, '[1] == [1]') // @param a int[], array "a" to check is identical to array "b" // @param b int[], array "b" to check is identical to array "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export int_array_equal(int[] a, int[] b, string[] case, string name = '') => assert_array_equal(a, b, case, name) // @function Boolean assert is true. Usage: assert.is_true(true, case, 'is true') // @param a bool, value "a" to check is true // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export is_true(bool a, string[] case, string name = '') => assert_true(a, case, name) // @function Boolean assert is false. Usage: assert.is_false(false, case, 'is false') // @param a bool, value "a" to check is false // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export is_false(bool a, string[] case, string name = '') => assert_false(a, case, name) // @function Boolean assert equal. Usage: assert.bool_equal(true, true, case, 'true == true') // @param a bool, value "a" to compare equal to "b" // @param b bool, value "b" to compare equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export bool_equal(bool a, bool b, string[] case, string name = '') => assert_equal(a, b, case, name) // @function Boolean assert not equal. Usage: assert.bool_not_equal(true, false, case, 'true != false') // @param a bool, value "a" to compare not equal "b" // @param b bool, value "b" to compare not equal "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export bool_not_equal(bool a, bool b, string[] case, string name = '') => assert_not_equal(a, b, case, name) // @function Boolean assert is NaN. Usage: assert.bool_nan(bool(na), case, 'bool is NaN') // @param a bool, value "a" to check is NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export bool_nan(bool a, string[] case, string name = '') => assert_nan(a, case, name) // @function Boolean assert is not NaN. Usage: assert.bool_not_nan(true, case, 'bool is not NaN') // @param a bool, value "a" to check is not NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export bool_not_nan(bool a, string[] case, string name = '') => assert_not_nan(a, case, name) // @function Boolean assert arrays are equal. Usage: assert.bool_array_equal(array.from(true), array.from(true), case, '[true] == [true]') // @param a bool[], array "a" to check is identical to array "b" // @param b bool[], array "b" to check is identical to array "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export bool_array_equal(bool[] a, bool[] b, string[] case, string name = '') => assert_array_equal(a, b, case, name) // @function String assert equal. Usage: assert.str_equal('hi', 'hi', case, '"hi" == "hi"') // @param a string, value "a" to compare equal to "b" // @param b string, value "b" to compare equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_equal(string a, string b, string[] case, string name = '') => assert_equal(a, b, case, name) // @function String assert not equal. Usage: assert.str_not_equal('hi', 'bye', case, '"hi" != "bye"') // @param a string, value "a" to compare not equal "b" // @param b string, value "b" to compare not equal "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_not_equal(string a, string b, string[] case, string name = '') => assert_not_equal(a, b, case, name) // @function String assert is NaN. Usage: assert.str_nan(string(na), case, 'string is NaN') // @param a string, value "a" to check is NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_nan(string a, string[] case, string name = '') => assert_nan(a, case, name) // @function String assert is not NaN. Usage: assert.str_not_nan('hi', case', 'string is not NaN') // @param a string, value "a" to check is not NaN // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_not_nan(string a, string[] case, string name = '') => assert_not_nan(a, case, name) // @function String assert value in string array. Usage: assert.str_in('hi', array.from('hi'), case, '"hi" in ["hi"]') // @param a string, value "a" to check is in array "b" // @param b string[], array "b" to check contains "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_in(string a, string[] b, string[] case, string name = '') => assert_in(a, b, case, name) // @function String assert value not in string array. Usage: assert.str_in('hi', array.from('bye'), case, '"hi" in ["bye"]') // @param a string, value "a" to check is not in array "b" // @param b string[], array "b" to check does not contain "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_not_in(string a, string[] b, string[] case, string name = '') => assert_not_in(a, b, case, name) // @function String assert arrays are equal. Usage: assert.str_array_equal(array.from('hi'), array.from('hi'), case, '["hi"] == ["hi"]') // @param a string[], array "a" to check is identical to array "b" // @param b string[], array "b" to check is identical to array "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export str_array_equal(string[] a, string[] b, string[] case, string name = '') => assert_array_equal(a, b, case, name) // @function Color assert equal. Usage: assert.color_equal(#000000, #000000, case, 'black == black') // @param a color, value "a" to compare equal to "b" // @param b color, value "b" to compare equal to "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export color_equal(color a, color b, string[] case, string name = '') => assert_equal(color_tostring(a), color_tostring(b), case, name) // @function Color assert not equal. Usage: assert.str_not_equal(#000000, #FFFFFF, case, 'black != white') // @param a color, value "a" to compare not equal "b" // @param b color, value "b" to compare not equal "a" // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the current unit test name, if undefined the test index of the current case is used // @returns bool, true if the assertion passes, false otherwise export color_not_equal(color a, color b, string[] case, string name = '') => assert_not_equal(color_tostring(a), color_tostring(b), case, name) // @function Assign a new test case name, for the next set of unit tests. Usage: assert.new_case(case, 'My tests') // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param name string, the case name for the next suite of tests export new_case(string[] case, string name) => if tuple_size(case) == 0 runtime.error('[Assert:new_case] Unable to assign new case to empty __ASSERTS array!') array.set(case, 0, name) array.set(case, 1, '0') // @function Clear all stored unit tests from all cases. Usage: assert.clear(case) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) export clear(string[] case) => tuple_trim(case, 1), array.set(case, 1, '0') // @function Revert the previous unit test. Usage: [string msg, bool result] = assert.revert(case) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @returns [msg string, result bool], tuple containing the msg and result of the reverted test export revert(string[] case) => if tuple_size(case) == 1 runtime.error(str.format('[Assert:revert] Unable to revert empty test case "{0}"!', array.get(case, 0))) count = str_decrement(array.get(case, 1)) array.set(case, 1, count == '-1' ? '0' : count) [msg, result] = tuple_pop(case) [msg, result == '.'] // @function Check if the last unit test has passed. Usage: bool success = assert.passed(case) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param revert bool, optionally revert the test // @returns bool, true only if the test passed export passed(string[] case, bool revert = false) => if tuple_size(case) == 1 runtime.error(str.format('[Assert:passed] No tests found for test case "{0}"!', array.get(case, 0))) [msg, result] = tuple_last(case) if revert revert(case) result == '.' // @function Check if the last unit test has failed. Usage: bool failure = assert.failed(case) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param revert bool, optionally revert the test // @returns bool, true only if the test failed export failed(string[] case, bool revert = false) => if tuple_size(case) == 1 runtime.error(str.format('[Assert:failed] No tests found for test case "{0}"!', array.get(case, 0))) [msg, result] = tuple_last(case) if revert revert(case) result == 'x' // @function Report the outcome of unit tests that fail. Usage: bool passed = assert.report(case) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) // @param verbose bool, toggle displaying the full report that includes the outcome of all tests // @param position string, the position for the report (global position vars) // @returns bool, true only if all tests passed export report(string[] case, bool verbose = false, string position = na) => [total, pass_count, fail_count, pass, fail] = process_results(case) text_size = verbose ? size.small : size.large if verbose and pass_count > 0 // array.concat(fail, pass) // Bug? This reverses the order! for i = 0 to array.size(pass) - 1 array.push(fail, array.get(pass, i)) if (verbose and pass_count > 0) or fail_count > 0 var tbl = table.new(na(position) ? position.top_center : position, 2, (verbose ? total : fail_count) + 1, #000000, fail_count ? #FF0000 : #00FF00, 1) title = str.format(FORMAT_REPORT_HEADER, verbose ? 'Results' : 'Failures', verbose ? pass_count : fail_count, total) table.cell(tbl, 0, 0, title, text_color=fail_count ? #FF0000 : #00FF00, text_halign=text.align_left, text_size=size.huge) for i = 0 to tuple_size(fail) - 1 [msg, result] = tuple_get(fail, i) table.cell(tbl, 0, i + 1, '- ' + msg, text_color=#FFFFFF, text_halign=text.align_left, text_size=text_size) table.cell(tbl, 1, i + 1, result == '.' ? '✔️' : '❌', text_halign=text.align_left, text_size=text_size) fail_count > 0 // ██╗ ██╗ ███╗ ██╗ ██╗ ████████╗ ████████╗ ███████╗ ██████╗ ████████╗ ██████╗ // ██║ ██║ ████╗ ██║ ██║ ╚══██╔══╝ ╚══██╔══╝ ██╔════╝ ██╔════╝ ╚══██╔══╝ ██╔════╝ // ██║ ██║ ██╔██╗██║ ██║ ██║ ██║ █████╗ ╚█████╗ ██║ ╚█████╗ // ██║ ██║ ██║╚████║ ██║ ██║ ██║ ██╔══╝ ╚═══██╗ ██║ ╚═══██╗ // ╚██████╔╝ ██║ ╚███║ ██║ ██║ ██║ ███████╗ ██████╔╝ ██║ ██████╔╝ // ╚═════╝ ╚═╝ ╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ // @function Assert module unit tests, for inclusion in parent script test suite. Usage: assert.unittest_assert(__ASSERTS) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) export unittest_assert(string[] case) => [start_total, start_pass_count, start_fail_count, start_pass, start_fail] = process_results(case, clear = false) new_case(case, 'Assert:once') assert_true(once(), case) assert_true(once(), case) for i = 1 to 3 trigger = once() if i == 1 assert_true(trigger, case) else assert_false(trigger, case) new_case(case, 'Assert:only') assert_true(only(), case) assert_false(only(0), case) // but why? assert_true(only(1), case) assert_true(only(2), case) for i = 1 to 3 trigger = only(2) if i <= 2 assert_true(trigger, case) else assert_false(trigger, case) new_case(case, 'Assert:str_increment') assert_equal(str_increment('-1'), '0', case) assert_equal(str_increment('0'), '1', case) assert_equal(str_increment('1'), '2', case) assert_equal(str_increment('10'), '11', case) new_case(case, 'Assert:str_decrement') assert_equal(str_decrement('11'), '10', case) assert_equal(str_decrement('2'), '1', case) assert_equal(str_decrement('1'), '0', case) assert_equal(str_decrement('0'), '-1', case) new_case(case, 'Assert:color_tostring') assert_equal(color_tostring(#000000), str.format(FORMAT_COLOR_STRING, 0, 0, 0), case) assert_equal(color_tostring(#FFFFFF), str.format(FORMAT_COLOR_STRING, 255, 255, 255), case) new_case(case, 'Assert:array_tostring') assert_equal(array_tostring(array.new_float()), '[]', case) assert_equal(array_tostring(array.from(1, 2, 3)), '[1, 2, 3]', case) assert_equal(array_tostring(array.from('a', 'b', 'c')), '[a, b, c]', case) assert_equal(array_tostring(array.from(1, 2, 3, 4, 5), 3), str.format(FORMAT_ARRAY_STRING, array.from(1, 2, 3), 2), case) new_case(case, 'Assert:init') test_case = init() assert_array_equal(test_case, array.from('Unit Test', '0'), case, 'init') new_case(case, 'Assert:new_case') new_case(test_case, 'New Case') assert_equal(1, 1, test_case, 'pass') new_case1 = str.format(FORMAT_DOUBLE, 'New Case', 'pass', 1, EQUAL, 1) assert_array_equal(test_case, array.from('New Case', '1', new_case1, '.'), case, 'new_case #1') assert_true(passed(test_case), case, 'passed') new_case(test_case, 'Next Case') assert_equal(1, 2, test_case, 'fail') assert_true(failed(test_case), case, 'failed') next_case1 = str.format(FORMAT_DOUBLE, 'Next Case', 'fail', 1, NOT_EQUAL, 2) assert_array_equal(test_case, array.from('Next Case', '1', new_case1, '.', next_case1, 'x'), case, 'new_case #2') new_case(case, 'Assert:revert') revert(test_case) assert_array_equal(test_case, array.from('Next Case', '0', new_case1, '.'), case, 'revert #1') revert(test_case) assert_array_equal(test_case, array.from('Next Case', '0'), case, 'revert #2') assert_equal(1, 1, test_case) assert_equal(1, 2, test_case) new_case(case, 'Assert:names') num_case1 = str.format(FORMAT_DOUBLE, 'Next Case', '#1', 1, EQUAL, 1) num_case2 = str.format(FORMAT_DOUBLE, 'Next Case', '#2', 1, NOT_EQUAL, 2) assert_array_equal(test_case, array.from('Next Case', '2', num_case1, '.', num_case2, 'x'), case, 'auto-numeric') new_case(case, 'Assert:clear') clear(test_case) assert_array_equal(test_case, array.from('Next Case', '0'), case, 'reset') assert_equal(1, 1, test_case, 'pass') assert_equal(1, 2, test_case, 'fail') new_case(case, 'Assert:process_results') [test_total, test_pass_count, test_fail_count, test_pass, test_fail] = process_results(test_case) assert_equal(test_total, 2, case, 'test total') assert_equal(test_pass_count, 1, case, 'test pass count') assert_equal(test_fail_count, 1, case, 'test fail count') assert_array_equal(test_pass, array.from('[ Next Case ] pass: "1" is equal to "1".', '.'), case, 'pass array') assert_array_equal(test_fail, array.from(next_case1, 'x'), case, 'fail array') new_case(case, 'Assert:assertions') assert_equal(1 + 1, 2, case, "equal") assert_equal(1 + 2, 2, case, "equal fail") assert_true(failed(case, true), case, "equal failed") assert_not_equal(1 + 2, 2, case, "not equal") assert_not_equal(1 + 1, 2, case, "not equal fail") assert_true(failed(case, true), case, "not equal failed") assert_greater(2, 1, case, 'greater') assert_greater(1, 1, case, 'greater fail') assert_true(failed(case, true), case, 'greater failed') assert_lesser(1, 2, case, 'lesser') assert_lesser(1, 1, case, 'lesser fail') assert_true(failed(case, true), case, 'lesser failed') assert_greater_or_equal(2, 1, case, 'greater or equal #1') assert_greater_or_equal(1, 1, case, 'greater or equal #2') assert_greater_or_equal(1, 2, case, 'greater or equal fail') assert_true(failed(case, true), case, 'greater or equal failed') assert_lesser_or_equal(1, 2, case, 'lesser or equal #1') assert_lesser_or_equal(1, 1, case, 'lesser or equal #2') assert_lesser_or_equal(2, 1, case, 'lesser or equal fail') assert_true(failed(case, true), case, 'lesser or equal failed') assert_true(true, case, "true") assert_true(false, case, "true fail") assert_true(failed(case, true), case, "true failed") assert_false(false, case, "false") assert_false(true, case, "false fail") assert_true(failed(case, true), case, "false failed") assert_nan(int(na), case, "nan") assert_nan(int(1), case, "nan fail") assert_true(failed(case, true), case, "nan failed") assert_not_nan(int(1), case, "not nan") assert_not_nan(int(na), case, "not nan fail") assert_true(failed(case, true), case, "not nan failed") assert_in(1, array.from(1), case, "array") assert_in(2, array.from(1), case, "array fail") assert_true(failed(case, true), case, "array failed") assert_array_equal(array.new_float(), array.new_float(), case, 'array equal #1') assert_array_equal(array.new_float(1), array.new_float(1), case, 'array equal #2') assert_array_equal(array.new_float(1), array.new_float(2), case, 'array equal fail') assert_true(failed(case, true), case, "array equal failed") new_case(case, 'Assert:export assertions') equal(1, 1, case, 'equal') not_equal(1, 2, case, 'not_equal') greater(2, 1, case, 'greater') lesser(1, 2, case, 'lesser') greater_or_equal(2, 1, case, 'greater_or_equal') lesser_or_equal(1, 2, case, 'lesser_or_equal') nan(float(na), case, 'nan') not_nan(1, case, 'not_nan') is_in(1, array.from(1.0, 2.0), case, 'is_in') is_not_in(3, array.from(1.0, 2.0), case, 'is_not_in') array_equal(array.from(1.0, 2.0), array.from(1.0, 2.0), case, 'array_equal') int_in(1, array.from(1, 2), case, 'int_in') int_not_in(3, array.from(1, 2), case, 'int_not_in') int_array_equal(array.from(1, 2), array.from(1, 2), case, 'int_array_equal') is_true(true, case, 'is_true') is_false(false, case, 'is_false') bool_equal(true, true, case, 'bool_equal') bool_not_equal(true, false, case, 'bool_not_equal') bool_nan(bool(na), case, 'bool_nan') bool_not_nan(false, case, 'bool_not_nan') bool_array_equal(array.from(true, false), array.from(true, false), case, 'bool_array_equal') str_equal('hi', 'hi', case, 'str_equal') str_not_equal('hi', 'bye', case, 'str_not_equal') str_nan(string(na), case, 'str_nan #1') str_nan('', case, 'str_nan #2') // An empty string is NaN apparently... str_not_nan('hi', case, 'str_not_nan') str_in('yes', array.from('yes', 'no'), case, 'str_in') str_not_in('maybe', array.from('yes', 'no'), case, 'str_not_in') str_array_equal(array.from('yes', 'no'), array.from('yes', 'no'), case, 'str_array_equal') color_equal(#000000, #000000, case, 'color_equal') color_not_equal(#000000, #FFFFFF, case, 'color_not_equal') new_case(case, 'Assert:totals') [total, pass_count, fail_count, pass, fail] = process_results(case, clear = false) assert_equal(total - start_total, 98, case, "total") assert_equal(pass_count - start_pass_count, 98, case, "pass count") assert_equal(fail_count - start_fail_count, 0, case, "fail count") // @function Run the assert module unit tests as a stand alone. Usage: assert.unittest() // @param verbose bool, optionally disable the full report to only display failures export unittest(bool verbose = true) => if once() __ASSERTS = init() unittest_assert(__ASSERTS) report(__ASSERTS, verbose) // ██████╗ ██╗ ██╗ ███╗ ██╗ // ██╔══██╗ ██║ ██║ ████╗ ██║ // ██████╔╝ ██║ ██║ ██╔██╗██║ // ██╔══██╗ ██║ ██║ ██║╚████║ // ██║ ██║ ╚██████╔╝ ██║ ╚███║ // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══╝ unittest() // _v_ Do you trust the bots? // (* *) / // __)#(__ // ( _..._ ) // || |_| || // >==() |_| ()==< // _(___)_ // [-] [-]
bench
https://www.tradingview.com/script/R9XguNNc-bench/
GeoffHammond
https://www.tradingview.com/u/GeoffHammond/
59
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Geoff Hammond //@version=5 // @description A simple banchmark library to analyse script performance and bottlenecks library("bench") // █▄▄ █▀▀ █▄ █ █▀▀ █ █ █ █ █▄▄ █▀█ ▄▀█ █▀█ █▄█ // █▄█ ██▄ █ ▀█ █▄▄ █▀█ █▄▄ █ █▄█ █▀▄ █▀█ █▀▄ █ // @TODO: If intervals are used, process the full span? // ██╗ ██╗███████╗██╗ ██████╗ ███████╗██████╗ ██████╗ // ██║ ██║██╔════╝██║ ██╔══██╗██╔════╝██╔══██╗██╔════╝ // ███████║█████╗ ██║ ██████╔╝█████╗ ██████╔╝╚█████╗ // ██╔══██║██╔══╝ ██║ ██╔═══╝ ██╔══╝ ██╔══██╗ ╚═══██╗ // ██║ ██║███████╗███████╗██║ ███████╗██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ // QUICK REFERENCE // // Looping benchmark style // benchmark = bench.new(samples = 500, loops = 5000) // data = array.new_int() // // if bench.start(benchmark) // while bench.loop(benchmark) // array.unshift(data, timenow) // // bench.mark(benchmark) // while bench.loop(benchmark) // array.unshift(data, timenow) // // bench.mark(benchmark) // while bench.loop(benchmark) // array.unshift(data, timenow) // // bench.stop(benchmark) // bench.reference(array.get(data, 0)) // bench.report(benchmark, '1x array.unshift()') // // // Linear benchmark style // benchmark = bench.new() // data = array.new_int() // // bench.start(benchmark) // for i = 0 to 1000 // array.unshift(data, timenow) // // bench.mark(benchmark) // for i = 0 to 1000 // array.unshift(data, timenow) // // bench.stop(benchmark) // bench.reference(array.get(data, 0)) // bench.report(benchmark,'1000x array.unshift()') // ██╗ ███╗ ███╗ ██████╗ █████╗ ██████╗ ████████╗ ██████╗ // ██║ ████╗ ████║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚══██╔══╝ ██╔════╝ // ██║ ██╔████╔██║ ██████╔╝ ██║ ██║ ██████╔╝ ██║ ╚█████╗ // ██║ ██║╚██╔╝██║ ██╔═══╝ ██║ ██║ ██╔══██╗ ██║ ╚═══██╗ // ██║ ██║ ╚═╝ ██║ ██║ ╚█████╔╝ ██║ ██║ ██║ ██████╔╝ // ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ import GeoffHammond/assert/4 // ██████╗ ██╗ █████╗ ██████╗ █████╗ ██╗ ██████╗ // ██╔════╝ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██╔════╝ // ██║ ██╗ ██║ ██║ ██║ ██████╦╝ ███████║ ██║ ╚█████╗ // ██║ ╚██╗ ██║ ██║ ██║ ██╔══██╗ ██╔══██║ ██║ ╚═══██╗ // ╚██████╔╝ ███████╗ ╚█████╔╝ ██████╦╝ ██║ ██║ ███████╗ ██████╔╝ // ╚═════╝ ╚══════╝ ╚════╝ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ var COUNTER = 0 var REQUIRED = 1 var STATE = 2 var LOOPS = 3 var MARKS = 4 var DATA = 5 var NEW = 0 var STARTED = 1 var MARKED = 2 var STOPPED = 3 var FINISHED = 4 var RATE = 0 var MEAN = 1 var VARIANCE = 2 var STDEV = 3 var MIN = 4 var MAX = 5 var FIRST = 6 var LAST = 7 var DELTA = 8 var SUM = 9 var RESULT_FIELDS = 10 var FORMAT_REPORT_HEADER = '{0}Benchmark Results:' var FORMAT_VARIANCE = '{0,number,#.#}%' var FORMAT_RATE = '~{0,number,#.##}{1}' var FORMAT_MICROTIME = '{0,number,#.###}{1}' // ███████╗ ██╗ ██╗ ███╗ ██╗ █████╗ ████████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ // ██╔════╝ ██║ ██║ ████╗ ██║ ██╔══██╗ ╚══██╔══╝ ██║ ██╔══██╗ ████╗ ██║ ██╔════╝ // █████╗ ██║ ██║ ██╔██╗██║ ██║ ╚═╝ ██║ ██║ ██║ ██║ ██╔██╗██║ ╚█████╗ // ██╔══╝ ██║ ██║ ██║╚████║ ██║ ██╗ ██║ ██║ ██║ ██║ ██║╚████║ ╚═══██╗ // ██║ ╚██████╔╝ ██║ ╚███║ ╚█████╔╝ ██║ ██║ ╚█████╔╝ ██║ ╚███║ ██████╔╝ // ╚═╝ ╚═════╝ ╚═╝ ╚══╝ ╚════╝ ╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚══╝ ╚═════╝ array_increment(arr, offset) => array.set(arr, offset, array.get(arr, offset) + 1), arr array_decrement(arr, offset) => array.set(arr, offset, array.get(arr, offset) - 1), arr array_last(arr) => array.get(arr, array.size(arr) - 1) // @TODO: remove this when next version of asserts is published only(int repeat = 1) => var done = 0 if done < repeat done += 1 true else false pad(string value, int amount = 1) => spaces = array.new_string(amount, ' ') str.format('{0}{1}{0}', array.join(spaces, ''), value) // ███╗ ███╗ █████╗ ██████╗ ██╗ ██╗ ██╗ ███████╗ // ████╗ ████║ ██╔══██╗ ██╔══██╗ ██║ ██║ ██║ ██╔════╝ // ██╔████╔██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ █████╗ // ██║╚██╔╝██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══╝ // ██║ ╚═╝ ██║ ╚█████╔╝ ██████╔╝ ╚██████╔╝ ███████╗ ███████╗ // ╚═╝ ╚═╝ ╚════╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚══════╝ add_compiler_reference(string value) => label.delete(label.new(bar_index, 0, value)) process_results(int[] benchmark) => required = array.get(benchmark, REQUIRED) state = array.get(benchmark, STATE) loops = array.get(benchmark, LOOPS) marks = array.get(benchmark, MARKS) if state < STOPPED runtime.error('[Bench:process_results] State is not stopped, please check order of execution.') sample_size = marks + 2 // the number of measurements in each sample data = array.slice(benchmark, DATA, array.size(benchmark)) samples = array.size(data) / sample_size if required != samples runtime.error(str.format('[Bench:process_results] Required sample count "{0}" does not equal captured sample count "{1}"', required, samples)) results = array.new_float() for i = 0 to marks interval = array.new_int() int first = na int last = na float delta = na for s = 0 to samples - 1 start = array.get(data, s * sample_size + i) end = array.get(data, s * sample_size + i + 1) array.push(interval, end - start) if s == 0 first := end - start if s == samples - 1 last := end - start size = array.size(interval) _delta = array.new_float() if size > 1 for j = 0 to size - 2 array.push(_delta, array.get(interval, j + 1) - array.get(interval, j)) delta := array.avg(_delta) / loops else delta := 0 mean = array.avg(interval) / loops min = array.min(interval) / loops max = array.max(interval) / loops array.push(results, 1000 / mean) // RATE array.push(results, mean) // MEAN array.push(results, (math.max(max - mean, mean - min) / mean) * 100) // VARIANCE array.push(results, array.stdev(interval) / loops) // STDEV array.push(results, min) // MIN array.push(results, max) // MAX array.push(results, first / loops) // FIRST array.push(results, last / loops) // LAST array.push(results, delta) // DELTA array.push(results, array.sum(interval)) // SUM results format_rate(float value) => if value >= 995000000 str.format(FORMAT_RATE, value / 1000000000, 'B') else if value >= 995000 str.format(FORMAT_RATE, value / 1000000, 'M') else if value >= 995 str.format(FORMAT_RATE, value / 1000, 'K') else str.format(FORMAT_RATE, value, '') format_microtime(float value) => if math.abs(value) < 0.000001 str.format(FORMAT_MICROTIME, value * 1000000000, 'ps') else if math.abs(value) < 0.001 str.format(FORMAT_MICROTIME, value * 1000000, 'ns') else if math.abs(value) < 1 str.format(FORMAT_MICROTIME, value * 1000, 'μs') else if math.abs(value) >= 1000 str.format(FORMAT_MICROTIME, value / 1000, 's') else str.format(FORMAT_MICROTIME, value, 'ms') // ██╗ ██╗ ██████╗ ██████╗ █████╗ ██████╗ ██╗ ██╗ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ╚██╗ ██╔╝ // ██║ ██║ ██████╦╝ ██████╔╝ ███████║ ██████╔╝ ╚████╔╝ // ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██║ ██╔══██╗ ╚██╔╝ // ███████╗ ██║ ██████╦╝ ██║ ██║ ██║ ██║ ██║ ██║ ██║ // ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ // @function Initialises a new benchmark array // @param samples int, the number of bars in which to collect samples // @param loops int, the number of loops to execute within each sample // @returns int[], the benchmark array export new(int samples = na, int loops = 1) => if samples <= 1 and loops <= 1 runtime.error('[Bench:new] Trying to run a benchmark with a sample size of 1 is just silly!') varip benchmark = array.new_int(2, samples) counter = array.get(benchmark, COUNTER) if na(counter) or counter == samples array.push(benchmark, NEW) // initial state array.push(benchmark, loops) // number of loops in each sample array.push(benchmark, 0) // number of marks if na(samples) if barstate.islastconfirmedhistory array.set(benchmark, COUNTER, -1) array.set(benchmark, REQUIRED, bar_index) array.set(benchmark, STATE, FINISHED) else array.set(benchmark, COUNTER, 1) benchmark // @function Determing if the benchmarks state is active // @param benchmark int[], the benchmark array // @returns bool, true only if the state is active export active(int[] benchmark) => state = array.get(benchmark, STATE) state > NEW and state < STOPPED // @function Start recording a benchmark from this point // @param benchmark int[], the benchmark array // @returns bool, true only if the benchmark is unfinished export start(int[] benchmark) => counter = array.get(benchmark, COUNTER) if counter > 0 or na(array.get(benchmark, REQUIRED)) if active(benchmark) runtime.error('[Bench:start] Timer has been previously started but not stopped! Please add a bench.stop() call.') array.set(benchmark, STATE, STARTED) array.set(benchmark, MARKS, 0) array_decrement(benchmark, COUNTER) array.push(benchmark, timenow) true else if counter == 0 array.set(benchmark, STATE, FINISHED) array_decrement(benchmark, COUNTER) false else false // @function Returns true until call count exceeds bench.new(loop) variable // @param benchmark int[], the benchmark array // @returns bool, true while looping export loop(int[] benchmark) => varip count = 0 if active(benchmark) and count < array.get(benchmark, LOOPS) count += 1 true else count := 0 false // @function Add a compiler reference to the chart so the calculations don't get optimised away // @param number float, a non-zero numeric value to reference // @param string string, a non-empty string value to reference export reference(float number = 0, string string = '') => if number != 0 add_compiler_reference(str.tostring(number)) if string != '' add_compiler_reference(string) // @function Marks the end of one recorded interval and the start of the next // @param benchmark int[], the benchmark array // @param number float, a numeric value to reference // @param string string, a string value to reference export mark(int[] benchmark, float number = na, string string = na) => if active(benchmark) and array.get(benchmark, COUNTER) >= 0 array.push(benchmark, timenow) array.set(benchmark, STATE, MARKED) array_increment(benchmark, MARKS) reference(number, string) // @function Stop the benchmark, ending the final interval // @param benchmark int[], the benchmark array // @param number float, a numeric value to reference // @param string string, a string value to reference export stop(int[] benchmark, float number = na, string string = na) => if active(benchmark) and array.get(benchmark, COUNTER) >= 0 array.set(benchmark, STATE, STOPPED) reference(number, string) array.push(benchmark, timenow) // @param Prints the benchmarks results to the screen // @param benchmark int[], the benchmark array // @param title string, add a custom title to the report // @param text_size string, the text size of the log console (global size vars) // @param position string, the position of the log console (global position vars) export report(int[] benchmark, string title = na, string text_size = na, string position = na) => if barstate.islastconfirmedhistory counter = array.get(benchmark, COUNTER) required = array.get(benchmark, REQUIRED) loops = array.get(benchmark, LOOPS) marks = array.get(benchmark, MARKS) if counter > 0 runtime.error('[Bench:report] Counter is not zero, there may not be enough bars on the chart, or bench.new(samples) is too high.') results = process_results(benchmark) size = array.size(results) / RESULT_FIELDS var tbl = table.new(na(position) ? position.middle_left : position, size + 1, 14, #000000, #888888, 1) if size _text_size = na(text_size) ? size.normal : text_size header_color = #FFFFFF heading_color = #FFFFFF cell_color = #adf5f7 table.cell(tbl, 0, 0, str.format(FORMAT_REPORT_HEADER, na(title) ? '' : title + '\n\n'), text_color=header_color, text_halign=text.align_left, text_size=size.large, bgcolor=na) table.cell(tbl, 0, 1, 'Total Executions:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 2, 'Timed Intervals:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 3, 'Interval:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=#111111) table.cell(tbl, 0, 4, 'Rate (per sec):', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 5, 'Mean:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 6, 'Variance:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 7, 'Std Dev:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 8, 'Fastest:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 9, 'Slowest:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 10, 'First:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 11, 'Last:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 12, 'Delta:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 0, 13, 'Total Time:', text_color=heading_color, text_halign=text.align_right, text_size=_text_size, bgcolor=na) table.cell(tbl, 1, 1, str.format('{0}', required * loops), text_color=cell_color, text_halign=text.align_left, text_size=_text_size, bgcolor=na) table.cell(tbl, 1, 2, str.format('{0}', marks + 1), text_color=cell_color, text_halign=text.align_left, text_size=_text_size, bgcolor=na) for i = 0 to size - 1 cell_bgcolor = i % 2 == 0 ? #060606 : na rate = array.get(results, i * RESULT_FIELDS + RATE) mean = array.get(results, i * RESULT_FIELDS + MEAN) variance = array.get(results, i * RESULT_FIELDS + VARIANCE) stdev = array.get(results, i * RESULT_FIELDS + STDEV) min = array.get(results, i * RESULT_FIELDS + MIN) max = array.get(results, i * RESULT_FIELDS + MAX) first = array.get(results, i * RESULT_FIELDS + FIRST) last = array.get(results, i * RESULT_FIELDS + LAST) delta = array.get(results, i * RESULT_FIELDS + DELTA) sum = array.get(results, i * RESULT_FIELDS + SUM) table.cell(tbl, i + 1, 3, pad(str.format('#{0}', i + 1)), text_color=heading_color, text_halign=text.align_center, text_size=_text_size, bgcolor=#111111) table.cell(tbl, i + 1, 4, pad(format_rate(rate)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 5, pad(format_microtime(mean)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 6, pad(str.format(FORMAT_VARIANCE, variance)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 7, pad(format_microtime(stdev)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 8, pad(format_microtime(min)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 9, pad(format_microtime(max)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 10, pad(format_microtime(first)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 11, pad(format_microtime(last)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 12, pad(format_microtime(delta)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) table.cell(tbl, i + 1, 13, pad(format_microtime(sum)), text_color=cell_color, text_halign=text.align_center, text_size=_text_size, bgcolor=cell_bgcolor) // ██╗ ██╗ ███╗ ██╗ ██╗ ████████╗ ████████╗ ███████╗ ██████╗ ████████╗ ██████╗ // ██║ ██║ ████╗ ██║ ██║ ╚══██╔══╝ ╚══██╔══╝ ██╔════╝ ██╔════╝ ╚══██╔══╝ ██╔════╝ // ██║ ██║ ██╔██╗██║ ██║ ██║ ██║ █████╗ ╚█████╗ ██║ ╚█████╗ // ██║ ██║ ██║╚████║ ██║ ██║ ██║ ██╔══╝ ╚═══██╗ ██║ ╚═══██╗ // ╚██████╔╝ ██║ ╚███║ ██║ ██║ ██║ ███████╗ ██████╔╝ ██║ ██████╔╝ // ╚═════╝ ╚═╝ ╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ // @function Cache module unit tests, for inclusion in parent script test suite. Usage: bench.unittest_bench(__ASSERTS) // @param case string[], the current test case and array of previous unit tests (__ASSERTS) export unittest_bench(string[] case) => assert.new_case(case, 'Bench:array_increment') assert.array_equal(array_increment(array.from(1, 2), 0), array.from(2, 2), case) assert.array_equal(array_increment(array.from(1, 2), 1), array.from(1, 3), case) assert.new_case(case, 'Bench:array_decrement') assert.array_equal(array_decrement(array.from(1, 2), 0), array.from(0, 2), case) assert.array_equal(array_decrement(array.from(1, 2), 1), array.from(1, 1), case) assert.new_case(case, 'Bench:array_last') assert.equal(array_last(array.from(1, 2, 3)), 3, case) assert.new_case(case, 'Bench:new') assert.equal(array.size(new()), 5, case) assert.equal(array.get(new(), COUNTER), 1, case) assert.nan(array.get(new(), REQUIRED), case) assert.equal(array.get(new(1000), COUNTER), 1000, case) assert.equal(array.get(new(1000), REQUIRED), 1000, case) assert.equal(array.get(new(5000), REQUIRED), 5000, case) assert.equal(array.get(new(1000), STATE), NEW, case) assert.equal(array.get(new(1000), LOOPS), 1, case) assert.equal(array.get(new(5000, 100), LOOPS), 100, case) assert.equal(array.get(new(1000), MARKS), 0, case) assert.equal(array.get(new(5000, 100), MARKS), 0, case) // @TODO: Bench:new barstate.islastconfirmedhistory section untested assert.new_case(case, 'Bench:start') benchmark = new() timestamp = timenow array.set(benchmark, MARKS, 1) assert.is_true(start(benchmark), case) assert.equal(array.size(benchmark), 6, case) assert.equal(array.get(benchmark, COUNTER), 0, case) assert.nan(array.get(benchmark, REQUIRED) , case) assert.equal(array.get(benchmark, STATE), STARTED, case) assert.equal(array.get(benchmark, MARKS), 0, case) assert.greater_or_equal(array_last(benchmark), timestamp, case) benchmark := new(1000) assert.is_true(start(benchmark), case) assert.equal(array.get(benchmark, COUNTER), 999, case) assert.equal(array.get(benchmark, REQUIRED), 1000, case) assert.equal(array.get(benchmark, STATE), STARTED, case) assert.equal(array.get(benchmark, MARKS), 0, case) array.set(benchmark, COUNTER, 0) array.set(benchmark, STATE, STOPPED) assert.is_false(start(benchmark), case) assert.equal(array.get(benchmark, COUNTER), -1, case) assert.equal(array.get(benchmark, STATE), FINISHED, case) assert.is_false(start(benchmark), case) assert.equal(array.get(benchmark, COUNTER), -1, case) assert.new_case(case, 'Bench:loop') i = 0 while loop(benchmark) i += 1 assert.equal(i, 0, case) array.set(benchmark, COUNTER, 10) array.set(benchmark, STATE, STARTED) i := 0 while loop(benchmark) i += 1 assert.equal(i, 1, case) array.set(benchmark, LOOPS, 10) i := 0 while loop(benchmark) i += 1 assert.equal(i, 10, case) assert.new_case(case, 'Bench:reference') // Not sure this function is really testable :/ assert.new_case(case, 'Bench:mark') timestamp := timenow mark(benchmark) assert.equal(array.size(benchmark), 7, case) assert.equal(array.get(benchmark, STATE), MARKED, case) assert.equal(array.get(benchmark, MARKS), 1, case) assert.greater_or_equal(array_last(benchmark), timestamp, case) assert.new_case(case, 'Bench:stop') stop(benchmark) timestamp := timenow assert.equal(array.size(benchmark), 8, case) assert.equal(array.get(benchmark, STATE), STOPPED, case) assert.greater_or_equal(array_last(benchmark), timestamp, case) assert.new_case(case, 'Bench:process_results') benchmark := new(3, 10) array.set(benchmark, COUNTER, -1) array.set(benchmark, STATE, FINISHED) array.set(benchmark, MARKS, 1) array.push(benchmark, 100), array.push(benchmark, 120), array.push(benchmark, 150) array.push(benchmark, 201), array.push(benchmark, 220), array.push(benchmark, 252) array.push(benchmark, 302), array.push(benchmark, 320), array.push(benchmark, 357) results = process_results(benchmark) assert.equal(array.size(results), RESULT_FIELDS * 2, case) sum = 20.0 + 19.0 + 18.0 mean = sum / 3.0 / 10.0 assert.equal(array.get(results, RATE), 1000.0 / mean, case) assert.equal(array.get(results, MEAN), mean, case) assert.equal(array.get(results, VARIANCE), 0.1 / mean * 100.0, case) assert.equal(array.get(results, STDEV), array.stdev(array.from(20, 19, 18)) / 10, case) assert.equal(array.get(results, MIN), 1.8, case) assert.equal(array.get(results, MAX), 2, case) assert.equal(array.get(results, FIRST), 2, case) assert.equal(array.get(results, LAST), 1.8, case) assert.equal(array.get(results, DELTA), -0.1, case) assert.equal(array.get(results, SUM), sum, case) sum := 30.0 + 32.0 + 37.0 mean := sum / 3.0 / 10.0 assert.equal(array.get(results, RESULT_FIELDS + RATE), 1000.0 / mean, case) assert.equal(array.get(results, RESULT_FIELDS + MEAN), mean, case) assert.equal(array.get(results, RESULT_FIELDS + VARIANCE), 0.4 / mean * 100.0, case) assert.equal(array.get(results, RESULT_FIELDS + STDEV), array.stdev(array.from(30, 32, 37)) / 10, case) assert.equal(array.get(results, RESULT_FIELDS + MIN), 3, case) assert.equal(array.get(results, RESULT_FIELDS + MAX), 3.7, case) assert.equal(array.get(results, RESULT_FIELDS + FIRST), 3, case) assert.equal(array.get(results, RESULT_FIELDS + LAST), 3.7, case) assert.equal(array.get(results, RESULT_FIELDS + DELTA), 0.35, case) assert.equal(array.get(results, RESULT_FIELDS + SUM), sum, case) assert.new_case(case, 'Bench:format_rate') assert.str_equal(format_rate(1000000000), '~1B', case) assert.str_equal(format_rate(995000000), '~0.99B', case) assert.str_equal(format_rate(994999999), '~995M', case) assert.str_equal(format_rate(994990000), '~994.99M', case) assert.str_equal(format_rate(1000000), '~1M', case) assert.str_equal(format_rate(995000), '~0.99M', case) assert.str_equal(format_rate(994999), '~995K', case) assert.str_equal(format_rate(994990), '~994.99K', case) assert.str_equal(format_rate(1000), '~1K', case) assert.str_equal(format_rate(995), '~0.99K', case) assert.str_equal(format_rate(994.99), '~994.99', case) assert.new_case(case, 'Bench:format_microtime') assert.str_equal(format_microtime(0.000000001), '1ps', case) assert.str_equal(format_microtime(0.000000999), '999ps', case) assert.str_equal(format_microtime(0.000001), '1ns', case) assert.str_equal(format_microtime(-0.000001), '-1ns', case) assert.str_equal(format_microtime(0.000001001), '1.001ns', case) assert.str_equal(format_microtime(0.000999), '999ns', case) assert.str_equal(format_microtime(0.001), '1μs', case) assert.str_equal(format_microtime(-0.001), '-1μs', case) assert.str_equal(format_microtime(0.001001), '1.001μs', case) assert.str_equal(format_microtime(0.999), '999μs', case) assert.str_equal(format_microtime(1), '1ms', case) assert.str_equal(format_microtime(-1), '-1ms', case) assert.str_equal(format_microtime(1.001), '1.001ms', case) assert.str_equal(format_microtime(999), '999ms', case) assert.str_equal(format_microtime(1000), '1s', case) assert.str_equal(format_microtime(-1000), '-1s', case) assert.str_equal(format_microtime(1001), '1.001s', case) assert.new_case(case, 'Bench:execution') benchmark := new(2, 10) i := 0 while only(3) // simulating three bars if start(benchmark) while loop(benchmark) i += 1 mark(benchmark) while loop(benchmark) i += 1 stop(benchmark) assert.equal(i, 40, case) assert.equal(array.size(benchmark), 11, case) assert.equal(array.get(benchmark, STATE), FINISHED, case) assert.equal(array.get(benchmark, MARKS), 1, case) // @function Run the bench module unit tests as a stand alone. Usage: bench.unittest() // @param verbose bool, optionally disable the full report to only display failures export unittest(bool verbose = true) => if assert.once() __ASSERTS = assert.init() unittest_bench(__ASSERTS) assert.report(__ASSERTS, verbose, position=position.top_right) // ███████╗██╗░░██╗░█████╗░███╗░░░███╗██████╗░██╗░░░░░███████╗░██████╗ // ██╔════╝╚██╗██╔╝██╔══██╗████╗░████║██╔══██╗██║░░░░░██╔════╝██╔════╝ // █████╗░░░╚███╔╝░███████║██╔████╔██║██████╔╝██║░░░░░█████╗░░╚█████╗░ // ██╔══╝░░░██╔██╗░██╔══██║██║╚██╔╝██║██╔═══╝░██║░░░░░██╔══╝░░░╚═══██╗ // ███████╗██╔╝╚██╗██║░░██║██║░╚═╝░██║██║░░░░░███████╗███████╗██████╔╝ // ╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░░░░╚═╝╚═╝░░░░░╚══════╝╚══════╝╚═════╝░ examples() => group1 = 'Example 1: Artificial looping benchmark (multiple samples per bar)' example1 = input.bool(true, 'Run?', group=group1) samples = input.int(500, 'Number of samples (bars) to run?', group=group1, minval=1, step=10) loops = input.int(5000, 'Number of loops to run in each sample?', group=group1, minval=1, step=10) group2 = 'Example 2: Integrated linear benchmark (one sample per bar)' example2 = input.bool(false, 'Run? (disable 1 first)', group=group2) unshifts = input.int(3000, 'Number of unshifts to bench on each bar?', group=group2, minval=1, step=10) if example1 // When doing artifical benchmarks, the faster the operation under test, the more loops are required to give an accurate result. // This in turn likely means lowering the sample size to only run a limited number of times. benchmark = new(samples = samples, loops = loops) data = array.new_int() // Here we limit execution to the chosen number of samples if start(benchmark) // We use the loop function to execute the code under tests for the required number of loops while loop(benchmark) // Code under test for interval 1 (unshift into 0 length array) array.unshift(data, timenow) mark(benchmark) // Loops can be used multiple times and must be run for all marked intervals while loop(benchmark) // Code under test for interval 2 (unshift into 5000 length array) array.unshift(data, timenow) mark(benchmark) while loop(benchmark) // Code under test for interval 3 (unshift into 10000 length array) array.unshift(data, timenow) stop(benchmark) // We must add a reference to the array, so the compiler doesn't ignore it (most artifical benchmarks will need this) reference(array.get(data, 0)) report(benchmark, '1x array.unshift()') else if example2 // This style of benchmarking will only be useful if you have a highly computationally expensive script. // As the default benchmark will only run a single sample on every bar until barstate.islastconfirmedhistory. benchmark = new() data = array.new_int() start(benchmark) // Expensive code under test for interval 1 (3000 unshifts onto a 0 length array) for i = 0 to unshifts array.unshift(data, timenow) // mark(benchmark) // // Example further code under test for interval 2 (1000 unshifts onto a 3000 length array) // for i = 0 to 1000 // array.unshift(data, timenow) stop(benchmark) // We must add a reference to the array, so the compiler doesn't ignore it (your code may not need this if it already draws) reference(array.get(data, 0)) report(benchmark, str.format('{0}x array.unshift()', unshifts)) // ██████╗ ██╗ ██╗ ███╗ ██╗ // ██╔══██╗ ██║ ██║ ████╗ ██║ // ██████╔╝ ██║ ██║ ██╔██╗██║ // ██╔══██╗ ██║ ██║ ██║╚████║ // ██║ ██║ ╚██████╔╝ ██║ ╚███║ // ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══╝ unittest() examples() // _____ // _.'_____`._ // .'.-' 12 `-.`. // /,' 11 1 `.\ // // 10 / 2 \\ // ;; / :: // || 9 ----O 3 || // :: ;; // \\ 8 4 // // \`. 7 5 ,'/ // '.`-.__6__.-'.' // ((-._____.-)) // _)) ((_ Is benching just an illusion too? // '--' '--'
LibraryPrivateUsage001
https://www.tradingview.com/script/LrBomXvi-LibraryPrivateUsage001/
LonesomeTheBlue
https://www.tradingview.com/u/LonesomeTheBlue/
132
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © LonesomeTheBlue //@version=5 // @description This library is used for math operations. library("LibraryPrivateUsage001") // @function checks if the array elements (which index is smaller than end) is smaller than the value ylv // @param ylv value to compare array elements // @param end last index of the array elements // @param arr the array pointer // @returns true if none of the elements is smaller than ylv, otherwise returns false bIsF(float ylv, float end, float [] arr) => array.min(array.slice(arr, 1, math.round(end))) >= ylv // @function checks if the array elements (which index is smaller than end) is greater than the value ylv // @param ylv value to compare array elements // @param end last index of the array elements // @param arr the array pointer // @returns true if none of the elements is greater than ylv, otherwise returns false tIsF(float ylv, float end, float [] arr) => array.max(array.slice(arr, 1, math.round(end))) <= ylv // @function checks if the array element is between v1 and v2 // @param rates_array array that keeps float elements // @param index then number of elements in the array to compare // @param v1 and v2 the values to compare with the array element // @returns true if the array element is between v1 and v2 isfine1(float [] rates_array, int index, float v1, float v2) => (array.get(rates_array, index) >= v1 and array.get(rates_array, index) <= v2) // @function checks if l1/l2 is between v1 and v2 // @param l1 float // @param l2 float // @param index then number of elements in the array to compare // @param v1 and v2 the values to compare with l1/l2 // @returns true if l1/l2is between v1 and v2 isFine(float d, float v1, float v2) => (d >= v1 and d <= v2) // @function assigns maximum and minimum values to the array mima // @param mima is the array to keep max/min // @param c1 first var of part1 // @param c2 second var of part1 // @param a1 first var of part2 // @param a2 second var of part2 // @returns none export getRMinmax1(float [] mima, float c1, float c2, float a1, float a2) => array.set(mima, 0, math.min(math.max(c1, c2), math.max(a1, a2))) array.set(mima, 1, math.max(math.min(c1, c2), math.min(a1, a2))) // @function assigns maximum and minimum values to the array mima // @param mima is the array to keep max/min // @param c1 first var // @param c2 second var // @returns none export getRMinmax2(float [] mima, float c1, float c2) => array.set(mima, 0, math.max(c1, c2)) array.set(mima, 1, math.min(c1, c2)) // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType10(bool thiscond, float [] allvalues, float [] arr) => if thiscond (array.get(allvalues, 9) < array.get(allvalues, 10) and (isFine((array.get(allvalues, 3) - array.get(allvalues, 4)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(allvalues, 12), array.get(allvalues, 13))) and (isFine((array.get(allvalues, 3) - array.get(allvalues, 2)) / (array.get(allvalues, 1) - array.get(allvalues, 2)), array.get(allvalues, 15), array.get(allvalues, 16))) and ((array.get(allvalues, 1) - array.get(allvalues, 0)) / (array.get(allvalues, 1) - array.get(allvalues, 2)) > 1.) and array.get(allvalues, 5) < math.max(array.get(allvalues, 1), array.get(allvalues, 3))) ? bIsF(math.max(array.get(allvalues, 1), array.get(allvalues, 3)), bar_index - array.get(allvalues, 8), arr) : false // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType11(bool thiscond, float [] allvalues, float [] arr) => if thiscond (array.get(allvalues, 9) > array.get(allvalues, 10) and (isFine((array.get(allvalues, 3) - array.get(allvalues, 4)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(allvalues, 12), array.get(allvalues, 13))) and (isFine((array.get(allvalues, 3) - array.get(allvalues, 2)) / (array.get(allvalues, 1) - array.get(allvalues, 2)), array.get(allvalues, 15), array.get(allvalues, 16))) and ((array.get(allvalues, 1) - array.get(allvalues, 0)) / (array.get(allvalues, 1) - array.get(allvalues, 2)) > 1.) and array.get(allvalues, 5) > math.min(array.get(allvalues, 1), array.get(allvalues, 3))) ? tIsF(math.min(array.get(allvalues, 1), array.get(allvalues, 3)), bar_index - array.get(allvalues, 8), arr) : false // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType12(bool thiscond, float [] allvalues, float [] arr) => if thiscond ((math.abs(array.get(allvalues, 2) - array.get(allvalues, 1)) > math.abs(array.get(allvalues, 2) - array.get(allvalues, 3))) and (isFine((array.get(allvalues, 2) - array.get(allvalues, 3)) / (array.get(allvalues, 4) - array.get(allvalues, 3)), array.get(allvalues, 15), array.get(allvalues, 16))) and (array.get(allvalues, 2) > array.get(allvalues, 3)) and (array.get(allvalues, 5) < array.get(allvalues, 3)) and (array.get(allvalues, 6) > array.get(allvalues, 14))) ? bIsF(math.max(array.get(allvalues, 1), array.get(allvalues, 3)), bar_index - array.get(allvalues, 7), arr) : false // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType13(bool thiscond, float [] allvalues, float [] arr) => if thiscond ((math.abs(array.get(allvalues, 2) - array.get(allvalues, 1)) > math.abs(array.get(allvalues, 2) - array.get(allvalues, 3))) and (isFine((array.get(allvalues, 2) - array.get(allvalues, 3)) / (array.get(allvalues, 4) - array.get(allvalues, 3)), array.get(allvalues, 15), array.get(allvalues, 16))) and (array.get(allvalues, 2) < array.get(allvalues, 3)) and (array.get(allvalues, 5) > array.get(allvalues, 3)) and (array.get(allvalues, 6) > array.get(allvalues, 14))) ? tIsF(math.min(array.get(allvalues, 1), array.get(allvalues, 3)), bar_index - array.get(allvalues, 7), arr) : false // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType14(bool thiscond, float [] allvalues, float [] arr) => if thiscond (isFine((array.get(allvalues, 0) - array.get(allvalues, 1)) / (array.get(allvalues, 2) - array.get(allvalues, 1)), array.get(allvalues, 17), array.get(allvalues, 18))) and (isFine((array.get(allvalues, 4) - array.get(allvalues, 3)) / (array.get(allvalues, 2) - array.get(allvalues, 3)), array.get(allvalues, 17), array.get(allvalues, 18))) and (isFine((array.get(allvalues, 1) - array.get(allvalues, 2)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(allvalues, 15), array.get(allvalues, 16))) and array.get(allvalues, 5) < math.min(array.get(allvalues, 1), array.get(allvalues, 3)) ? bIsF(array.get(allvalues, 3), bar_index - array.get(allvalues, 7), arr) : false // @function checks if thiscond is true and elements of rates array is between the elements of rates_array // @param thiscond to check if it's true // @param rates_array to get values to compare // @param arr keeps the values to compare them with the elements of rates_array // @returns true if all conditions met export checkType15(bool thiscond, float [] allvalues, float [] arr) => if thiscond (isFine((array.get(allvalues, 1) - array.get(allvalues, 0)) / (array.get(allvalues, 1) - array.get(allvalues, 2)), array.get(allvalues, 17), array.get(allvalues, 18))) and (isFine((array.get(allvalues, 3) - array.get(allvalues, 4)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(allvalues, 17), array.get(allvalues, 18))) and (isFine((array.get(allvalues, 1) - array.get(allvalues, 2)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(allvalues, 15), array.get(allvalues, 16))) and array.get(allvalues, 5) > math.max(array.get(allvalues, 1), array.get(allvalues, 3)) ? tIsF(array.get(allvalues, 3), bar_index - array.get(allvalues, 7), arr) : false // @function checks conditions and if the conditions met then get max/min values and assign them to elements mima array // @param vals array to to get values // @param allina array of constant values // @param index array pointer // @returns minmax values in a array if all conditions met CheckRtype1(float [] vals, float [] allina, int index) => mima = array.new_float(2, na) if isFine((array.get(vals, 1) - array.get(vals, 2)) / (array.get(vals, 1) - array.get(vals, 0)), array.get(allina, 22 * (index - 1)), array.get(allina, 22 * (index - 1) + 1)) and isFine((array.get(vals, 3) - array.get(vals, 2)) / (array.get(vals, 1) - array.get(vals, 2)), array.get(allina, 22 * (index - 1) + 2), array.get(allina, 22 * (index - 1) + 3)) p0 = array.get(vals, 0) p1 = array.get(vals, 1) p2 = array.get(vals, 2) p3 = array.get(vals, 3) c1 = p3 - array.get(allina, 22 * (index - 1) + 4) * (p3 - p2) c2 = p3 - array.get(allina, 22 * (index - 1) + 5) * (p3 - p2) a1 = p1 - array.get(allina, 22 * (index - 1) + 6) * (p1 - p0) a2 = p1 - array.get(allina, 22 * (index - 1) + 7) * (p1 - p0) getRMinmax1(mima, c1, c2, a1, a2) [array.get(mima, 0), array.get(mima, 1)] // @function checks conditions and if the conditions met then get max/min values and assign them to elements mima array // @param vals array to to get values // @param allina array of constant values // @param index array pointer // @returns minmax values in a array if all conditions met CheckRtype2(float [] vals, float [] allina, int index) => mima = array.new_float(2, na) if isFine((array.get(vals, 2) - array.get(vals, 1)) / (array.get(vals, 0) - array.get(vals, 1)), array.get(allina, 22 * (index - 1)), array.get(allina, 22 * (index - 1) + 1)) and isFine((array.get(vals, 0) - array.get(vals, 3)) / (array.get(vals, 0) - array.get(vals, 1)), array.get(allina, 22 * (index - 1) + 8), array.get(allina, 22 * (index - 1) + 9)) p2 = array.get(vals, 0) // x p1 = array.get(vals, 3) // c c1 = p1 - array.get(allina, 22 * (index - 1) + 10) * (p1 - p2) c2 = p1 - array.get(allina, 22 * (index - 1) + 11) * (p1 - p2) getRMinmax2(mima, c1, c2) [array.get(mima, 0), array.get(mima, 1)] // @function checks mima array and if conditions met assigns the elements of pre_loc array // @param pre_loc keeps the elements that is set when conditions met // @param arr is an array which keeps the values to compare // @param index is an integer value that is used as index while assigning values to pre_loc array // @returns mima is the array that keeps max/min values setPPL(float [] pre_loc, float [] arr, int index, int dir, float mima) => if array.size(pre_loc) == 0 for x = 0 to 7 array.push(pre_loc, array.get(arr, index + x)) array.unshift(pre_loc, mima) else if (dir == 1 and array.get(pre_loc, 0) > mima) or (dir == -1 and array.get(pre_loc, 0) < mima) for x = 1 to 8 array.set(pre_loc, x, array.get(arr, index + x - 1)) array.set(pre_loc, 0, mima) // @function checks arr array and if distance is greater than mindis // @param ylv is used to check level // @param arr is an array which keeps the values to compare // @param mindis is the distance // @param index is start value for the loop // @returns the location in arr export findmaxup(float [] arr, float ylv, float mindis, int index)=> ret = 0 for x = index to (index < array.size(arr) ? array.size(arr) - 1 : na) by 2 if array.get(arr, x) < ylv or (array.get(arr, x) - ylv >= mindis) ret := array.get(arr, x) < ylv ? 0 : x break ret // @function checks arr array and if distance is greater than mindis // @param ylv is used to check level // @param arr is an array which keeps the values to compare // @param mindis is the distance // @param index is start value for the loop // @returns the location in arr export findmaxdown(float [] arr, float ylv, float mindis, int index)=> ret = 0 for x = index to (index < array.size(arr) ? array.size(arr) - 1 : na) by 2 if array.get(arr, x) > ylv or (ylv - array.get(arr, x) >= mindis) ret := array.get(arr, x) > ylv ? 0 : x break ret // @function used find right level // @param x and xl is used for x // @param a and al is used for a // @returns xl for x export fxl(float x, float xl, float a, float al, float b) => len = al - xl float slope = (a - x) / len float vline = a - slope ret = xl for t = 1 to len by 1 if slope > 0 and vline < b or slope < 0 and vline > b ret := al - t break vline := vline - slope math.round(ret) // @function used find minmax value from the array // @param mvar is used to search which part // @returns levels and ind export gmm(float [] marray, int mvar) => float ma = na float mi = na int ind = mvar == 1 ? array.indexof(marray, array.min(marray)) : array.indexof(marray, array.max(marray)) if ind >= 0 ind -= (ind % 2) ma := array.get(marray, ind) mi := array.get(marray, ind + 1) ind := math.round(ind / 2) [ma, mi, ind] // @function checks checksmType using all values and the const arrays // @param mc_arr keeps c values // @param allvalues keeps all values variables // @param const_array keeps constant values // @param mh_arr keeps h values // @param mk_arr keeps l values // @returns dloc variable if all conditions met export checksmType(float [] allvalues, float [] const_array, float [] mc_arr, float [] mh_arr, float [] ml_arr) => float Dloc = na if isFine((array.get(allvalues, 2) - array.get(allvalues, 3)) / (array.get(allvalues, 2) - array.get(allvalues, 1)), array.get(const_array, 0), array.get(const_array, 1)) and isFine((array.get(allvalues, 3) - array.get(allvalues, 4)) / (array.get(allvalues, 3) - array.get(allvalues, 2)), array.get(const_array, 0), array.get(const_array, 1)) and (array.get(allvalues, 1) - array.get(allvalues, 0)) / (array.get(allvalues, 1) - array.get(allvalues, 2)) > 1. // check first part slp = (array.get(allvalues, 3) - array.get(allvalues, 1)) / (array.get(allvalues, 7) - array.get(allvalues, 5)) ln = array.get(allvalues, 1) + slp firstpart = true len1 = math.round(bar_index - array.get(allvalues, 5)) len12 = bar_index - array.get(allvalues, 7) ddd = array.get(allvalues, 9) hl_array1 = ddd == 1 ? mh_arr : ml_arr for k = len1 - 1 to 1 by 1 if k > len12 if array.get(hl_array1, k) * ddd > ln * ddd firstpart := false break else if array.get(mc_arr, k) * ddd > ln * ddd firstpart := false break ln := ln + slp if firstpart slp2 = (array.get(allvalues, 4) - array.get(allvalues, 2)) / (array.get(allvalues, 8) - array.get(allvalues, 6)) ln2 = array.get(allvalues, 2) + slp2 len22 = math.round(bar_index - array.get(allvalues, 6)) len23 = bar_index - array.get(allvalues, 8) Dloc := ln hl_array2 = ddd == 1 ? ml_arr : mh_arr for k = len22 - 1 to 1 by 1 if k > len23 if array.get(hl_array2, k) * ddd < ln2 * ddd Dloc := na break else if array.get(mc_arr, k) * ddd < ln2 * ddd Dloc := na break ln2 := ln2 + slp2 Dloc // @function removes the element if the condition is not met // @param cond the condition to check // @param allina keeps constant values // @param allinp the array which the function removes the element // @param add is the index for the arrays // @returns null export checkcondtype1(float cond, float [] allina, int [] allinp, int add)=> for x = array.size(allinp) - 1 to 0 index = 22 * (array.get(allinp, x) - 1) + add if cond < array.get(allina, index) or cond > array.get(allina, index + 1) array.remove(allinp, x) // @function removes the element if the condition is not met // @param cond the condition to check // @param allina keeps constant values // @param allinp the array which the function removes the element // @param add is the index for the arrays // @returns null export checkcondtype2(float cond, float [] allina, int [] allinp, int add)=> for x = array.size(allinp) - 1 to 0 index = 12 * (array.get(allinp, x) - 1) + add if cond < array.get(allina, index) or cond > array.get(allina, index + 1) array.remove(allinp, x) // @function checks type1 values and locs using thiscond and the arrays that keeps the values // @param thiscond keeps if enabled // @param drw condition to draw // @param index used as index for the arrays // @param xtod keeps all values // @param allina keeps constant values // @param mpp keep the valus if there is any suitable // @param mppl keep the locs if there is any suitable // @param D is the last point // @param sd keeps the sd // @returns null getOnePPType1(bool thiscond, bool drw, int index, float [] xtod, float [] allina, float [] mpp, float [] mppl, float D, int sd)=> for x = 0 to (thiscond ? array.size(xtod) - 1 : na) by 10 [ma, mi] = CheckRtype1(array.from(array.get(xtod, x + 6), array.get(xtod, x + 4), array.get(xtod, x + 2), array.get(xtod, x)), allina, index) if mi > 0 and ma >= mi if sd == 1 and D < mi or sd == -1 and D > ma array.set(mpp, index * 2, ma) array.set(mpp, index * 2 + 1, mi) if drw setPPL(mppl, xtod, x, sd, (sd == 1 ? mi : ma)) break // @function checks type2 values and locs using thiscond and the arrays that keeps the values // @param thiscond keeps if enabled // @param drw condition to draw // @param index used as index for the arrays // @param xtod keeps all values // @param allina keeps constant values // @param mpp keep the valus if there is any suitable // @param mppl keep the locs if there is any suitable // @param D is the last point // @param sd keeps the sd // @returns null getOnePPType2(bool thiscond, bool drw, int index, float [] xtod, float [] allina, float [] mpp, float [] mppl, float D, int sd)=> for x = 0 to (thiscond ? array.size(xtod) - 1 : na) by 10 [ma, mi] = CheckRtype2(array.from(array.get(xtod, x + 6), array.get(xtod, x + 4), array.get(xtod, x + 2), array.get(xtod, x)), allina, index) if mi > 0 and ma >= mi if sd == 1 and D < mi or sd == -1 and D > ma array.set(mpp, index * 2, ma) array.set(mpp, index * 2 + 1, mi) if drw setPPL(mppl, xtod, x, sd, (sd == 1 ? mi : ma)) break // @function search all types according to thiscond array // @param thiscond is the array that keeps if element is enabled // @param allina keeps constant values // @param xtod keeps all values // @param D is the last point // @param sd keeps the sd // @param drw keeps if it's enabled or not // @returns pp and ppl arrays export getpps(bool [] thiscond, float [] allina, float [] xtod, float D, int sd, bool drw) => pp = array.new_float(40, na) ppl = array.new_float(0) getOnePPType1(array.get(thiscond, 0), drw, 1, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 1), drw, 2, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 2), drw, 3, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 3), drw, 4, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 4), drw, 5, xtod, allina, pp, ppl, D, sd) getOnePPType2(array.get(thiscond, 5), drw, 6, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 6), drw, 7, xtod, allina, pp, ppl, D, sd) getOnePPType1(array.get(thiscond, 7), drw, 8, xtod, allina, pp, ppl, D, sd) [pp, ppl] // @function finds all possible points by using allpoints array // @param allpoints contains all points in it // @param side keeps the current side // @param mplen keeps the length of mp // @param mploc keeps the location of mp // @returns apat array that contains possible points export getthepoints(float [] allpoints, int side, int mplen, int mploc) => // find max X location to search lastpoint = 12 for x = 11 to array.size(allpoints) - 1 by 2 if bar_index - array.get(allpoints, x) > mploc break lastpoint := x + 1 apat = array.new_int(0) float lastmain = array.get(allpoints, 0) float lastp = array.get(allpoints, 2) for c = 2 to lastpoint - 8 by 4 if side == 1 and array.get(allpoints, c - 2) > lastmain or side == -1 and array.get(allpoints, c - 2) < lastmain break if side == 1 and array.get(allpoints, c) <= lastp or side == -1 and array.get(allpoints, c) >= lastp array.push(apat, c) array.push(apat, 0) array.push(apat, 0) array.push(apat, 0) array.push(apat, 0) lastp := array.get(allpoints, c) lastp if array.size(apat) >= 5 for y = 0 to array.size(apat) - 1 by 5 c = array.get(apat, y) lastmain := array.get(allpoints, c) lastp := array.get(allpoints, c + 2) first = true for b = c + 2 to lastpoint - 6 by 4 if first first := false array.set(apat, y + 1, b) else if side == 1 and array.get(allpoints, b - 2) < lastmain or side == -1 and array.get(allpoints, b - 2) > lastmain break if side == 1 and array.get(allpoints, b) >= lastp or side == -1 and array.get(allpoints, b) <= lastp lastp := array.get(allpoints, b) array.push(apat, c) array.push(apat, b) array.push(apat, 0) array.push(apat, 0) array.push(apat, 0) for y = 0 to array.size(apat) - 1 by 5 b = array.get(apat, y + 1) if b == 0 continue lastmain := array.get(allpoints, b) lastp := array.get(allpoints, b + 2) first = true c = 0 for a = b + 2 to lastpoint - 4 by 4 if first c := array.get(apat, y) first := false array.set(apat, y + 2, a) else if side == 1 and array.get(allpoints, a - 2) > lastmain or side == -1 and array.get(allpoints, a - 2) < lastmain break if side == 1 and array.get(allpoints, a) <= lastp or side == -1 and array.get(allpoints, a) >= lastp lastp := array.get(allpoints, a) array.push(apat, c) array.push(apat, b) array.push(apat, a) array.push(apat, 0) array.push(apat, 0) for y = 0 to array.size(apat) - 1 by 5 a = array.get(apat, y + 2) if a == 0 continue lastmain := array.get(allpoints, a) lastp := array.get(allpoints, a + 2) first = true b = 0 c = 0 for x = a + 2 to lastpoint - 1 by 4 if first c := array.get(apat, y) b := array.get(apat, y + 1) first := false array.set(apat, y + 3, x) array.set(apat, y + 4, x) else if side == 1 and array.get(allpoints, x - 2) < lastmain or side == -1 and array.get(allpoints, x - 2) > lastmain break if side == 1 and array.get(allpoints, x) >= lastp or side == -1 and array.get(allpoints, x) <= lastp lastp := array.get(allpoints, x) array.push(apat, c) array.push(apat, b) array.push(apat, a) array.push(apat, x) array.push(apat, x) for y = array.size(apat) - 5 to (array.size(apat) >= 5 ? 0 : na) by 5 if array.size(apat) < 5 break p1 = array.get(allpoints, array.get(apat, y) + 1) p2 = array.get(allpoints, array.get(apat, y + 1) + 1) p3 = array.get(allpoints, array.get(apat, y + 2) + 1) p4 = array.get(allpoints, array.get(apat, y + 3) + 1) if array.get(apat, y + 4) == 0 or bar_index == p1 or p1 == p2 or p2 == p3 or p3 == p4 or bar_index - p4 < mplen array.remove(apat, y + 4) array.remove(apat, y + 3) array.remove(apat, y + 2) array.remove(apat, y + 1) array.remove(apat, y) continue xlev = array.get(allpoints, array.get(apat, y + 3)) minmax = xlev mima = array.get(allpoints, array.get(apat, y + 2)) > xlev ? true : false start = array.get(apat, y + 3) + 2 for x = start to array.size(allpoints) > start ? array.size(allpoints) - 1 : na by 2 if mima and array.get(allpoints, x) > minmax or not mima and array.get(allpoints, x) < minmax minmax := array.get(allpoints, x) array.set(apat, y + 4, x) if mima and array.get(allpoints, x) < xlev or not mima and array.get(allpoints, x) > xlev break apat
Volatility
https://www.tradingview.com/script/JE1mqKCL-Volatility/
Electrified
https://www.tradingview.com/u/Electrified/
167
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // @version=5 // @description Functions for determining if volatility (true range) is within or exceeds normal. library('Volatility') import Electrified/MovingAverages/3 as MA import Electrified/SessionInfo/9 as Session import Electrified/GapDetection/5 as Gap import Electrified/DataCleaner/10 as Data // @field value The current value. // @field average The the average value . // @field normal The normal value within one standard deviation. // @field deviation The relative value compared to normal where anything below 1 is considered within normal and each whole number above indicates the deviation away from normal. export type Volatility float value float average float normal float deviation // The "True Range" (ta.tr) is used for measuring volatility. // Values are normalized by the volume adjusted weighted moving average (VAWMA) to be more like percent moves than price. trFormula(float H, float L, float Cp) => math.max(H - L, math.abs(H - Cp), math.abs(L - Cp)) ////////////////////////////////////////////////// // @function Calculates the true range for a given span of bars. // @param span Number of bars measure the true range. // @param quantized When true, the true range is calculated once for every span. When false (default), the true range is calulated for the span on every bar. export calcTrueRange( simple int span = 1, simple bool quantized = false) => if span < 1 runtime.error("The 'span' value must be at least 1.") float(na) else if span == 1 ta.tr else if quantized var bar = 0 bar += 1 var float tr = na if bar % span == 0 tr := trFormula( ta.highest(high, span), ta.lowest(low, span), close[span]) tr else trFormula( ta.highest(high, span), ta.lowest(low, span), close[span]) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Calculates the volatility based upon the true range. // @param len Number of bars measure the deviation. // @param len maxDev deviation before considered an outlier. // @param span Number of bars measure the true range. // @param quantized When true, the true range is calculated once for every span. When false (default), the true range is calulated for the span on every bar. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. export fromTrueRange( simple int len, simple float maxDev, simple int span = 1, simple bool quantized = false, simple bool useWma = false, simple int smoothing = 0) => tr = calcTrueRange(span, quantized) cleaned = Data.naOutliers(tr, len, maxDev, useWma, smoothing) d = Data.stdev(cleaned, len, useWma, smoothing) level1 = d.mean + d.stdev dev = if tr < level1 // Is normal? tr / level1 else // Is not normal? level1 + (tr - level1) / d.stdev Volatility.new(tr, d.mean, level1, dev) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns the normal upper range of volatility and the normal gap value. // @param len Number of bars to measure volatility. // @param maxDeviation The limit of volatility before considered an outlier. // @param level The amount of standard deviation after cleaning outliers to be considered within normal. // @param gapDays The number of days in the past to measure overnight gap volaility. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @param volatility The value to use as a volatility measure. Default is (ta.tr) the "True Range". // @returns [atr + stdev * level, Gap.normal(gapDays, spec, res)] export normalWithGap( simple int len, simple float maxDeviation = 3, simple float level = 1, simple int gapDays = 50, simple string spec = session.regular, simple string res = '1440', series float volatility = ta.tr) => var values = array.new_float() vawma = MA.vawma(len) tr = volatility / vawma // VAWMA is used to normalize the values to a price paid per share. Closer to % than price. stdRaw = ta.stdev(tr, len) avgRaw = ta.sma(tr, len) if tr < avgRaw + maxDeviation * stdRaw array.push(values, tr) if array.size(values)>len array.shift(values) atr = array.avg(values) stdev = array.stdev(values) latest = atr + stdev * level [latest * vawma, Gap.normal(gapDays, 2, spec, res) * level] /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns the normal upper range of volatility. Compensates for overnight gaps within a regular session. // @param len Number of bars to measure volatility. // @param maxDeviation The limit of volatility before considered an outlier. // @param level The amount of standard deviation after cleaning outliers to be considered within normal. // @param gapDays The number of days in the past to measure overnight gap volaility. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @param volatility The value to use as a volatility measure. Default is (ta.tr) the "True Range". export normal( simple int len, simple float maxDeviation = 3, simple float level = 1, simple int gapDays = 50, simple string spec = session.regular, simple string res = '1440', series float volatility = ta.tr) => [n, g] = normalWithGap(len, maxDeviation, level, gapDays, spec, res, volatility) syminfo.session == session.regular and Session.isFirstBar() ? g : n /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns true if the volatility (true range) is within normal levels. Compensates for overnight gaps within a regular session. // @param len Number of bars to measure volatility. // @param maxDeviation The limit of volatility before considered an outlier. // @param level The amount of standard deviation after cleaning outliers to be considered within normal. // @param gapDays The number of days in the past to measure overnight gap volaility. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @param volatility The value to use as a volatility measure. Default is (ta.tr) the "True Range". export isNormal( simple int len, simple float maxDeviation = 3, simple float level = 1, simple int gapDays = 50, simple string spec = session.regular, simple string res = '1440', series float volatility = ta.tr) => volatility < normal(len, maxDeviation, level, gapDays, spec, res) /////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns ratio of the current value to the normal value. Compensates for overnight gaps within a regular session. // @param len Number of bars to measure volatility. // @param maxDeviation The limit of volatility before considered an outlier. // @param level The amount of standard deviation after cleaning outliers to be considered within normal. // @param gapDays The number of days in the past to measure overnight gap volaility. // @param spec session.regular (default), session.extended or other time spec. // @param res The resolution (default = '1440'). // @param volatility The value to use as a volatility measure. Default is (ta.tr) the "True Range". export severity( simple int len, simple float maxDeviation = 3, simple float level = 1, simple int gapDays = 50, simple string spec = session.regular, simple string res = '1440', series float volatility = ta.tr) => volatility / normal(len, maxDeviation, level, gapDays, spec, res) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // Example //////////////////////////////////////// /////////////////////////////////////////////////// days = input.int(30, 'Days to Measure', tooltip='The number of days to use in measuring volatility.') maxDev = input.float(2, 'Max Deviation', minval=1, tooltip='The limit of volatility before considered an outlier.') level = input.float(2, 'Standard Deviation Level', minval=1, tooltip='The amount of standard deviation after cleaning outliers to be considered within normal.') int len = days * 390 / timeframe.multiplier volatility = ta.tr normalVol = normal(len, maxDev, level, days) plot(volatility, 'Volatility', color.red) plot(normalVol, 'Volatility Normal', color.green)
DataCleaner
https://www.tradingview.com/script/rv0pbZsA-DataCleaner/
Electrified
https://www.tradingview.com/u/Electrified/
23
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // @version=5 // @description Functions for acquiring outlier levels and deriving a cleaned version of a series. library("DataCleaner") ////////////////////////////////////////////////// // @type Contains the mean (average) and the value of the standard deviation. // @field mean The mean (average). // @field standard The standard deviation. export type Deviation float mean float stdev ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @description This WMA handles NA values wma( series float src, simple int len) => sum = 0.0 count = 0 last = len - 1 for i = 0 to last s = src[i] if not na(s) m = last - i + 1 // triangular multiple count += m sum += s * m count == 0 ? na : sum/count ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Calculates and returns both the mean and the standard deviation. // @param src The series to use for the calculation. // @param len The length of the calculation. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. export stdev( series float src, simple int len, simple bool useWma = false, simple int smoothing = 0) => prev = src[1] // ignore current in measurment as it could throw off result. mean = useWma ? wma(prev, len) : ta.sma(prev, len) diff = prev - mean diff2 = diff * diff variance = useWma ? wma(diff2, len) : ta.sma(diff2, len) stdev = math.sqrt(variance) if smoothing > 0 mean := ta.sma(mean, smoothing + 1) stdev := ta.sma(stdev, smoothing + 1) Deviation.new(mean, stdev) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Calculates and returns both the mean and the standard deviation. // @param src The array to use for the calculation. export stdev(series float[] src) => sum = 0.0 count = 0 for e in src if not na(e) sum += e count += 1 for e in src if not na(e) sum += e count += 1 mean = sum / count diff2sum = 0.0 for e in src if not na(e) diff = e - mean diff2 = diff * diff diff2sum += diff2 variance = diff2sum / count stdev = math.sqrt(variance) Deviation.new(mean, stdev) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the (standard deviation) outlier level for a given series. // @param src The series to average and add a multiple of the standard deviation to. // @param len The The number of bars to measure. // @param level The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. // @returns The average of the series plus the multiple of the standard deviation. export outlierLevel( series float src, simple int len, simple float level, simple bool useWma = false, simple int smoothing = 0) => if level == 0 runtime.error('Passing a level of (0) zero to "level" is simply the average.') d = stdev(src, len, useWma, smoothing) d.mean + d.stdev * level ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns only values that are within the maximum deviation. // @param src The series to filter results from. // @param len The The number of bars to measure. // @param maxDeviation The maximum deviation before considered an outlier. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. export naOutliers( series float src, simple int len, simple float maxDeviation = 4, simple bool useWma = false, simple int smoothing = 0)=> if maxDeviation == 0 runtime.error('Passing a level of (0) zero to "maxDeviation" is simply the average.') d = stdev(src, len, useWma, smoothing) dev = d.stdev * maxDeviation src > d.mean + dev or src < d.mean - dev ? na : src ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns the source value adjusted by its standard deviation. // @param src The series to measure. // @param len The number of bars to measure the standard deviation. // @param maxDeviation The maximum deviation before considered an outlier. // @param baseline The value considered to be at center. Typically zero. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. export normalize( series float src, simple int len, simple int maxDeviation = 4, float baseline = 0, simple bool useWma = false, simple int smoothing = 0) => cleaned = naOutliers(src, len, maxDeviation, useWma, smoothing) d = stdev(src, len, useWma, smoothing) src / (src >= baseline ? (d.mean + d.stdev) : math.abs(d.mean - d.stdev)) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns an array representing the result series with (outliers provided by the source) removed. // @param src The source series to read from. // @param result The result series. // @param len The maximum size of the resultant array. // @param maxDeviation The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary. // @returns An array containing the cleaned series. export cleanUsing( series float src, series float result, simple int len, simple float maxDeviation) => var cleaned = array.new_float() if maxDeviation == 0 runtime.error('Cannot clean a series with a "maxDeviation" of (0) zero.') cleaned else // Hold the previous value so it's not included in the set yet. var raw = array.new_float() var level = outlierLevel(src, len, maxDeviation) // Is the value in bounds? Add it to the series. if(maxDeviation > 0 and src < level or maxDeviation < 0 and src > level) array.push(cleaned, result) // Maxed out results? if(array.size(cleaned) > len) array.shift(cleaned) level := outlierLevel(src, len, maxDeviation) cleaned ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns an array representing the source series with outliers removed. // @param src The source series to read from. // @param len The maximum size of the resultant array. // @param maxDeviation The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary. // @returns An array containing the cleaned series. export clean( series float src, simple int len, simple float maxDeviation) => cleanUsing(src, src, len, maxDeviation) ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns an array representing the source array with outliers removed. // @param src The source series to read from. // @param maxDeviation The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary. // @returns An array containing the cleaned series. export cleanArray( float[] src, simple float maxDeviation) => if array.size(src)==0 src else d = stdev(src) cleaned = array.new_float() last = array.size(src) - 1 level = d.stdev * maxDeviation hi = d.mean + level lo = d.mean - level for i = 0 to last v = array.get(src, i) if lo < v and v < hi array.push(cleaned, v) cleaned ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Returns an array representing the source array with outliers removed. // @param src The array to set outliers to N/A. // @param maxDeviation The maximum deviation before considered an outlier. // @returns True if there were any outliers; otherwise false. export naArrayOutliers( float[] src, simple float maxDeviation) => if array.size(src)==0 false else d = stdev(src) last = array.size(src) - 1 level = d.stdev * maxDeviation hi = d.mean + level lo = d.mean - level bool modified = false for i = 0 to last v = array.get(src, i) if lo > v or v > hi array.set(src, i, na) modified := true modified ////////////////////////////////////////////////// ////////////////////////////////////////////////// // @function Gets the (standard deviation) outlier level for a given series after a single pass of removing any outliers. // @param src The series to average and add a multiple of the standard deviation to. // @param len The The number of bars to measure. // @param level The positive or negative multiple of the standard deviation to apply to the average. A positive number will be the upper boundary and a negative number will be the lower boundary. // @param maxDeviation The optional standard deviation level to use when cleaning the series. The default is the value of the provided level. // @param useWma When true, the calulcation is done using an improved weighted moving average to avoid giving significance to older values. // @param smoothing The number of extra bars to help in smoothing out the result so that large spikes dont' occur from recent data. // @returns The average of the series plus the multiple of the standard deviation. export outlierLevelAdjusted( series float src, simple int len, simple float level, simple float maxDeviation = 0, simple bool useWma = false, simple int smoothing = 0) => if level == 0 runtime.error('Passing a level of (0) zero to "level" is simply the average.') cleaned = naOutliers(src, len, maxDeviation==0 ? level : maxDeviation, useWma, smoothing) d = stdev(cleaned, len, useWma, smoothing) d.mean + d.stdev * level ////////////////////////////////////////////////// candleHeight = high - low src = input.source(close, "Source") source = input.bool(false, "Use Source instead of High-Low") ? src : candleHeight len = input.int(200, "Length") maxDev = input.float(2, "Max Deviation", minval=1) level = input.float(4, "Max Deviation After Cleaning", minval=1) wmaYes = input.bool(false, "Use WMA instead of SMA") smoothing = input.int(10, "Smoothing", 0) //plot(ta.atr(len), "ATR", color.red) plot(candleHeight, "Candle Height", color.yellow) before = outlierLevel(candleHeight, len, maxDev, wmaYes, smoothing) plot(before, "Deviation Before Adjustment", color.orange) after = outlierLevelAdjusted(candleHeight, len, level, 0, wmaYes, smoothing) plot(after, "Deviation After Adjustment", color.green)
FunctionZigZagMultipleMethods
https://www.tradingview.com/script/RQfqaRAJ-FunctionZigZagMultipleMethods/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
342
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description ZigZag Multiple Methods. library(title='FunctionZigZagMultipleMethods') string m_000 = '(MANUAL) Percent price move over X * Y' string m_001 = 'Percent price move over atr(X) * Y' string m_002 = 'Percent price move over max(tr) * Y' string m_003 = 'high or low pivot(X, Y)' string m_004 = 'Price Action' // @function Helper methods enumeration. // @param idx int, index of method, range 0 to 4. // @returns string export method (int idx) => //{ switch (idx) (0) => m_000 (1) => m_001 (2) => m_002 (3) => m_003 (4) => m_004 => m_000 //} // @function Multiple method ZigZag. // @param method string, default='(MANUAL) Percent price move over X * Y', method for zigzag. // @param value_x float, x value in method. // @param value_y float, y value in method. // @returns tuple with: // zigzag float // direction // reverse_line float // realtimeofpivot int export function (string method, float value_x, float value_y) => //{ var float _percent = na if method == m_001 _percent := ta.sma(ta.tr(true), int(value_x)) / open * value_y //ta.atr() requires simple int input.. else if method == m_002 float _tr = (ta.tr / open) * value_y if na(_percent) _percent := _tr if _tr > _percent _percent := _tr else _percent := value_x * value_y // direction after last pivot var bool _direction = na // track highest price since last lower pivot var float _hprice = na // track lowest price since last higher pivot var float _lprice = na // zigzag variable for ploting var float _zz = na // real pivot time var int _tz = na var int _htime = na var int _ltime = na // reverse line var float _reverse_line = 0.0 // range needed for reaching reversal threshold float _reverse_range = 0.0 // pivots high / low for method m_003 // string m_003 = 'high or low pivot(X, Y)' _pivot_h = ta.pivothigh(value_x, value_y) _pivot_l = ta.pivotlow(value_x, value_y) if bar_index >= 1 if na(_direction) _direction := true _reverse_range := nz(_zz[1]) * _percent if _direction _lprice := na _ltime := time if na(_hprice) if high < high[1] _hprice := high[1] _htime := time[1] else _hprice := high _htime := time else if high >= _hprice _hprice := high _htime := time if method == m_003 _reverse_line := _hprice if _pivot_h _zz := _hprice _tz := _htime _direction := false else if method == m_004 _reverse_line := _hprice if high < high[1] and (low < low[1] or (close-low < (high-low) * 0.5)) //down or engulfing closing low if low < low[1] _lprice := low _ltime := time else _lprice := low[1] _ltime := time[1] _zz := _hprice _tz := _htime _direction := false else _reverse_line := (_hprice - _reverse_range) if close < _reverse_line _zz := _hprice _tz := _htime _direction := false else//if not _direction _hprice := na _htime := na if na(_lprice) if low > low[1] _lprice := low[1] _ltime := time[1] else _lprice := low _ltime := time else if low <= _lprice _lprice := low _ltime := time if method == m_003 _reverse_line := _lprice if _pivot_l _zz := _lprice _tz := _ltime _direction := true else if method == m_004 _reverse_line := _lprice if high > high[1] and (low > low[1] or (close-low > (high-low) * 0.5))//up or engulfing closing high if high > high[1] _hprice := high _htime := time else _hprice := high[1] _htime := time[1] _zz := _lprice _tz := _ltime _direction := true else _reverse_line := (_lprice + _reverse_range) if close > _reverse_line _zz := _lprice _tz := _ltime _direction := true [_zz, _direction, _reverse_line, _tz] //{ usage: string zigzag_method = input.string( defval=m_000, title="Method to use for the zigzag:", options=[m_000, m_001, m_002, m_003, m_004], group='ZigZag Options:' ) float param_x = input.float(defval=1.0, title='parameter X', group='ZigZag Options:') float param_y = input.float(defval=1.0, title='parameter Y', group='ZigZag Options:') [price_a, is_up, reverse, _rl_time] = function(zigzag_method, param_x, param_y) plot(ta.change(price_a)!=0?price_a:na) //{ remarks: //}}}
FunctionPeakDetection
https://www.tradingview.com/script/FKWXIRix-FunctionPeakDetection/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
145
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Method used for peak detection, similar to MATLAB peakdet method library(title='FunctionPeakDetection') import RicardoSantos/ArrayGenerate/1 as ag // @function Method for detecting peaks. // @param sample_x float array, sample with indices. // @param sample_y float array, sample with data. // @param delta float, positive threshold value for detecting a peak. // @returns tuple with found max/min peak indices. export function (float[] sample_x, float[] sample_y, float delta) => //{ int _size_x = array.size(sample_x) int _size_y = array.size(sample_y) // switch (_size_x != _size_y) => runtime.error('FunctionPeakDetection -> function(): "sample_x" and "sample_y" size does not match.') (delta < 0.0) => runtime.error('FunctionPeakDetection -> function(): "delta" must be positive.') // float[] _maxtab = array.new_float() float[] _mintab = array.new_float() float _mn = +1.0e308 float _mx = -1.0e308 float _mnpos = na float _mxpos = na bool _look_for_max = true for _i = 0 to _size_x-1 _current = array.get(sample_y, _i) if _current > _mx _mx := _current _mxpos := array.get(sample_x, _i) if _current < _mn _mn := _current _mnpos := array.get(sample_x, _i) if _look_for_max if _current < (_mx - delta) array.push(_maxtab, _mxpos) _mn := _current _mnpos := array.get(sample_x, _i) _look_for_max := false else if _current > (_mn + delta) array.push(_mintab, _mnpos) _mx := _current _mxpos := array.get(sample_x, _i) _look_for_max := true [_maxtab, _mintab] //{ reference: // https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/utilities.py#L33 //{ usage: // this is just a example, label garbage collection is not taken in account.. x = bar_index < 101 ? array.from(0.0) : ag.sequence_from_series(bar_index, 100, 0, true) y = bar_index < 101 ? array.from(0.0) : ag.sequence_from_series(close, 100, 0, true) delta = array.stdev(y) [mx, mn] = function(x, y, delta) if array.size(mx) > 0 for _i = 0 to array.size(mx)-1 label.new(int(array.get(mx, _i)), close[bar_index-array.get(mx, _i)], 'V') if array.size(mn) > 0 for _i = 0 to array.size(mn)-1 label.new(int(array.get(mn, _i)), close[bar_index-array.get(mn, _i)], 'A', style=label.style_label_up) plot(close) //}}
MLActivationFunctions
https://www.tradingview.com/script/NBsglstB-MLActivationFunctions/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
31
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Activation functions for Neural networks. library(title='MLActivationFunctions') // reference: // https://www.educba.com/perceptron-learning-algorithm/ // https://blog.primen.dk/basic-neural-network-model-insights/ // https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html // https://en.wikipedia.org/wiki/Artificial_neural_network // https://blog.primen.dk/basic-neural-network-code-example-java/ // https://mlfromscratch.com/activation-functions-explained/ // https://www.analyticssteps.com/blogs/7-types-activation-functions-neural-network // http://binaryplanet.org/category/activation-function/ // https://keras.io/api/layers/activations/ // @function Basic threshold output classifier to activate/deactivate neuron. // @param value float, value to process. // @returns float export binary_step (float value) => //{ value > 0.0 ? 1.0 : 0.0 //{ usage: //{ remarks: //}}} // @function Input is the same as output. // @param value float, value to process. // @returns float export linear (float value) => //{ value //{ usage: //{ remarks: //}}} // @function Sigmoid or logistic function. // @param value float, value to process. // @returns float export sigmoid (float value) => //{ 1.0 / (1.0 + math.exp(-value)) //{ usage: //{ remarks: //}}} // @function Derivative of sigmoid function. // @param value float, value to process. // @returns float export sigmoid_derivative (float value) => //{ float _f = sigmoid(value) _f * (1.0 - _f) //{ usage: //{ remarks: //}}} // @function Hyperbolic tangent function. // @param value float, value to process. // @returns float export tanh (float value) => //{ float _ep = math.exp(value) float _en = math.exp(-value) (_ep - _en) / (_ep + _en) //{ usage: //{ remarks: //}}} // @function Hyperbolic tangent function derivative. // @param value float, value to process. // @returns float export tanh_derivative (float value) => //{ 1.0 - math.pow(tanh(value), 2) //{ usage: //{ remarks: //}}} // @function Rectified linear unit (RELU) function. // @param value float, value to process. // @returns float export relu (float value) => //{ value <= 0.0 ? 0.0 : value //{ usage: //{ remarks: //}}} // @function RELU function derivative. // @param value float, value to process. // @returns float export relu_derivative (float value) => //{ value <= 0 ? 0 : 1.0 //{ usage: //{ remarks: //}}} // @function Leaky RELU function. // @param value float, value to process. // @returns float export leaky_relu (float value) => //{ value < 0.0 ? 0.01 * value : value //{ usage: //{ remarks: //}}} // @function Leaky RELU function derivative. // @param value float, value to process. // @returns float export leaky_relu_derivative (float value) => //{ value < 0 ? 0.01 : 1.0 //{ usage: //{ remarks: //}}} // @function RELU-6 function. // @param value float, value to process. // @returns float export relu6 (float value) => //{ switch (value < 0.0) => 0.01 * value (value > 6.0) => 6.0 => value //{ usage: //{ remarks: //}}} // @function Softmax function. // @param value float array, values to process. // @returns float export softmax (float[] values) => //{ int _size_v = array.size(values) switch _size_v < 1 => runtime.error(str.format('MLActivationFunctions -> softmax(): "values" has the wrong size: {0}', _size_v)) float[] _tmp = array.copy(values) for _i = 0 to (_size_v - 1) array.set(_tmp, _i, math.exp(array.get(values, _i))) float _tot = array.sum(_tmp) for _i = 0 to (_size_v - 1) array.set(_tmp, _i, array.get(_tmp, _i) / _tot) _tmp //{ usage: // var a = array.from(0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9) // var b = softmax(a) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str.tostring(b))//ok //{ remarks: //}}} // @function Softmax derivative function. // @param value float array, values to process. // @returns float export softmax_derivative (float[] values) => //{ int _size_v = array.size(values) switch _size_v < 1 => runtime.error(str.format('MLActivationFunctions -> softmax(): "values" has the wrong size: {0}', _size_v)) float[] _tmp = array.new_float(_size_v * _size_v, 0.0) for _i = 0 to (_size_v - 1) float _vi = array.get(values, _i) for _j = 0 to (_size_v - 1) float _vj = array.get(values, _j) if _i == _j array.set(_tmp, _j * _size_v + _i, _vi * (1.0 - _vi)) else array.set(_tmp, _j * _size_v + _i, -_vi * _vj) _tmp //{ usage: // var a = array.from(1.0, 2.0) // var b = softmax(a) // var c = softmax_derivative(b) // var str = str.format('a: {0}\nb: {1}\nc: {2}', str.tostring(a), str.tostring(b), str.tostring(c)) // if barstate.islastconfirmedhistory // label.new(bar_index, 0.0, str)//ok //{ remarks: // https://stackoverflow.com/questions/33541930/how-to-implement-the-softmax-derivative-independently-from-any-loss-function //}}} // @function Softplus function. // @param value float, value to process. // @returns float export softplus (float value) => //{ math.log(math.exp(value) + 1.0) //{ usage: // var a = array.from(-20.0, -1, 0, 1, 20) // if barstate.islastconfirmedhistory // b = array.new_float(5) // for _i = 0 to 4 // array.set(b, _i, softplus(array.get(a, _i))) // label.new(bar_index, 0.0, str.tostring(b))//ok //{ remarks: //}}} // @function Softsign function. // @param value float, value to process. // @returns float export softsign (float value) => //{ value / (math.abs(value) + 1.0) //{ usage: // var a = array.from(-1.0, 0, 1) // if barstate.islastconfirmedhistory // b = array.new_float(3) // for _i = 0 to 2 // array.set(b, _i, softsign(array.get(a, _i))) // label.new(bar_index, 0.0, str.tostring(b))//ok //{ remarks: //}}} // @function Exponential Linear Unit (ELU) function. // @param value float, value to process. // @param alpha float, default=1.0, predefined constant, controls the value to which an ELU saturates for negative net inputs. . // @returns float export elu (float value, float alpha=1.0) => //{ switch (value > 0.0) => value (value < 0.0) => alpha * (math.exp(value) - 1.0) => 0.0 //{ usage: //{ remarks: //}}} // @function Scaled Exponential Linear Unit (SELU) function. // @param value float, value to process. // @param alpha float, default=1.67326324, predefined constant, controls the value to which an SELU saturates for negative net inputs. . // @param scale float, default=1.05070098, predefined constant. // @returns float export selu (float value, float alpha=1.67326324, float scale=1.05070098) => //{ switch (value > 0) => scale * value (value < 0) => scale * alpha * (math.exp(value) - 1.0) => 0.0 //{ usage: //{ remarks: //}}} // @function Pointer to math.exp() function. // @param value float, value to process. // @returns float export exponential (float value) => //{ math.exp(value) //{ usage: //{ remarks: //}}} // @function Activation function. // @param name string, name of activation function. // @param value float, value to process. // @param alpha float, default=na, if required. // @param scale float, default=na, if required. // @returns float export function (string name, float value, float alpha=na, float scale=na) => //{ switch (name) ('binary step') => binary_step(value) ('linear') => linear(value) ('sigmoid') => sigmoid(value) ('tanh') => tanh(value) ('relu') => relu(value) ('leaky relu') => leaky_relu(value) ('relu 6') => relu6(value) // ('softmax') => value ('softplus') => softplus(value) ('softsign') => softsign(value) ('elu') => elu(value, alpha) ('selu') => selu(value, alpha, scale) ('exponential') => exponential(value) ('sin') => math.sin(value) => value //{ usage: //{ remarks: // TODO: improve selection of functions. //}}} // @function Derivative Activation function. // @param name string, name of activation function. // @param value float, value to process. // @param alpha float, default=na, if required. // @param scale float, default=na, if required. // @returns float export derivative (string name, float value, float alpha=na, float scale=na) => //{ switch (name) // ('binary step') => binary_step(value) // ('linear') => linear(value) ('sigmoid') => sigmoid_derivative(value) ('tanh') => tanh_derivative(value) ('relu') => relu_derivative(value) ('leaky relu') => leaky_relu_derivative(value) // ('relu 6') => relu6(value) // ('softmax') => value // ('softplus') => softplus(value) // ('softsign') => softsign(value) // ('elu') => elu(value, alpha) // ('selu') => selu(value, alpha, scale) // ('exponential') => exponential(value) ('sin') => math.cos(value) => value * (alpha + scale + 1.0)//just to use the parameters //{ usage: //{ remarks: // TODO: improve selection of functions. //}}}
Interpolation
https://www.tradingview.com/script/0NhkCzGJ-Interpolation/
Electrified
https://www.tradingview.com/u/Electrified/
31
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // Original Easing Functions: (c) 2001 Robert Penner http://robertpenner.com/easing/ // @version=5 // @description Functions for interpolating values. Can be useful in signal processing or applied as a sigmoid function. library('Interpolation') clamp(float k, bool unbound) => unbound ? k : k < 0 ? 0 : k > 1 ? 1 : k /////////////////////////////////////////////////// // @function Returns the linear adjusted value. // @param k A number (float) from 0 to 1 representing where the on the line the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export linear( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) offset + delta * m /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the quadratic (easing-in) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export quadIn( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) offset + delta * m * m /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the quadratic (easing-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export quadOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) offset + delta * m * (2 - m) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the quadratic (easing-in-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export quadInOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) * 2 f = if m <= 1 0.5 * m * m else m -= 1 -0.5 * (m * (m - 2) - 1) offset + delta * f /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the cubic (easing-in) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export cubicIn( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) offset + delta * m * m * m /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the cubic (easing-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export cubicOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) - 1 m := m * m * m + 1 offset + delta * m /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the cubic (easing-in-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export cubicInOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) * 2 f = if m <= 1 0.5 * m * m * m else m -= 2 0.5 * m * m * m + 2 offset + delta * f /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the exponential (easing-in) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export expoIn( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) switch m 0 => offset 1 => offset + delta => offset + delta * math.pow(1024, m - 1) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the exponential (easing-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export expoOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) switch m 0 => offset 1 => offset + delta => offset + delta * (1 - math.pow(2, -10*m)) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the exponential (easing-in-out) adjusted value. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export expoInOut( float k, float delta = 1, float offset = 0, simple bool unbound = false) => m = clamp(k, unbound) switch m 0 => offset 1 => offset + delta => m *= 2 f = m<=1 ? math.pow(1024, m - 1) : (-math.pow(2, -10*(m - 1)) + 2) offset + delta * f * 0.5 /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Returns the adjusted value by function name. // @param fn The name of the function. Allowed values: linear, quadIn, quadOut, quadInOut, cubicIn, cubicOut, cubicInOut, expoIn, expoOut, expoInOut. // @param k A number (float) from 0 to 1 representing where the on the curve the value is. // @param delta The amount the value should change as k reaches 1. // @param offset The start value. // @param unbound When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta). export using( simple string fn, float k, float delta = 1, float offset = 0, simple bool unbound = false) => switch fn "linear" => linear(k, delta, offset, unbound) "quadIn" => quadIn(k, delta, offset, unbound) "quadOut" => quadOut(k, delta, offset, unbound) "quadInOut" => quadInOut(k, delta, offset, unbound) "cubicIn" => cubicIn(k, delta, offset, unbound) "cubicOut" => cubicOut(k, delta, offset, unbound) "cubicInOut" => cubicInOut(k, delta, offset, unbound) "expoIn" => expoIn(k, delta, offset, unbound) "expoOut" => expoOut(k, delta, offset, unbound) "expoInOut" => expoInOut(k, delta, offset, unbound) => runtime.error("Unknown function name.") na /////////////////////////////////////////////////// /////////////////////////////////////////////////// // Demo var float bar = na day = time("D") if day != day[1] bar := 0 else bar += 1 float end = 390 / 2 / timeframe.multiplier // half bars per day float pos = bar / end fn = input.string("expoInOut", "Function", options=["linear", "quadIn", "quadOut", "quadInOut", "cubicIn", "cubicOut", "cubicInOut", "expoIn", "expoOut", "expoInOut"]) hline(0) hline(0.5) hline(1) plot(using(fn, pos))
Averages
https://www.tradingview.com/script/tYncfHar-Averages/
Electrified
https://www.tradingview.com/u/Electrified/
17
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Electrified (electrifiedtrading) // @version=5 // @description Contains utilities for generating averages from arrays. Useful for manipulated or cleaned data. library('Averages', true) /////////////////////////////////////////////////// // @function Calculates the triangular weighted average of a set of values where the last value has the highest weight. // @param src The array to derive the average from. // @param startingWeight The weight to begin with when calculating the average. Higher numbers will decrease the bias. export triangular( float[] src, simple int startingWeight = 1) => var float notAvailable = na len = array.size(src) if len == 0 notAvailable else sum = 0.0 total = 0 for i = 0 to len - 1 s = array.get(src, i) if not na(s) m = i + startingWeight // triangular multiple total += m sum += s * m total == 0 ? na : sum/total /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Calculates the weighted average of a set of values. // @param src The array to derive the average from. // @param weights The array containing the weights for the source. // @param weightDefault The default value to use when a weight is NA. export weighted( float[] src, float[] weights, simple float weightDefault = na) => var float notAvailable = na len = array.size(src) if len == 0 notAvailable else if len > array.size(weights) runtime.error("Weight array is shorter than the source.") notAvailable else sum = 0.0 total = 0.0 for i = 0 to len - 1 s = array.get(src, i) if not na(s) m = array.get(weights, i) if na(m) and not na(weightDefault) m := weightDefault if not na(m) total += m sum += s * m total == 0 ? na : sum/total /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Calculates the weighted average of a set of values where the last value has the highest triangular multiple. // @param src The array to derive the average from. // @param weights The array containing the weights for the source. // @param startingMultiple The multiple to begin with when calculating the average. Higher numbers will decrease the bias. export triangularWeighted( float[] src, float[] weights, simple float weightDefault = na, simple int startingMultiple = 1) => var float notAvailable = na len = array.size(src) if len == 0 notAvailable else if len > array.size(weights) runtime.error("Weight array is shorter than the source.") notAvailable else sum = 0.0 total = 0.0 for i = 0 to len - 1 s = array.get(src, i) if not na(s) w = array.get(weights, i) if na(w) and not na(weightDefault) w := weightDefault if not na(w) m = i + startingMultiple // triangular multiple wm = w * m total += wm sum += s * wm total == 0 ? na : sum/total /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Calculates the exponential average of a set of values where the last value has the highest weight. // @param src The array to derive the average from. export exponential(float[] src) => var float notAvailable = na len = array.size(src) if len == 0 notAvailable else var float emaPrev = na var float s = na float alpha = 2 / (len + 1) float a1 = 1 - alpha ema = emaPrev for i = 0 to len - 1 v = array.get(src, i) if not na(v) s := v ema := alpha * s + a1 * nz(ema) if i == 0 emaPrev := ema ema /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Creates an array from the provided series (oldest to newest). // @param src The array to derive from. // @param len The target length of the array. // @param omitNA If true, NA values will not be added to the array and the resultant array may be shorter than the target length. export arrayFrom( series float src, simple int len, simple bool omitNA = false) => var a = omitNA ? array.new_float() : array.new_float(len, na) if not omitNA or not na(src) array.push(a, src) if not omitNA or array.size(a) > len array.shift(a) a /////////////////////////////////////////////////// // Demo ema = exponential(arrayFrom(close, 60)) hlc3Array = arrayFrom(hlc3, 60) volArray = arrayFrom(volume, 60) vawma = triangularWeighted(hlc3Array, volArray) plot(ema, 'ema(60)', color.red) plot(vawma, 'vawma(60)', color.purple)
regress
https://www.tradingview.com/script/lWhoaf3L-regress/
voided
https://www.tradingview.com/u/voided/
9
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © voided //@version=5 // @description produces the slope (beta), y-intercept (alpha) and coefficient of determination for a linear regression library("regress") // @function regress: computes alpha, beta, and r^2 for a linear regression of y on x // @param x the explaining (independent) variable // @param y the dependent variable // @param len use the most recent "len" values of x and y // @returns [ alpha, beta, r2 ]: alpha is the x-intercept, beta is the slope, an r2 is the coefficient of determination export regress(float x, float y, int len) => // alpha, beta float[] x_ = array.new_float() float[] y_ = array.new_float() float[] xy = array.new_float() float[] x2 = array.new_float() for i = 0 to len by 1 x_i = x[i] y_i = y[i] array.push(x_, x_i) array.push(y_, y_i) array.push(xy, x_i * y_i) array.push(x2, math.pow(x_i, 2)) x_mean = array.avg(x_) y_mean = array.avg(y_) xy_mean = array.avg(xy) x2_mean = array.avg(x2) beta = (x_mean * y_mean - xy_mean) / (math.pow(x_mean, 2) - x2_mean) alpha = y_mean - beta * x_mean // coefficient of determination float[] squared_error_model = array.new_float() float[] squared_error_mean = array.new_float() for i = 0 to array.size(x_) by 1 m_i = beta * x[i] + alpha y_i = y[i] array.push(squared_error_model, math.pow(y_i - m_i, 2)) array.push(squared_error_mean, math.pow(y_i - y_mean, 2)) r2 = 1 - (array.sum(squared_error_model) / array.sum(squared_error_mean)) // return values: // // alpha: y-intercept of linear regression // beta: slope of linear regression // r_2: coefficient of determination [ alpha, beta, r2 ]
Library_RICH
https://www.tradingview.com/script/C558w3G9-Library-RICH/
Richard37
https://www.tradingview.com/u/Richard37/
10
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Richard37 //@version=5 // @description TODO: add library description here library("Library_RICH") // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export sum(float x, float y) => a = x + y // @function: ckeck if there are buy reversal conditions (divergences) in rsi // insure that the bar count since the last pivot low is within the specified range (min- and max range) // ckeck if there is a higher-low in rsi and lower-low in the price // (doubel) ckeck if buy reversal condition is true // @param : rsi value, pivot left lenght, pivot right lenght, min. and max. range // @returns : two values: bar-reversal-condition (true) and pivot low if is true export checkBuyReversal(float _rsiValue, int _pivotLeft, int _pivotRight, int _minRange, int _maxRange) => bool pivotLowTrue = na(ta.pivotlow(_rsiValue, _pivotLeft, _pivotRight)) ? false : true int barsCount = ta.barssince(pivotLowTrue[1] == true) bool inRange = _minRange <= barsCount and barsCount <= _maxRange bool RSI_HL_check = _rsiValue[_pivotRight] > ta.valuewhen(pivotLowTrue, _rsiValue[_pivotRight], 1) and inRange bool price_LL_check = close[_pivotRight] < ta.valuewhen(pivotLowTrue, close[_pivotRight], 1) bool buyReversalCondition = price_LL_check and RSI_HL_check and pivotLowTrue //buy condition is true [buyReversalCondition, pivotLowTrue] //[buyCondition, pivot_low_true] = checkBuyReversal(rsi_value, pivot_left, pivot_right) <- how to call the function with multiple results // @function: ckeck if there are buy cintinuation conditions (hidden divergences) in rsi // insure that the bar count since the last pivot low is within the specified range (min- and max range) // ckeck if there is a lower-low in rsi and higher-low in the price // (doubel) ckeck if buy continuation condition is true // @param : rsi value, pivot left lenght, pivot right lenght, min. and max. range // @returns : two results: bar-reversal-condition (true) and pivot low, if is true export checkBuyContinuation(float _rsiValue, int _pivotLeft, int _pivotRight, int _minRange, int _maxRange) => bool pivotLowTrue = na(ta.pivotlow(_rsiValue, _pivotLeft, _pivotRight)) ? false : true int barsCount = ta.barssince(pivotLowTrue[1] == true) bool inRange = _minRange <= barsCount and barsCount <= _maxRange bool RSI_LL_check = _rsiValue[_pivotRight] < ta.valuewhen(pivotLowTrue, _rsiValue[_pivotRight], 1) and inRange bool price_HL_check = close[_pivotRight] > ta.valuewhen(pivotLowTrue, close[_pivotRight], 1) bool buyContinuationCondition = price_HL_check and RSI_LL_check and pivotLowTrue //buy condition is true [buyContinuationCondition, pivotLowTrue] // @function: ckeck if there are sell reversal conditions (divergences) in rsi // insure that the bar count since the last pivot high is within the specified range (min- and max range) // ckeck if there is a lower-high in rsi and higher-high in the price // (doubel) ckeck if sell reversal condition is true // @param : rsi value, pivot left lenght, pivot right lenght, min. and max. range // @returns : two results: sell-reversal-condition (true) and pivot high, if is true export checkSellReversal(float _rsiValue, int _pivotLeft, int _pivotRight, int _minRange, int _maxRange) => bool pivotHighTrue = na(ta.pivothigh(_rsiValue, _pivotLeft, _pivotRight)) ? false : true int barsCount = ta.barssince(pivotHighTrue[1] == true) bool inRange = _minRange <= barsCount and barsCount <= _maxRange bool RSI_LH_check = _rsiValue[_pivotRight] < ta.valuewhen(pivotHighTrue, _rsiValue[_pivotRight], 1) and inRange bool price_HH_check = close[_pivotRight] > ta.valuewhen(pivotHighTrue, close[_pivotRight], 1) bool sellReversalCondition = price_HH_check and RSI_LH_check and pivotHighTrue //buy condition is true [sellReversalCondition, pivotHighTrue] // @function: ckeck if there are sell cointunuation conditions (divergences) in rsi // insure that the bar count since the last pivot high is within the specified range (min- and max range) // ckeck if there is a higher-high in rsi and lower-high in the price // (doubel) ckeck if sell continuation condition is true // @param : rsi value, pivot left lenght, pivot right lenght, min. and max. range // @returns : two results: sell-continuation-condition (true) and pivot high, if is true export checkSellContinuation(float _rsiValue, int _pivotLeft, int _pivotRight, int _minRange, int _maxRange) => bool pivotHighTrue = na(ta.pivothigh(_rsiValue, _pivotLeft, _pivotRight)) ? false : true int barsCount = ta.barssince(pivotHighTrue[1] == true) bool inRange = _minRange <= barsCount and barsCount <= _maxRange bool RSI_HH_check = _rsiValue[_pivotRight] > ta.valuewhen(pivotHighTrue, _rsiValue[_pivotRight], 1) and inRange bool price_LH_check = close[_pivotRight] < ta.valuewhen(pivotHighTrue, close[_pivotRight], 1) bool sellContinuationCondition = price_LH_check and RSI_HH_check and pivotHighTrue //buy condition is true [sellContinuationCondition, pivotHighTrue]
ColorArray
https://www.tradingview.com/script/BQNZUZif-ColorArray/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
18
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © kaigouthro //@version=5 import kaigouthro/calc/5 import kaigouthro/hsvColor/15 as h // @description Color Array Resizer/Maker. // Input up to 10 colors, or an array of colors as an argument // set the desired output size of colors to a new color array // NOTE: it pushes to the array, so not meant to be used on reassign, // so . ! to (:=) library('ColorArray',true) // @function Helper anySize(size,_c,bool _switchMode = false)=> cols = array.size(_c) -1 color[] colray = array.new_color() int[] percol = calc.split(size,cols) _c2 = array.get(_c,0) for k = 1 to cols _count = array.get(percol,k-1) _c1 = _c2 _c2 := array.get(_c,k) for i = 1 to _count switch _count 1 => array.push(colray, _c2) => switch _switchMode => array.push(colray, h.hsl_gradient(i, 1, _count, _c1,_c2)) => array.push(colray, h.hsv_gradient(i, 1, _count, _c1,_c2)) colray // @function Color Gradient for Two through ~any~ amount of colors // (1-10 input colors, any more, use an array of cols as input) // @param _array Your own color array (no size limit) // @param _1 Color input # 1 // @param _2 Color input # 2 // @param _3 Color input # 3 (Optional) // @param _4 Color input # 4 (Optional) // @param _5 Color input # 5 (Optional) // @param _6 Color input # 6 (Optional) // @param _7 Color input # 7 (Optional) // @param _8 Color input # 8 (Optional) // @param _9 Color input # 9 (Optional) // @param _10 Color input # 10 (Optional) // @param _mode Switch to Alt HSL mode (i highly suggest fewer colors and larger size for this mode.) // @returns array of colors to specified size. export makeGradient(int size, color _1, color _2, color _3, color _4, color _5, color _6, color _7, color _8, color _9, color _10 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4, color _5, color _6, color _7, color _8, color _9 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5, _6, _7, _8, _9) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4, color _5, color _6, color _7, color _8 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5, _6, _7, _8) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4, color _5, color _6, color _7 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5, _6, _7) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4, color _5, color _6 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5, _6) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4, color _5 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4, _5) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3, color _4 , bool _mode = false )=> _array = array.from(_1, _2, _3, _4) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2, color _3 , bool _mode = false )=> _array = array.from(_1, _2, _3) anySize(size, _array, _mode) export makeGradient(int size, color _1, color _2 , bool _mode = false )=> _array = array.from(_1, _2) anySize(size, _array, _mode) export makeGradient(int size, color[] _array , bool _mode = false )=> anySize(size, _array, _mode) // @function Multiple Color Fader (Negative Limit, Negative strong, Negative mild, neutral, Positive mild, Positive strong, Positive limit) // @param _source (float ) input value to follow // @param _mid (float ) midpoint ( 0 for osc) // @param _colsin (color[] ) colors to generate the fades // @param _th (float ) 0-1,threshold to first level // @param _thmax (float ) 0-1,threshold to second level // @returns color output export fade(float _source, float _mid , color[] _colsin, float _th =0.01, float _thmax = 0.05) => // { var color hc3 = na,var color lc3 = na,var color hc2 = na, var color lc2 = na var color hc1 = na,var color lc1 = na,var color out = na, var _limit = 0. var _cols = makeGradient(6,_colsin), varip float src = 0 varip _src = float(na) _s3a = array.get(_cols, 0) _s2a = array.get(_cols, 1) _s1a = array.get(_cols, 2) _s1b = array.get(_cols, 3) _s2b = array.get(_cols, 4) _s3b = array.get(_cols, 5) _1 = math.max(0.01,math.min(_th,_thmax * 0.99 )) _2 = math.min(0.99,math.max(_1*1.01 ,_thmax )) _3 = 1.01 _src := nz(_source) _limit := math.max(_limit, calc.gapSize(_src,_mid)) src := (calc.percentOfDistance(calc.gapSize(_src,_mid) , 0 , _limit) *math.sign(_src-_mid)) hc3 := h.hsv_gradient( src , _2 , _3 , _s2b , _s3b ) hc2 := h.hsv_gradient( src , _1 , _2 , _s1b , hc3 ) hc1 := h.hsv_gradient( src , 0 , _1 , lc2 , hc2 ) lc3 := h.hsv_gradient( src , -_3 , - _2 , _s3a , _s2a ) lc2 := h.hsv_gradient( src , -_2 , - _1 , lc3 , _s1a ) lc1 := h.hsv_gradient( src , -_1 , 0 , lc2 , hc2 ) out := h.hsv_gradient( src , -_1 , _1 , lc1 , hc1 ) //@function Focus color to an array position //@param _source (float) //@param _values (floa) //@param _colss (color[]) Colors to Use, 2 or more //@param _mode (bool) Optional color from array val //@returns Color array with focused color focus(_source , _values, _cols,bool _mode = false )=> size = array.size(_values) _colarray = makeGradient(size+1,_cols) _colors = array.new_color(size) _pow = 1/math.pow(size,1/3.) _dist = calc.gapSize(_source,array.min(_values))/array.range(_values) for [_i,_val] in _values _d = switch _mode => calc.gapSize(_val,array.min(_values))/array.range(_values) => _i / size _weight = math.pow(calc.gapSize(_dist,_d ), _pow ) array.set(_colors,_i, array.get(_cols,int(array.size(_colarray)*_weight))) array.set(_colors,math.floor(_dist *size ),array.get(_cols,0)) _colors
json
https://www.tradingview.com/script/rkijNKEy-json/
MA_PT
https://www.tradingview.com/u/MA_PT/
13
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © MA_PT //@version=5 // @description Convert JSON strings to tradingview Pine Script library("json") var string msg_json_example = 'Example of json\n [{"ticker":"AAPL","price":"100"},{"ticker":"TSLA","price":"200"}]' var string msg_incorrect_format = '(json)(ERROR) -> Did not find correct format ' //############################################################################## //###################### 1 - Internal Functions ############################ //############################################################################## // @function Check if JSON string is valid check_json_format_is_correct(string raw_json)=> if raw_json== "" or raw_json == " " or na(raw_json) runtime.error("(json) Error -> Input json is empty") array_open_bracket = str.split(raw_json,'{') array_closing_bracket = str.split(raw_json,'}') int a_size_opening = array.size(array_open_bracket) int a_size_closing = array.size(array_closing_bracket) if a_size_opening != a_size_closing or a_size_opening<=1 or a_size_closing<=1 runtime.error(msg_incorrect_format + " missing character { or } pair of brackets :\n" + msg_json_example) if array.size(str.split(raw_json,':')) <=1 runtime.error(msg_incorrect_format + msg_json_example) // @function Clean input raw JSON and returns clean JSON // @return (string) Clean JSON string raw_to_clean_json(string raw_json)=> // Remove unnecessary symbols // Add extra brackets [] and Remove spaces string clean_json = str.replace_all('['+raw_json+']',' ','') // Remove tabs clean_json := str.replace_all(clean_json,' ','') // Check if the JSON format is valid check_json_format_is_correct(clean_json) // Replace splicing character clean_json := str.replace_all(clean_json,'","','";"') // Remove unnecessary characters var special_characters = array.from('[',']','"') clean_json := for symbol in special_characters clean_json := str.replace_all(clean_json,symbol,'') //______________________________________________________________________________ // @function Returns array with each JSON elements // @param raw_json (string) Raw JSON string // @return (string array) array of JSON elements split_json_to_array(string raw_json)=> string clean_json = raw_to_clean_json(raw_json) string clean_element = str.replace_all(clean_json,',','') clean_element := str.replace_all(clean_element,'}','') string[] elements_array = str.split(clean_element,"{") //############################################################################## //###################### 2 - Export Functions ############################ //############################################################################## // @function Returns string array with all key names // @param raw_json (string) Raw JSON string // @returns (string array) Array with all key names export get_json_keys_names(string raw_json)=> split_json_array = split_json_to_array(raw_json) array_of_key_names = array.new_string() if array.size(split_json_array) >=1 split_keys = str.split(array.get(split_json_array,0),";") for element_to_process in split_keys array.push(array_of_key_names,array.get(str.split(element_to_process,":"),0)) array_of_key_names // @function Returns string array with values of the input key name // @param raw_json (string) Raw JSON string // @param key_name (string) Name of the key to be fetched // @returns (string array) Array with values of the input key name export get_values_by_id_name(string raw_json, string key_name)=> array_key_names = get_json_keys_names(raw_json) // Check if the searched element name exists (-1 not found) int key_index = array.indexof(array_key_names,key_name) if key_index<0 str = str.tostring(array_key_names) runtime.error('(json)->get_values_by_id_name Key Name "'+key_name+ '" not found | Available ' + str) array_of_values = array.new_string() for element in split_json_to_array(raw_json) split_parts = str.split(element,";") split_value = str.split(array.get(split_parts,key_index),":") array.push(array_of_values,array.get(split_value,1)) array_of_values //___________________________size_of_json_string________________________________ // @function Returns size of raw JSON string [n_of_values, n_of_keys_names] // @param raw_json (string) Raw JSON string // @returns [int, int] Size of n_of_values, size of n_of_keys_names export size_of_json_string(string raw_json)=> array_of_elements = split_json_to_array(raw_json) int n_of_values = array.size(array_of_elements) int n_of_keys_names = array.size(str.split(array.get(array_of_elements,0),";")) [int(n_of_values), int(n_of_keys_names)]
easytable
https://www.tradingview.com/script/aIwbJg1d-easytable/
MA_PT
https://www.tradingview.com/u/MA_PT/
30
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // ©MA_PT // @version=5 // @description easytable is an easy way to create tables, change colors, insert arrays to tables, remove rows/columns, and format tables. library(title="easytable") import MA_PT/json/1 //############################################################################## //###################### 1 - Internal Functions ############################ //############################################################################## // @function Generate colors to recreate a striped pattern stripped_style(int i, int j, color odd_row, color even_row, color text_c,bool oritation)=> bg_color = oritation ? (i%2 == 0) ? odd_row: even_row : (j%2 == 0) ? odd_row: even_row array.from(bg_color,text_c) //______________________________________________________________________________ // @function Generate colors to color headers only. header_style(int i, int j, color cells, color header, color text_c,int style)=> color bg_color = switch style 1 => (i==0) ? header:cells 2 => (j==0) ? header:cells 3 => (j==0 or i==0) ? header:cells => na array.from(bg_color,text_c) //______________________________________________________________________________ // @function Generate colors to recreate chess pattern. chezz_style(int i, int j, color odd_row, color even_row, color text_c)=> bg_color = (i%2 == 0 and j%2 == 0) or (i%2 != 0 and j%2 != 0) ? odd_row: even_row array.from(bg_color,text_c) //Fetch tables array and nº of tables found. fetch_tbl_and_size()=> found_tables = table.all [found_tables, array.size(found_tables)] //############################################################################## //###################### 2 - Export Functions ############################ //############################################################################## // @function Identifies all tables ID number in each cell(0,0). export indentify_table_id()=> [found_tables, n_found] = fetch_tbl_and_size() if n_found<1 runtime.error('(easytable) → indentify_table_id()      "No table was found."') for i=0 to n_found - 1 table.cell(array.get(found_tables, i),0,0, str.tostring(i), bgcolor = color.black, text_color=color.yellow, text_size=size.huge) //______________________________________________________________________________ // @function Get table object by ID number. // @param id_number (int) ID number of the table to fetch. // @returns table. export get_table_by_id(int id_number = 0) => [found_tables, n_found] = fetch_tbl_and_size() if n_found<1 runtime.error('(easytable) → get_table_by_id()       "No table was found."') if id_number > n_found - 1 runtime.error('(easytable) → get_table_by_id()       The ID number does not exist. Available 0' + (n_found==1 ? na: " to " +str.tostring(n_found-1))) table tbl_return = array.get(found_tables, id_number) //______________________________________________________________________________ // @function Change cells background colors. // @param table_object (table) table object to be changed. // @param cells_color (color) Cells color. // @param start_column (int) Start column. // @param end_column (int) End column. // @param start_row (int) Start Row. // @param end_row (int) End Row to change. // @returns Void. export change_cells_color(table table_object, color cells_color, int start_column, int end_column, int start_row = 0, int end_row=0) => for i = start_column to end_column for j = start_row to end_row table.cell_set_bgcolor(table_object, i, j, cells_color) //______________________________________________________________________________ // @function Change cells text colors. // @param table_object (table) table object to be changed. // @param text_color (color) Text color. // @param start_column (int) Start column. // @param end_column (int) End column. // @param start_row (int) Start Row. // @param end_row (int) End Row. // @returns Void. export change_cells_text_color(table table_object, color text_color, int start_column, int end_column, int start_row = 0, int end_row = 0) => for i = start_column to end_column for j = start_row to end_row table.cell_set_text_color(table_object, i, j, text_color) //______________________________________________________________________________ // @function Change All table text color. // @param table_object (table) table object to be changed. // @param text_color (color) Text color. // @param table_column_size (int) Size of the table columns. // @param table_row_size (int) Size of the table rows. // @returns Void. export change_all_table_text_color(table table_object, color text_color, int table_column_size, int table_row_size) => for i = 0 to table_column_size-1 for j = 0 to table_row_size-1 table.cell_set_text_color(table_object, i, j, text_color) // @function Change table size. // @param table_object (table) table object to be changed. // @param n_of_columns (int) Size of the table columns. // @param n_of_rows (int) Size of the table rows. // @param tbl_size (string) size of the table. // @returns Void. export change_table_size(table table_object,int n_of_columns,int n_of_rows,string tbl_size)=> for i_rows=0 to n_of_rows-1 for i_cols=0 to n_of_columns-1 table.cell_set_text_size(table_object, i_cols, i_rows, tbl_size) //______________________________________________________________________________ // @function Change table cells text size . // @param text_size (string) Text size. // @param start_column (int) Start column. // @param end_column (int)(optional) End column. // @param start_row (int)(optional) Start Row. // @param end_row (int)(optional) End Row. // @param table_id (int)(optional) Number of the ID of the table. // @returns Void. export change_cells_text_size(table table_object, string text_size, int start_column, int end_column = na, int start_row = 0, int end_row = na) => for i = start_column to na(end_column) ? start_column : end_column for j = start_row to na(end_row) ? start_row : end_row table.cell_set_text_size(table_object, i, j, text_size) //______________________________________________________________________________ // @function Delete specified rows from table. // @param table_object (table) table object to be changed. // @param table_column_size (int) Table columns max size. // @param start_row (int) Start row to delete. // @param end_row (int)(optional) End row to delete (optional — Assumes start_row value). // @returns Void. export table_delete_row( table table_object, int table_column_size, int start_row, int end_row = na) => table.clear(table_object,0,start_row, table_column_size, na(end_row) ? start_row : end_row ) //______________________________________________________________________________ // @function Delete specified columns from table. // @param table_object (table) table object to be changed. // @param table_row_size (int) Table rows max size. // @param start_column (int) Start column to delete. // @param end_column (int)(optional) End column to delete (optional — Assumes start_column value). // @returns Void. export table_delete_column(table table_object, int table_row_size, int start_column, int end_column = na) => table.clear(table_object, start_column,0,na(end_column)? start_column:end_column,table_row_size) //______________________________________________________________________________ // @function Insert string array to table column without passing table object. // @param column_to_insert (int) Column to be inserted. // @param array_to_insert (string array) Start column to delete. // @param table_id (int)(optional) Number of the ID of the table. // @returns Void. export array_to_table_column_auto(int column_to_insert, string[] array_to_insert, int table_id = na) => table_object = get_table_by_id(na(table_id)? 0:table_id) int i = 0 for element in array_to_insert table.cell_set_text(table_object, column_to_insert, i, element) i+=1 //______________________________________________________________________________ // @function Insert string array to table row without passing table object. // @param row_to_insert (int) Column to be inserted. // @param array_to_insert (string array) Start column to delete. // @param table_id (int)(optional) Number of the ID of the table. // @returns Void. export array_to_table_row_auto(int row_to_insert, string[] array_to_insert, int table_id = na) => table_object = get_table_by_id(na(table_id)? 0:table_id) for i = 0 to array.size(array_to_insert) -1 table.cell_set_text(table_object, i, row_to_insert, array.get(array_to_insert,i)) //______________________________________________________________________________ // @function Insert string array to table row by passing table object. // @param table_object (table) table object to be changed. // @param row_to_insert (int) Row to be inserted. // @param array_to_insert (string array) Start column to delete. // @returns Void. export array_to_table_row(table table_object , int row_to_insert, string[] array_to_insert) => for i = 0 to array.size(array_to_insert) -1 table.cell_set_text(table_object, i, row_to_insert, array.get(array_to_insert,i)) //______________________________________________________________________________ // @function Insert string array to table column by passing table object. // @param table_object (table) table object to be changed. // @param column_to_insert (int) Column to be inserted. // @param array_to_insert (string array) Start column to delete. // @returns Void. export array_to_table_column(table table_object, int column_to_insert, string[] array_to_insert) => for i = 0 to array.size(array_to_insert) -1 table.cell_set_text(table_object, column_to_insert, i, array.get(array_to_insert,i)) //______________________________________________________________________________ // @function Changes cell color at set intervals (blink). // @param cell_column (int) Cell column position. // @param cell_row (int) Cell row position. // @param c_color (color) Color to blink. // @param blink_interval_ms (int)(opt) Interval in milliseconds. // @param table_id (int)(opt) Table ID number. export blink_cell(int cell_column, int cell_row, color c_color, int blink_interval_ms=1000, int table_id = na)=> varip bool state = false varip time_n = timenow if (timenow - time_n) > blink_interval_ms time_n := timenow state := not(state) color_state = state? c_color: color.rgb(color.r(c_color),color.g(c_color),color.b(c_color),10) table_object = get_table_by_id(na(table_id)? 0:table_id) table.cell_set_bgcolor(table_object,cell_column,cell_row,color_state) //______________________________________________________________________________ // @function Changes table pre-style by selecting a pre-style number. // @param table_object (table) table object to be changed. // @param number_of_columns (int) Table column size. // @param number_of_rows (int) Table row size. // @param color 1 (color) Color of . // @returns Void. export change_table_style(table table_object, int number_of_columns, int number_of_rows, int style_number=0, color color_1 = color.black, color color_2 = color.gray, color color_3_txt = color.white)=> if na(style_number) runtime.error('(easytable) → Must provide style number 0 to 15') for i = 0 to number_of_rows -1 for j=0 to number_of_columns -1 c_bg_and_txt_c = switch style_number 0 => stripped_style(i,j,color_1,color_2,color_3_txt,true) 1 => stripped_style(i,j,color_1,color_2,color_3_txt,false) 2 => header_style(i,j,color_1,color_2,color_3_txt,1) 3 => header_style(i,j,color_1,color_2,color_3_txt,2) 4 => header_style(i,j,color_1,color_2,color_3_txt,3) 5 => chezz_style(i,j,color_2,color_1,color_3_txt) => array.from(color.blue,color.white) if not na(array.get(c_bg_and_txt_c,0)) table.cell_set_bgcolor(table_object,j,i,array.get(c_bg_and_txt_c,0)) table.cell_set_text_color(table_object,j,i,array.get(c_bg_and_txt_c,1)) //______________________________________________________________________________ // @function Create a simple(blank) table without any styling. // @param n_of_columns (int) Numbers of columns in the table. // @param n_of_rows (int) Number of rows in the table. // @param position (string) table position. // @returns table object. export create_table_clean( int n_of_columns, int n_of_rows, string position = position.top_right) => if n_of_columns <= 0 runtime.error("(easytable) → create_table() Cannot create table with nº row less than 1") if n_of_rows <= 0 runtime.error("(easytable) → create_table() Cannot create table with nº column less than 1") table tbl = table.new(position, n_of_columns , n_of_rows) for i = 0 to n_of_rows -1 for j = 0 to n_of_columns - 1 table.cell(tbl, j , i) tbl //______________________________________________________________________________ // @function Create table with a pre-set style. // @param n_of_columns (int) Numbers of columns in the table. // @param n_of_rows (int) Number of rows in the table. // @param style_number (int) Style number. // @param position (string) table position. // @returns table object. export create_table_with_style( int n_of_columns, int n_of_rows, int style_number = 1, string position = position.top_right) => table tbl = create_table_clean(n_of_columns,n_of_rows,position) change_table_style(tbl, n_of_columns, n_of_rows,style_number) tbl // @function Create table based on input raw json string. // @param raw_json (int) Raw json string. // @returns table object. export json_to_table(string raw_json)=> [n_rows, n_columns] = json.size_of_json_string(raw_json) table table_plot = create_table_with_style(n_columns,n_rows+1,2) //+1 title // table table_plot = create_table_clean(n_columns,n_rows+1) //+1 title key_names = json.get_json_keys_names(raw_json) int i = 0 for key_name in key_names array_to_push = json.get_values_by_id_name(raw_json,key_name) array.unshift(array_to_push,key_name) array_to_table_column(table_plot,i,array_to_push) i+=1 table_plot //############################################################################## //###################### 3 - Examples ############################ //############################################################################## // @function Example function that display a table based on a json export json_example()=> var string json_example = '[{"ticker":"MSFT","%":"6.33%"},{"ticker":"AAPL","%":"5.88%"},{"ticker":"Amazon","%":"3.83%"},{"ticker":"Alphabet","%":"2.22%"},{"ticker":"Tesla","%":"2.19%"},{"ticker":"Alphabet","%":"2.09%"},{"ticker":"Meta Platforms","%":"1.98%"},{"ticker":"NVIDIA","%":"1.92%"},{"ticker":"Berkshire Hathaway","%":"1.34%"},{"ticker":"JPMorgan Chase & Co.","%":"1.27%"}]' var tbl = json_to_table(json_example) export example_create_table()=> var n_row = 9 var n_col = 5 var style = 0 // var tbl = create_table_with_style(n_row,n_col,style,position.bottom_right) var tbl = create_table_with_style(n_of_columns = 9, n_of_rows = 9, style_number = 5, position = position.bottom_right) table.set_border_width(tbl,1) var array_text = array.from('e','a','s','y','t','a','b','l','e') array_to_table_row(tbl,0,array_text) array_to_table_column(tbl,0,array_text) blink_cell(int(math.random(0,n_row-1)),int(math.random(0,n_col-1)),color.red,table_id = 1) if barstate.islast json_example() example_create_table()
global
https://www.tradingview.com/script/9gDqBnZG-global/
marspumpkin
https://www.tradingview.com/u/marspumpkin/
12
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © marspumpkin //@version=5 // @description: // Currently in PineScript you cannot change variables from within functions because of the scope limitations. // One way to work around that is to use Arrays. // This Library simplifies the use of arrays as Global Variables to make your code look cleaner. library("global") export init(int value) => array.new_int(1, value) export init(float value) => array.new_float(1, value) export init(bool value) => array.new_bool(1, value) export init(color value) => array.new_color(1, value) export init(string value) => array.new_string(1, value) export init(label value) => array.new_label(1, value) export init(line value) => array.new_line(1, value) export init(linefill value) => array.new_linefill(1, value) export init(box value) => array.new_box(1, value) export init(table value) => array.new_table(1, value) // @function set value to first element in array. MUST call init() first. // @param source array, value of the same type // @returns array containing single item export set(int[] source, int value) => array.set(source, 0, value) export set(float[] source, float value) => array.set(source, 0, value) export set(bool[] source, bool value) => array.set(source, 0, value) export set(color[] source, color value) => array.set(source, 0, value) export set(string[] source, string value) => array.set(source, 0, value) export set(label[] source, label value) => array.set(source, 0, value) export set(line[] source, line value) => array.set(source, 0, value) export set(linefill[] source, linefill value) => array.set(source, 0, value) export set(box[] source, box value) => array.set(source, 0, value) export set(table[] source, table value) => array.set(source, 0, value) // @function gets value // @param source any type of array // @returns first item from array export get(int[] source) => array.get(source, 0) export get(float[] source) => array.get(source, 0) export get(bool[] source) => array.get(source, 0) export get(color[] source) => array.get(source, 0) export get(string[] source) => array.get(source, 0) export get(label[] source) => array.get(source, 0) export get(line[] source) => array.get(source, 0) export get(linefill[] source) => array.get(source, 0) export get(box[] source) => array.get(source, 0) export get(table[] source) => array.get(source, 0) // Sample code below: var price = init(close) var test = open test_function() => // test := close -> does not work set(price, open) // works if open < close set(price, high) // works // test := close -> does not work test_function() if barstate.islast label.new(x=bar_index, y=high, textcolor=color.yellow, text = str.tostring(get(price)), size=size.normal, style=label.style_none)
Pivots library
https://www.tradingview.com/script/Bu9eKkXv-Pivots-library/
boitoki
https://www.tradingview.com/u/boitoki/
75
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © boitoki //@version=5 // @description TODO: add library description here library("Pivots", overlay=true) //////////////////// // Functions //////////////////// f_pivots (_type, _open, _high, _low, _close) => float PP = na float R1 = na, float R2 = na, float R3 = na, float R4 = na, float R5 = na float S1 = na, float S2 = na, float S3 = na, float S4 = na, float S5 = na if _type == 'Traditional' PP := (_high + _low + _close) / 3 R1 := PP + PP - _low S1 := PP - (_high - PP) R2 := PP + _high - _low S2 := PP - (_high - _low) R3 := _high + 2 * (PP - _low) S3 := _low - 2 * (_high - PP) R4 := PP * 3 + (_high - 3 * _low) S4 := PP * 3 - (3 * _high - _low) R5 := PP * 4 + (_high - 4 * _low) S5 := PP * 4 - (4 * _high - _low) else if _type == 'Fibonacci' PP := (_high + _low + _close) / 3 R1 := PP + (_high - _low) * 0.382 S1 := PP - (_high - _low) * 0.382 R2 := PP + (_high - _low) * 0.618 S2 := PP - (_high - _low) * 0.618 R3 := PP + (_high - _low) * 1.000 S3 := PP - (_high - _low) * 1.000 R4 := PP + (_high - _low) * 1.272 S4 := PP - (_high - _low) * 1.272 R5 := PP + (_high - _low) * 1.618 S5 := PP - (_high - _low) * 1.618 else if _type == 'Woodie' PP := (_high + _low + 2 * _open) / 4 R1 := PP + PP - _low S1 := PP - (_high - PP) R2 := PP + _high - _low S2 := PP - (_high - _low) R3 := _high + 2 * (PP - _low) S3 := _low - 2 * (_high - PP) R4 := R3 + _high - _low S4 := S3 - (_high - _low) else if _type == 'Classic' PP := (_high + _low + _close) / 3 pivot_range = _high - _low R1 := PP * 2 - _low S1 := PP * 2 - _high R2 := PP + 1 * pivot_range S2 := PP - 1 * pivot_range R3 := PP + 2 * pivot_range S3 := PP - 2 * pivot_range R4 := PP + 3 * pivot_range S4 := PP - 3 * pivot_range else if _type == 'DM' pivotX_Demark_X = _high + _low * 2 + _close if _close == _open pivotX_Demark_X := _high + _low + _close * 2 if _close > _open pivotX_Demark_X := _high * 2 + _low + _close PP := pivotX_Demark_X / 4 R1 := pivotX_Demark_X / 2 - _low S1 := pivotX_Demark_X / 2 - _high else if _type == 'Camarilla' PP := (_high + _low + _close) / 3 pivot_range = _high - _low R1 := _close + pivot_range * 1.1 / 12.0 S1 := _close - pivot_range * 1.1 / 12.0 R2 := _close + pivot_range * 1.1 / 6.0 S2 := _close - pivot_range * 1.1 / 6.0 R3 := _close + pivot_range * 1.1 / 4.0 S3 := _close - pivot_range * 1.1 / 4.0 R4 := _close + pivot_range * 1.1 / 2.0 S4 := _close - pivot_range * 1.1 / 2.0 else if _type == 'Floor' PP := math.avg(_high, _low, _close) S1 := (PP * 2) - _high S2 := PP - (_high - _low) S3 := _low - 2 * (_high - PP) R1 := (PP * 2) - _low R2 := PP + (_high - _low) R3 := _high + 2 * (PP - _low) else if _type == 'Tom DeMarks Pivots' var x = 0.0 if _close < _open x := _high + (2 * _low) + _close else if _close > _open x := (2 * _high) + _low + _close else x := _high + _low + (2 * _close) PP := x / 4 S1 := (x / 2) - _high R1 := (x / 2) - _low else if _type == 'Expected Pivot Points' PP := (_high + _low + _close) / 3 R1 := PP * 2 - _low S1 := PP * 2 - _high R2 := PP + (R1 - S1) S2 := PP - (R1 - S1) else if _type == 'Zone Analysis' PP := math.avg(_high, _low) R1 := math.avg(PP, _high) S1 := math.avg(PP, _low) else if _type == 'HL2' PP := math.avg(_high, _low) else PP := (_high + _low + _close) / 3 [PP, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5] f_cpr (_high, _low, _close) => PP = (_high + _low + _close) / 3 BC = (_high + _low) / 2 TC = PP - BC + PP CPR = math.abs(TC - BC) [BC, TC, CPR] f_htf_ohlc (_htf) => var htf_o = 0., var htf_h = 0., var htf_l = 0., htf_c = close var htf_ox = 0., var htf_hx = 0., var htf_lx = 0., var htf_cx = 0. if ta.change(time(_htf)) != 0 htf_ox := htf_o, htf_o := open htf_hx := htf_h, htf_h := high htf_lx := htf_l, htf_l := low htf_cx := htf_c[1] else htf_h := math.max(high, htf_h) htf_l := math.min(low , htf_l) [htf_ox, htf_hx, htf_lx, htf_cx, htf_o, htf_h, htf_l, htf_c] //////////////////// // Inputs //////////////////// i_pivots_type = input.string('Traditional', 'Pivots type', options=['Traditional', 'Fibonacci', 'Woodie', 'Classic', 'DM', 'Camarilla', 'Floor', 'Tom DeMarks Pivots', 'Expected Pivot Points', 'PP only', 'Zone Analysis', 'HL2']) i_htf_type = input.string('D', 'Pivots timeframe', options=['60', '120', '240', '360', '720', 'D', 'W', 'M', '6M', '12M']) //////////////////// // Exports //////////////////// // @function Calculates the pivot point and returns its value. // @param _type Specifies the type of pivot point. // @param _open The open price // @param _high The high price // @param _low The low price // @param _clsoe The close price // @returns Returns the value of the calculated pivot point as a tuple. export pivots (simple string _type, float _open, float _high, float _low, float _close) => f_pivots(_type, _open, _high, _low, _close) // @function Calculate the Central Pivot Range // @param _high The high price // @param _low The low price // @param _clsoe The close price // @returns Returns the values as a tuple. export cpr (float _high, float _low, float _close) => f_cpr(_high, _low, _close) // @function Calculate the HTF values // @param _htf Resolution // @returns Returns the values as a tuple. export htf_ohlc (simple string _htf) => f_htf_ohlc(_htf) //////////////////// // Sample codes //////////////////// [O1, H1, L1, C1, O0, H0, L0, C0] = htf_ohlc(i_htf_type) [PP, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5] = pivots(i_pivots_type, O1, H1, L1, C1) [BC, TC, CPR] = cpr(H1, L1, C1) f_render_candle (htf) => is_htf_session_broken = ta.change(time(htf)) != 0 time_x11 = ta.valuewhen(is_htf_session_broken, time, 1) time_x1 = ta.valuewhen(is_htf_session_broken, time, 0) offset = math.round(ta.change(time)) time_x2 = (2 * time_x1 - time_x11) - offset color0 = O0 < C0 ? color.green : color.red color01 = color.new(color0, 90) color1 = O1 < C1 ? color.green : color.red color11 = color.new(color1, 90) var box oc = na, var box hl = na if ta.change(time(htf)) oc := box.new(time_x1, O1, time_x2, C1, bgcolor=color.new(color0, 90), border_color=color.new(color0, 30), xloc=xloc.bar_time) hl := box.new(time_x1, H1, time_x2, L1, bgcolor=color.new(color0, 90), border_color=color.new(color0, 30), border_style=line.style_dotted, xloc=xloc.bar_time) true else box.set_top(oc, math.max(O0, C0)) box.set_bottom(oc, math.min(O0, C0)) box.set_bgcolor(hl, color.new(color0, 90)) box.set_border_color(hl, color.new(color01, 30)) box.set_top(hl, H0) box.set_bottom(hl, L0) box.set_bgcolor(oc, color.new(color0, 90)) box.set_border_color(oc, color.new(color01, 30)) true // Example (Pivots) f_render_pivots (htf) => is_htf_session_broken = ta.change(time(htf)) != 0 time_x11 = ta.valuewhen(is_htf_session_broken, time, 1) time_x1 = ta.valuewhen(is_htf_session_broken, time, 0) offset = math.round(ta.change(time)) time_x2 = (2 * time_x1 - time_x11) - offset color1 = color.orange label l_PP = na label l_R1 = na, label l_S1 = na label l_R2 = na, label l_S2 = na label l_R3 = na, label l_S3 = na label l_R4 = na, label l_S4 = na label l_R5 = na, label l_S5 = na if ta.change(time(htf)) line.new(time_x1, PP, time_x2, PP, color=color1, xloc=xloc.bar_time, width=2) line.new(time_x1, R1, time_x2, R1, color=color1, xloc=xloc.bar_time) line.new(time_x1, R2, time_x2, R2, color=color1, xloc=xloc.bar_time) line.new(time_x1, R3, time_x2, R3, color=color1, xloc=xloc.bar_time) line.new(time_x1, R4, time_x2, R4, color=color1, xloc=xloc.bar_time) line.new(time_x1, R5, time_x2, R5, color=color1, xloc=xloc.bar_time) line.new(time_x1, S1, time_x2, S1, color=color1, xloc=xloc.bar_time) line.new(time_x1, S2, time_x2, S2, color=color1, xloc=xloc.bar_time) line.new(time_x1, S3, time_x2, S3, color=color1, xloc=xloc.bar_time) line.new(time_x1, S4, time_x2, S4, color=color1, xloc=xloc.bar_time) line.new(time_x1, S5, time_x2, S5, color=color1, xloc=xloc.bar_time) l_PP := label.new(time_x2, PP, 'PP', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_PP[1]) l_R1 := label.new(time_x2, R1, 'R1', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_R1[1]) l_R2 := label.new(time_x2, R2, 'R2', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_R2[1]) l_R3 := label.new(time_x2, R3, 'R3', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_R3[1]) l_R4 := label.new(time_x2, R4, 'R4', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_R4[1]) l_R5 := label.new(time_x2, R5, 'R5', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_R5[1]) l_S1 := label.new(time_x2, S1, 'S1', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_S1[1]) l_S2 := label.new(time_x2, S2, 'S2', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_S2[1]) l_S3 := label.new(time_x2, S3, 'S3', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_S3[1]) l_S4 := label.new(time_x2, S4, 'S4', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_S4[1]) l_S5 := label.new(time_x2, S5, 'S5', style=label.style_label_left, color=color.new(color.black, 100), textcolor=color1, xloc=xloc.bar_time), label.delete(l_S5[1]) f_render_pivots(i_htf_type) f_render_candle(i_htf_type)
TradingHook
https://www.tradingview.com/script/B6ezn0JF/
dokang
https://www.tradingview.com/u/dokang/
55
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © dokang //@version=5 // @description This library is a client script for making a webhook signal formatted string to TradingHook webhook server. library("TradingHook", overlay = true) check_exchange(string exchange) => var supported_exchanges = array.from("UPBIT", "BINANCE", "BITGET") if not array.includes(supported_exchanges, exchange) runtime.error(exchange+"is not supported.") check_exchange_support_amount_order(string exchange) => var supported_exchanges = array.from("BINANCE") if not array.includes(supported_exchanges, exchange) runtime.error(exchange+"is not supported.") check_exchange_support_cost_order(string exchange) => var supported_exchanges = array.from("UPBIT") if not array.includes(supported_exchanges, exchange) runtime.error(exchange+"is not supported.") check_futures(string ticker) => if not str.endswith(ticker, "PERP") runtime.error("Function entry_message() is only supported in Futures ticker") is_futures(string ticker) => if str.endswith(ticker, "PERP") true else false // @function Make a buy Message for TradingHook. // @param password (string) [Required] password that you set in .env file. // @param amount (float) [Optional] amount. If not set, your strategy qty will be sent. // @param order_name (string) [Optional] order_name. The default name is "Order". // @returns (string) A string containing the formatted webhook message. export buy_message(string password, float amount = na, string order_name="Order") => prefix = syminfo.prefix check_exchange(prefix) order_amount = float(na) str_amount = string(na) if amount order_amount := amount str_amount := str.tostring(amount) else str_amount := "{{strategy.order.contracts}}" order_amount := str.tonumber(str_amount) cost = order_amount * close str_cost = str.tostring(cost) str_price = str.tostring(close) json = '{' + str.format( ' "password":"{0}", "amount":"{1}", "price":"{2}", "cost":"{3}", "side":"{4}", "exchange":"{5}", "base":"{6}", "quote":"{7}", "order_name":"{8}" ', password, str_amount, str_price, str_cost, "BUY", syminfo.prefix, syminfo.basecurrency, syminfo.currency, order_name) +'}' json // @function Make a sell message for TradingHook. // @param password (string) [Required] password that you set in .env file. // @param percent (string) [Required] what percentage of your quantity you want to sell. // @param order_name (string) [Optional] order_name. The default name is "Order". // @returns (string) A string containing the formatted webhook message. export sell_message(string password, string percent, string order_name="Order") => check_exchange(syminfo.prefix) pos = str.pos(percent,"%") if not pos runtime.error("Function sell_message() param 'percent' must include '%'") sell_percent = str.substring(percent, 0, pos) str_price = str.tostring(close) json = '{' + str.format( ' "password":"{0}", "amount":"{1}", "price":"{2}", "sell_percent":"{3}", "side":"{4}", "exchange":"{5}", "base":"{6}", "quote":"{7}", "order_name":"{8}" ', password, "0",str_price, sell_percent,"SELL", syminfo.prefix, syminfo.basecurrency, syminfo.currency, order_name) +'}' json // @function Make a Entry Message for TradingHook. // @param password (string) [Required] password that you set in .env file. // @param amount (float) [Optional] amount. If not set, your strategy qty will be sent. // @param leverage (int) [Optional] leverage. If not set, your leverage doesn't change. // @param order_name (string) [Optional] order_name. The default name is "Order". // @returns (string) A string containing the formatted webhook message. export entry_message(string password, float amount = na, int leverage = 0,string order_name="Order") => prefix = syminfo.prefix check_exchange(prefix) if not is_futures(syminfo.ticker) runtime.error("Function entry_message() is only supported in Futures ticker") order_amount = float(na) str_amount = string(na) action = "{{strategy.order.action}}" if amount order_amount := amount str_amount := str.tostring(amount) else str_amount := "{{strategy.order.contracts}}" order_amount := str.tonumber(str_amount) cost = order_amount * close str_cost = str.tostring(cost) str_price = str.tostring(close) str_leverage = str.tostring(leverage) json = '{' + str.format( ' "password":"{0}", "amount":"{1}", "price":"{2}", "cost":"{3}", "side":"{4}", "exchange":"{5}", "base":"{6}", "quote":"{7}", "leverage": "{8}", "order_name":"{9}" ', password, str_amount, str_price, str_cost, "entry/"+action, syminfo.prefix, syminfo.basecurrency, syminfo.currency+"PERP", str_leverage, order_name) +'}' json // @function Make a close message for TradingHook. // @param password (string) [Required] password that you set in .env file. // @param percent (string) [Required/Optional] what percentage of your quantity you want to close. // @param amount (float) [Required/Optional] quantity you want to close. // @param order_name (string) [Optional] order_name. The default name is "Order". // @returns (string) A string containing the formatted webhook message. export close_message(string password, string percent = na, float amount = na, string order_name="Order") => check_exchange(syminfo.prefix) check_futures(syminfo.ticker) action = "{{strategy.order.action}}" str_price = str.tostring(close) json = string(na) // for percent pos = int(na) close_percent = string(na) // for amount order_amount = float(na) str_amount = string(na) if na(percent) and na(amount) runtime.error("You have to set percent or amount param") else if not na(percent) and not na(amount) runtime.error("You have to set only percent or amount param. You can't set both percent and amount ") else if not na(percent) pos := str.pos(percent,"%") if not pos runtime.error("Function close_message() param 'percent' must include '%'") close_percent := str.substring(percent, 0, pos) json := '{' + str.format( ' "password":"{0}", "amount":"{1}", "price":"{2}", "close_percent":"{3}", "side":"{4}", "exchange":"{5}", "base":"{6}", "quote":"{7}", "order_name":"{8}" ', password, "0",str_price, close_percent, "close/"+action, syminfo.prefix, syminfo.basecurrency, syminfo.currency+"PERP", order_name) +'}' else if not na(amount) order_amount := amount str_amount := str.tostring(amount) json := '{' + str.format( ' "password":"{0}", "amount":"{1}", "price":"{2}", "close_percent":"{3}", "side":"{4}", "exchange":"{5}", "base":"{6}", "quote":"{7}", "order_name":"{8}" ', password, str_amount, str_price, "0", "close/"+action, syminfo.prefix, syminfo.basecurrency, syminfo.currency+"PERP", order_name) +'}' json
Common Functions
https://www.tradingview.com/script/KJYxDHNj-Common-Functions/
gliderfund
https://www.tradingview.com/u/gliderfund/
2
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © gliderfund //@version=5 // https://www.tradingview.com/script/KJYxDHNj-Common-Functions/ // import gliderfund/CommonFunctions/2 as com // @description This Library provides some handy functions commonly used in Pine Script. library(title = "CommonFunctions", overlay = true) // ############################################# // ############################################# // CROSSES // ############################################# // ############################################# // @function Checks the existance of crosses between the series // @param source1 First series // @param offset1 (Optional) Offset of First series. By default 0 // @param source2 (Optional) Second series. By default 'close' price // @param offset2 (Optional) Offset of Second series. By default 0 // @returns [cross, crossOver, crossUnder] export crosses(series float source1, simple int offset1 = 0, series float source2 = close, simple int offset2 = 0) => cross = ta.cross(source1[offset1], source2[offset2]) // crossOver: true when source1 crossed over source2 otherwise false crossOver = ta.crossover(source1[offset1], source2[offset2]) // crossUnder: true when source1 crossed under source2 otherwise false crossUnder = ta.crossunder(source1[offset1], source2[offset2]) // Result [cross, crossOver, crossUnder] // End of Function // ############################################# // ############################################# // MARKET STATE // ############################################# // ############################################# // @function Determines Bullish/Bearish state according to the relative position between the series. // @param source1 Active series used to determine bullish/bearish states. // @param offset1 (Optional) Offset of First series. By default 0. // @param source2 (Optional) Second series. By default 'close' price. // @param offset2 (Optional) Offset of Second series. By default 0. // @returns [bullish, bearish] export marketState(series float source1, simple int offset1 = 0, series float source2 = close, simple int offset2 = 0) => // Conditions bullish = source1[offset1] < source2[offset2] bearish = source1[offset1] >= source2[offset2] // Result [bullish, bearish] // End of Function // ############################################# // ############################################# // HISTOGRAM PROFILE // ############################################# // ############################################# // @function Histogram profiling // @param hist Histogram series // @param ref Reference value. By default '0' // @returns [histPosUp, histPosDown, histNegUp, histNegDown] export histProfile(series float hist, series float ref = 0.0) => histPosUp = hist > hist[1] and hist > ref histPosDown = hist < hist[1] and hist > ref histNegUp = hist < hist[1] and hist <= ref histNegDown = hist > hist[1] and hist <= ref // Result [histPosUp, histPosDown, histNegUp, histNegDown] // End of Function // ############################################# // ############################################# // FLOAT SELECT // ############################################# // ############################################# // @function Selects the appropiate float variable based on a boolean condition. If multiple sources are activated simultaneously, the order within the switch clause prevails. The first one activated is the one being output. // @param showSrc1 Boolean controlling the activation of Source #1. // @param src1 Source #1. // @param showSrc2 Boolean controlling the activation of Sources #2-10. By default 'false'. // @param src2 Sources #2-10. By default 'number'. // @returns Selected source. export floatSelect(simple bool showSrc1 = true, series float src1 = 1, simple bool showSrc2 = false, series float src2 = 2, simple bool showSrc3 = false, series float src3 = 3, simple bool showSrc4 = false, series float src4 = 4, simple bool showSrc5 = false, series float src5 = 5, simple bool showSrc6 = false, series float src6 = 6, simple bool showSrc7 = false, series float src7 = 7, simple bool showSrc8 = false, series float src8 = 8, simple bool showSrc9 = false, series float src9 = 9, simple bool showSrc10 = false, series float src10 = 10) => float result = switch showSrc1 => src1 showSrc2 => src2 showSrc3 => src3 showSrc4 => src4 showSrc5 => src5 showSrc6 => src6 showSrc7 => src7 showSrc8 => src8 showSrc9 => src9 showSrc10 => src10 => float(na) // Result result // End of Function // ############################################# // ############################################# // INTEGER SELECT // ############################################# // ############################################# // @function Selects the appropiate integer variable based on a boolean condition. If multiple sources are activated simultaneously, the order within the switch clause prevails. The first one activated is the one being output. // @param showSrc1 Boolean controlling the activation of Source #1. // @param src1 Source #1. // @param showSrc2 Boolean controlling the activation of Sources #2-10. By default 'false'. // @param src2 Sources #2-10. By default 'number'. // @returns Selected source. export intSelect(simple bool showSrc1 = true, series int src1 = 1, simple bool showSrc2 = false, series int src2 = 2, simple bool showSrc3 = false, series int src3 = 3, simple bool showSrc4 = false, series int src4 = 4, simple bool showSrc5 = false, series int src5 = 5, simple bool showSrc6 = false, series int src6 = 6, simple bool showSrc7 = false, series int src7 = 7, simple bool showSrc8 = false, series int src8 = 8, simple bool showSrc9 = false, series int src9 = 9, simple bool showSrc10 = false, series int src10 = 10) => bool result = switch showSrc1 => src1 showSrc2 => src2 showSrc3 => src3 showSrc4 => src4 showSrc5 => src5 showSrc6 => src6 showSrc7 => src7 showSrc8 => src8 showSrc9 => src9 showSrc10 => src10 => int(na) // Result result // End of Function // ############################################# // ############################################# // BOOL SELECT // ############################################# // ############################################# // @function Selects the appropiate bool variable based on a boolean condition. If multiple sources are activated simultaneously, the order within the switch clause prevails. The first one activated is the one being output. // @param showSrc1 Boolean controlling the activation of Source #1. // @param src1 Source #1. // @param showSrc2 Boolean controlling the activation of Sources #2-10. By default 'false'. // @param src2 Sources #2-10. By default 'false'. // @returns Selected source. export boolSelect(simple bool showSrc1 = true, series bool src1 = na, simple bool showSrc2 = false, series bool src2 = na, simple bool showSrc3 = false, series bool src3 = na, simple bool showSrc4 = false, series bool src4 = na, simple bool showSrc5 = false, series bool src5 = na, simple bool showSrc6 = false, series bool src6 = na, simple bool showSrc7 = false, series bool src7 = na, simple bool showSrc8 = false, series bool src8 = na, simple bool showSrc9 = false, series bool src9 = na, simple bool showSrc10 = false, series bool src10 = na) => bool result = switch showSrc1 => src1 showSrc2 => src2 showSrc3 => src3 showSrc4 => src4 showSrc5 => src5 showSrc6 => src6 showSrc7 => src7 showSrc8 => src8 showSrc9 => src9 showSrc10 => src10 => bool(na) // Result result // End of Function
MovingAverages
https://www.tradingview.com/script/BPixsIOP-MovingAverages/
TanawutWattana
https://www.tradingview.com/u/TanawutWattana/
5
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TanawutWattana // @version=5 // @description Contains utilities for generating moving average values including getting a moving average by name and a function for generating a Volume-Adjusted WMA. library('MovingAverages', true) isLenInvalid(simple int len, simple string name = 'len') => if na(len) runtime.error("The '"+name+"' param cannot be NA.") true else if len < 0 runtime.error("The '"+name+"' param cannot be negative.") true else if len == 0 true else false //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // VAWMA = VWMA and WMA combined. // Simply put, this attempts to determine the average price per share over time weighted heavier for recent values. // Uses triangular algorithm to taper off values in the past (same as WMA does). //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Simple Moving Avereage // @param _D The series to measure from. // @param _len The number of bars to measure with. export sma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _sma=ta.sma(_D, _len) _sma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Exponential Moving Avereage // @param _D The series to measure from. // @param _len The number of bars to measure with. export ema( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _ema=ta.ema(_D, _len) _ema /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function RSI Moving Avereage // @param _D The series to measure from. // @param _len The number of bars to measure with. export rma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _rma=ta.rma(_D,_len) _rma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Weighted Moving Avereage // @param _D The series to measure from. // @param _len The number of bars to measure with. export wma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _wma=ta.wma(_D,_len) _wma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function volume-weighted Moving Avereage // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. export vwma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _vwma=ta.vwma(_D,_len) _vwma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Arnaud Legoux Moving Avereage // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. export alma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _alma=ta.alma(_D,_len, 0.8, 6) _alma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Coefficient Moving Avereage (CMA) is a variation of a moving average that can simulate SMA or WMA with the advantage of previous data. // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. // @param C The coefficient to use when averaging. 0 behaves like SMA, 1 behaves like WMA. // @param compound When true (default is false) will use a compounding method for weighting the average. export cma( series float _D, simple int _len, simple float C = 1, simple bool compound = false) => var float notAvailable = na if isLenInvalid(_len, 'n') notAvailable else var float result = na sum = 0.0 weight = 1.0 weightTotal = 0.0 for m = 1 to _len s = _D[_len - m] if not na(s) sum := sum + s * weight weightTotal += weight if compound weight *= 1 + C else weight += C prev = result[_len] if na(prev) result := sum / weightTotal else result := (prev + sum) / (weightTotal + 1) /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Double Exponential Moving Avereage // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. export dema( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else e1 = ta.ema(_D, _len) e2 = ta.ema(e1, _len) _dema=2 * e1 - e2 _dema /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Arnaud Legoux Moving Avereage // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. export zlsma( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _zlsma1 = ta.linreg(_D, math.round(_len/2), 0) _zlsma2 = ta.linreg(_zlsma1, math.round(_len/2), 0) _zlsma=(2*_zlsma1)-_zlsma2 _zlsma /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Arnaud Legoux Moving Avereage // @param _D The series to measure from. Default is 'close'. // @param _len The number of bars to measure with. export zlema( series float _D, simple int _len) => if isLenInvalid(_len, 'n') na else _quadLength = math.round((_len -1)/4) _sensitivePrice = (_D + (_D - _D[_quadLength])) _zlema=ta.ema(_sensitivePrice, _len) _zlema /////////////////////////////////////////////////// /////////////////////////////////////////////////// // @function Generates a moving average based upon a 'type'. // @param type The type of moving average to generate. Values allowed are: SMA, EMA, WMA, VWMA and VAWMA. // @param len The number of bars to measure with. // @param src The series to measure from. Default is 'close'. // @returns The moving average series requested. export get( simple string type='SMA', series float src = close, simple int len=20) => if isLenInvalid(len, 'n') na else switch type 'SMA' => ta.sma(src, len) 'EMA' => ta.ema(src, len) 'RMA' => ta.rma(src, len) 'WMA' => ta.wma(src, len) 'VWMA' => ta.vwma(src,len) 'ALMA' => ta.alma(src, len, 0.8,6) 'CMA' => cma(src, len) 'DMEA' => dema(src, len) 'ZLSMA' => zlsma(src, len) 'ZLEMA' => zlema(src, len) => runtime.error("No matching MA type found.") ta.sma(src, len) /////////////////////////////////////////////////// // Demo plot(ema(hlc3,30), 'ema(20)', color.red) plot(wma(hlc3,30), 'wma(20)', color.yellow) plot(vwma(hlc3,30), 'vwma(20)', color.blue)
Pivots
https://www.tradingview.com/script/GZFEz0Ca-Pivots/
gliderfund
https://www.tradingview.com/u/gliderfund/
83
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © gliderfund //@version=5 // @description This Library focuses in functions related to pivot highs and lows and some of their applications (i.e. divergences, zigzag, harmonics, support and resistance...) library(title = "Pivots", overlay = true) // ############################################# // ############################################# // PIVOT HIGH & LOW // ############################################# // ############################################# // @function Delivers series of pivot highs, lows and zigzag. // @param srcH Source series to look for pivot highs. Stricter applications might source from 'close' prices. Oscillators are also another possible source to look for pivot highs and lows. By default 'high' // @param srcL Source series to look for pivot lows. By default 'low' // @param length This value represents the minimum number of candles between pivots. The lower the number, the more detailed the pivot profile. The higher the number, the more relevant the pivots. By default 10 // @returns [pivotHigh, pivotLow] export pivots(series float srcH = high, series float srcL = low, simple int length = 10) => // Pivot Highs float pivotHigh = nz(srcH[length]) if length == 0 pivotHigh else pivotHFound = true for i = 0 to math.abs(length - 1) if srcH[i] > pivotHigh pivotHFound := false break for i = length + 1 to (2 * length) if srcH[i] >= pivotHigh pivotHFound := false break if not pivotHFound and (length * 2 <= bar_index) pivotHigh := float(na) // Pivot Lows float pivotLow = nz(srcL[length]) if length == 0 pivotLow else pivotLFound = true for i = 0 to math.abs(length - 1) if srcL[i] < pivotLow pivotLFound := false break for i = length + 1 to (2 * length) if srcL[i] <= pivotLow pivotLFound := false break if not pivotLFound and (length * 2 <= bar_index) pivotLow := float(na) // Result [pivotHigh, pivotLow] // End of Function // ############################################# // ############################################# // ZIGZAG ARRAY/SERIES // ############################################# // ############################################# // @function Delivers a Zigzag series based on alternating pivots. Ocasionally this line could paint a few consecutive lows or highs without alternating. That happens because it's finding a few consecutive Higher Highs or Lower Lows. If to use lines entities instead of series, that could be easily avoided. But in this one, I'm more interested outputting series rather than painting/deleting line entities. // @param pivotHigh Pivot high series // @param pivotLow Pivot low series // @returns [zigzagSeries, zigzagValues, zigzagIndex, zigzagPivot] export zigzagArray(series float pivotHigh, series float pivotLow) => // Arrays float[] zigzagValues = array.new_float(0) int[] zigzagIndex = array.new_int(0) bool[] zigzagPivot = array.new_bool(0) // true: Pivot High, false: Pivot Low float[] zigzagSeries = array.new_float(0) // Defines the origin values for each Line int indexPrevPivot = na float prevValue = na int prevIndex = na bool prevPivot = na // Get values from last pivot if array.size(zigzagPivot) > 0 indexPrevPivot := array.size(zigzagPivot) - 1 prevValue := array.get(zigzagValues, indexPrevPivot) prevIndex := array.get(zigzagIndex, indexPrevPivot) prevPivot := array.get(zigzagPivot, indexPrevPivot) // Actions on Pivot Points if pivotLow // Actions on a Pivot Low if prevPivot or na(prevPivot) // Last recorded pivot was a High or na array.push(zigzagValues, pivotLow) array.push(zigzagIndex, bar_index) array.push(zigzagPivot, false) array.push(zigzagSeries, pivotLow) else // Last recorded pivot was a Low if prevValue > pivotLow // If current Low is Lower array.pop(zigzagValues) array.pop(zigzagIndex) array.set(zigzagSeries, prevIndex, na) array.push(zigzagValues, pivotLow) array.push(zigzagIndex, bar_index) array.push(zigzagSeries, pivotLow) else array.push(zigzagSeries, na) else if pivotHigh // Actions on a Pivot High if not prevPivot or na(prevPivot) // Last recorded pivot was a Low or na array.push(zigzagValues, pivotHigh) array.push(zigzagIndex, bar_index) array.push(zigzagPivot, true) array.push(zigzagSeries, pivotHigh) else // Last recorded pivot was a High if prevValue < pivotHigh // If current High is Higher array.pop(zigzagValues) array.pop(zigzagIndex) array.set(zigzagSeries, prevIndex, na) array.push(zigzagValues, pivotHigh) array.push(zigzagIndex, bar_index) array.push(zigzagSeries, pivotHigh) else array.push(zigzagSeries, na) else array.push(zigzagSeries, na) // Result [zigzagSeries, zigzagValues, zigzagIndex, zigzagPivot] // End of Function // ############################################# // ############################################# // ZIGZAG LINE // ############################################# // ############################################# // @function Delivers a Zigzag based on line entities. // @param srcH Source series to look for pivot highs. Stricter applications might source from 'close' prices. Oscillators are also another possible source to look for pivot highs and lows. By default 'high' // @param srcL Source series to look for pivot lows. By default 'low' // @param colorLine Color of the Zigzag Line. By default Fuchsia // @param widthLine Width of the Zigzag Line. By default 4 // @returns Zigzag printed on screen export zigzagLine(simple int length = 10, series float srcH = high, series float srcL = low, simple color colorLine = #FF00FF, simple int widthLine = 4) => // Function inspired from Tr0st's Zig Zag High Low Indicator: https://www.tradingview.com/script/I2xTwDzy-Zig-Zag-High-Low // Vars var lastPivotHigh = 0.0 var barHigh = bar_index var lastPivotLow = math.pow(srcH, 10) var barLow = bar_index var upWeGo = false // Define the Line parameters var line zLine = na // Pivot Points pivotHigh = ta.highest(srcH, length * 2 + 1) pivotLow = ta.lowest(srcL, length * 2 + 1) if upWeGo if (pivotLow == low[length] and low[length] < lastPivotLow) // If current Pivot Low is Lower than the last recorded one... lastPivotLow := low[length] barLow := bar_index line.delete(zLine) zLine := line.new(x1 = barHigh - length, y1 = lastPivotHigh, x2 = barLow - length, y2 = lastPivotLow, xloc = xloc.bar_index, extend = extend.none, color = colorLine, style = line.style_solid, width = widthLine) if (pivotHigh == high[length] and high[length] > lastPivotLow) // If current Pivot High is Higher than the last Pivot Low... lastPivotHigh := high[length] barHigh := bar_index upWeGo := false zLine := line.new(x1 = barHigh - length, y1 = lastPivotHigh, x2 = barLow - length, y2 = lastPivotLow, xloc = xloc.bar_index, extend = extend.none, color = colorLine, style = line.style_solid, width = widthLine) else if (pivotHigh == high[length] and high[length] > lastPivotHigh) // If current Pivot High is Higher than the last recorded one... lastPivotHigh := high[length] barHigh := bar_index line.delete(zLine) zLine := line.new(x1 = barHigh - length, y1 = lastPivotHigh, x2 = barLow - length, y2 = lastPivotLow, xloc = xloc.bar_index, extend = extend.none, color = colorLine, style = line.style_solid, width = widthLine) if (pivotLow == low[length] and low[length] < lastPivotHigh) // If current Pivot Low is Lower than the last Pivot High... lastPivotLow := low[length] barLow := bar_index upWeGo := true zLine := line.new(x1 = barHigh - length, y1 = lastPivotHigh, x2 = barLow - length, y2 = lastPivotLow, xloc = xloc.bar_index, extend = extend.none, color = colorLine, style = line.style_solid, width = widthLine) // End of Function // ############################################# // ############################################# // DIVERGENCES // ############################################# // ############################################# // @function Calculates divergences between 2 series // @param h2 Series in which to locate divs: Highs // @param l2 Series in which to locate divs: Lows // @param h1 Series in which to locate pivots: Highs. By default high // @param l1 Series in which to locate pivots: Lows. By default low // @param length Length used to calculate Pivots: By default 10 // @returns [actualH2, actualL2, actualH1, actualL1, bullRegDiv, bearRegDiv, bullHidDiv, bearHidDiv, bullRegDivRT, bearRegDivRT, bullHidDivRT, bearHidDivRT] export divergence(series float h2, series float l2, series float h1 = high, series float l1 = low, simple int length = 10) => // Pivots [pivotHigh, pivotLow] = pivots(h1, l1, length) // Pivot Highs valueLastH1 = ta.valuewhen(pivotHigh, h1[length], 0) valuePastH1 = ta.valuewhen(pivotHigh, h1[length], 1) actualH1 = pivotHigh pastH1 = actualH1 ? valuePastH1 : na lastH1 = valueLastH1 // Pivot Lows valueLastL1 = ta.valuewhen(pivotLow, l1[length], 0) valuePastL1 = ta.valuewhen(pivotLow, l1[length], 1) actualL1 = pivotLow pastL1 = actualL1 ? valuePastL1 : na lastL1 = valueLastL1 // Div Highs valueActualH2 = ta.valuewhen(pivotHigh, h2[length], 0) valuePastH2 = ta.valuewhen(pivotHigh, h2[length], 1) actualH2 = actualH1 ? valueActualH2 : na pastH2 = actualH1 ? valuePastH2 : na lastH2 = valueActualH2 // Div Lows valueActualL2 = ta.valuewhen(pivotLow, l2[length], 0) valuePastL2 = ta.valuewhen(pivotLow, l2[length], 1) actualL2 = actualL1 ? valueActualL2 : na pastL2 = actualL1 ? valuePastL2 : na lastL2 = valueActualL2 // Conditions // RT conditions: Real Time Potential Divergence Building // Regular Bullish Divergence bullRegDiv = (actualL1 < pastL1) and (actualL2 > pastL2) bullRegDivRT = barstate.islast and (l1[0] < lastL1) and (l2[0] > lastL2) // Regular Bearish Divergence bearRegDiv = (actualH1 > pastH1) and (actualH2 < pastH2) bearRegDivRT = barstate.islast and (h1[0] > lastH1) and (h2[0] < lastH2) // Hidden Bullish Divergence bullHidDiv = (actualL1 > pastL1) and (actualL2 < pastL2) bullHidDivRT = barstate.islast and (l1[0] > lastL1) and (l2[0] < lastL2) // Hidden Bearish Divergence bearHidDiv = (actualH1 < pastH1) and (actualH2 > pastH2) bearHidDivRT = barstate.islast and (h1[0] < lastH1) and (h2[0] > lastH2) // Result [actualH2, actualL2, actualH1, actualL1, bullRegDiv, bearRegDiv, bullHidDiv, bearHidDiv, bullRegDivRT, bearRegDivRT, bullHidDivRT, bearHidDivRT] // End of Function // Example zigzagLine()
poStrategyLibrary
https://www.tradingview.com/script/EUvxPPjm-poStrategyLibrary/
payam_omrani
https://www.tradingview.com/u/payam_omrani/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © payam_omrani //@version=5 // @description essential function for export library("poStrategyLibrary") export isFlat() => strategy.position_size == 0 export isLongShort() => strategy.position_size != 0 export pipProfit() => entryPrice = strategy.opentrades.entry_price(0) profitByUSD = strategy.opentrades.profit(0) pipValue = strategy.opentrades.size(0) * syminfo.mintick * 10 if(strategy.position_size < 0) if(profitByUSD / pipValue < 0) math.abs(profitByUSD / pipValue) else profitByUSD / pipValue export pipLoss() => entryPrice = strategy.opentrades.entry_price(0) profitByUSD = strategy.opentrades.profit(0) pipValue = strategy.opentrades.size(0) * syminfo.mintick * 10 if(strategy.position_size > 0) if(profitByUSD / pipValue < 0) math.abs(profitByUSD / pipValue) else profitByUSD / pipValue export usdProfit() => profitByUSD = strategy.opentrades.profit(0) export usdLoss() => profitByUSD = strategy.opentrades.profit(0) if(strategy.position_size > 0) if(profitByUSD < 0) math.abs(profitByUSD) else profitByUSD
Chikou
https://www.tradingview.com/script/7eyXMAn7-Chikou/
MightyZinger
https://www.tradingview.com/u/MightyZinger/
31
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © MightyZinger //@version=5 // @description This library defines Chikou Filter function to enhances functionality of Chikou-Span from Ichimoku Cloud using a simple trend filter. //Chikou is basically close value of ticker offset to close and it is a good for indicating if close value has crossed potential Support/Resistance zone from past. Chikou is usually used with 26 period. //Chikou filter uses a lookback length calculated from provided lookback percentage and checks if trend was bullish or bearish within that lookback period. //Bullish : Trend is bullish if Chikou span is above high values of all candles within defined lookback period. Bull color shows bullish trend . //Bearish: Trend is bearish if Chikou span is below low values of all candles within defined lookback period. This is indicated by Bearish color. //Reversal / Choppiness : Reversal color indicates that Chikou are swinging around candles within defined lookback period which is an indication of consolidation or trend reversal. library("Chikou") // @function Chikou Filter for Ichimoku Cloud with Color and Signal Output // @param src Price Source (better to use (OHLC4+high+low/3 instead of default close value) // @param len Chikou Legth (displaced source value) // @param _high Ticker High Value // @param _low Ticker Low Value // @param bull_col Color to be returned if source value is greater than all candels within provided lookback percentage. // @param bear_col Color to be returned if source value is lower than all candels within provided lookback percentage. // @param r_col Color to be returned if source value is swinging around candles within defined lookback period which is an indication of consolidation or trend reversal. // @returns Color based on trend. 'bull_col' if trend is bullish, 'bear_col' if trend is bearish. 'r_col' if no prominent trend. Integer Signal is also returned as 1 for Bullish, -1 for Bearish and 0 for no prominent trend. export chikou(float src, simple int len, float _high, float _low, color bull_col, color bear_col, color r_col)=> var _up = bool(na) var _dn = bool(na) var _re = bool(na) var color _clr = color.new(na, 0) var sig = int(na) _up := src > ta.highest(_high, len)[len] _dn := src < ta.lowest(_low, len)[len] _re := src < ta.highest(_high, len)[len] and src > ta.lowest(_low, len)[len] _clr := _up ? bull_col : _dn ? bear_col : r_col sig := _up ? 1 : _dn ? -1 : 0 // provides Bullish and Bearish condition in Integer format that can be used as signals [_clr, sig] ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///// Source Options ////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // ─── Different Sources Options List ───► [ string SRC_Tv = 'Use traditional TradingView Sources ' string SRC_Wc = '(high + low + (2 * close)) / 4' string SRC_Wo = 'close+high+low-2*open' string SRC_Wi = '(close+high+low) / 3' string SRC_Ex = 'close>open ? high : low' string SRC_Hc = 'Heikin Ashi Close' string src_grp = 'Source Parameters' // ●───────── Inputs ─────────● { diff_src = input.string(SRC_Wi, '→ Different Sources Options', options=[SRC_Tv, SRC_Wc, SRC_Wo, SRC_Wi, SRC_Ex, SRC_Hc], group=src_grp) i_sourceSetup = input.source(close, 'Source Setup', group=src_grp) uha_src = input.bool(true, title='Use Heikin Ashi Candles for Different Source Calculations', group=src_grp) i_Symmetrical = input.bool(true, 'Apply Symmetrically Weighted Moving Average at the price source (May Result Repainting)', group=src_grp) // Heikinashi Candles for calculations h_close = uha_src ? ohlc4 : close f_ha_open() => haopen = float(na) haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(ohlc4[1])) / 2 haopen h_open = uha_src ? f_ha_open() : open h_high = high h_low = low // Get Source src_o = diff_src == SRC_Wc ? (h_high + h_low + 2 * h_close) / 4 : diff_src == SRC_Wo ? h_close + h_high + h_low - 2 * h_open : diff_src == SRC_Wi ? (h_close + h_high + h_low) / 3 : diff_src == SRC_Ex ? h_close > h_open ? h_high : h_low : diff_src == SRC_Hc ? ohlc4 : i_sourceSetup src_f = i_Symmetrical ? ta.swma(src_o) : src_o // Symmetrically Weighted Moving Average? string grp1 = 'Chikou Parameters' c_len = input.int(26, title='Chikou Period:', group=grp1) ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Chikou Plot [c_col, _trend] = chikou(src_f, c_len, high, low, color.green, color.red, color.yellow) chikou_plot = plot(src_f, offset = -c_len+1 , color= c_col , title="Chikou-Span", linewidth=4) ///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////
Timed_exit_alert_for_webhook
https://www.tradingview.com/script/cA0xdHDu-Timed-exit-alert-for-webhook/
natronix
https://www.tradingview.com/u/natronix/
13
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © natronix //@version=5 // @description TODO: add library description here library("Timed_exit_alert_for_webhook") t = time(timeframe.period, input('1440- 1441:23456',title='Time to send in close order')) //plot(na(t) ? 0 : 1) //bgcolor(not na(t) ? green : na) time_cond = na(t) ? 0 : 1 alertcondition(time_cond,title="alert time condition to exit position",message="close") // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export fun(float x) => //TODO : add function body and return value here x
console
https://www.tradingview.com/script/ZctemeK9-console/
keio
https://www.tradingview.com/u/keio/
16
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © keio //@version=5 // @description TODO: simple debug console. USAGE : import keio/console/1 as console library("console", overlay=false) // ███████╗ █████╗ ███████╗██╗ ██╗ // ██╔════╝██╔══██╗██╔════╝╚██╗ ██╔╝ // █████╗ ███████║███████╗ ╚████╔╝ // ██╔══╝ ██╔══██║╚════██║ ╚██╔╝ // ███████╗██║ ██║███████║ ██║ // ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ // // ██████╗ ██████╗ ██╗███╗ ██╗████████╗ // ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ // ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ // ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ // ██║ ██║ ██║██║██║ ╚████║ ██║ // ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ // // ██████╗ ██████╗ ███╗ ██╗███████╗ ██████╗ ██╗ ███████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝██╔═══██╗██║ ██╔════╝ // ██║ ██║ ██║██╔██╗ ██║███████╗██║ ██║██║ █████╗ // ██║ ██║ ██║██║╚██╗██║╚════██║██║ ██║██║ ██╔══╝ // ╚██████╗╚██████╔╝██║ ╚████║███████║╚██████╔╝███████╗███████╗ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚══════╝╚══════╝ // █ █ █▀█ █ █ █ ▀█▀ █▀█ █ █ █▀ █▀▀ // █▀█ █▄█ ▀▄▀▄▀ █ █▄█ █▄█ ▄█ ██▄ // Make sure your strategy overlay is false // █ █▄ █ █▀ ▀█▀ ▄▀█ █ █ // █ █ ▀█ ▄█ █ █▀█ █▄▄ █▄▄ // import keio/console/2 as console // var log = console.init() // █▀█ █▀█ █ █▄ █ ▀█▀ // █▀▀ █▀▄ █ █ ▀█ █ // log := console.print(log, "message") // █▀█ █▀█ ▀█▀ █ █▀█ █▄ █ ▄▀█ █ // █▄█ █▀▀ █ █ █▄█ █ ▀█ █▀█ █▄▄ // You can also specify the number of lines displayed and the number of panes/columns // Simply pass the 'lines' and 'panes' parameters when initializing, for example: // var log = console(lines=10, panes=4) // Lines are limited to 60, default is 5 // Panes are limited to 20, default is 8 // █▀▀ ▀▄▀ ▄▀█ █▀▄▀█ █▀█ █ █▀▀ █▀ ▀█▀ █▀█ ▄▀█ ▀█▀ █▀▀ █▀▀ █▄█ // ██▄ █ █ █▀█ █ ▀ █ █▀▀ █▄▄ ██▄ ▄█ █ █▀▄ █▀█ █ ██▄ █▄█ █ // //@version=5 // strategy("example", overlay=false) // import keio/console/2 as console // var log = console.init() // var int long = 0 // longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) // if (longCondition) // long += 1 // log := console.print(log, "Long entry : " + str.tostring(long)) // strategy.entry("long", strategy.long) // strategy.exit(id = "long exit", from_entry = "long", limit=close, stop=close) // █ █ █▄▄ █▀█ ▄▀█ █▀█ █▄█ █▀▀ █▀█ █▀▄ █▀▀ // █▄▄ █ █▄█ █▀▄ █▀█ █▀▄ █ █▄▄ █▄█ █▄▀ ██▄ var MAX_ENTRIES = 1200 var MAX_LINES = 60 var MAX_PANES = 20 // @function init() function. USAGE : var log = console.init() // @param lines Optional. Number of lines to display // @param panes Optional. Number of panes to display // @returns initialised log export init(int lines=5, int panes=8) => // Set configuration parameters int n_lines = (na(lines) or lines <= 0 or lines > MAX_LINES) ? MAX_LINES : lines int n_panes = (na(panes) or panes <= 0) ? 1 : (panes > MAX_PANES ? MAX_PANES : panes) // Initialise log string[] log = array.new_string(MAX_ENTRIES) // Save parameters array.push(log, str.tostring(n_lines)) array.push(log, str.tostring(n_panes)) // Return log log // @function Prints a message to the console. USAGE : log := console.print(log, "message") // @param log The log returned from the init() function // @param input Message to be displayed in the console // @returns The log export print(string[] log, string input) => // Extract configuration parameters int panes = math.floor(str.tonumber(array.pop(log))) int lines = math.floor(str.tonumber(array.pop(log))) // Save new log input array.push(log, input) // Discard oldest log input array.shift(log) // Create console table var table console = table.new( position=position.bottom_left, columns=panes, rows=1, border_color=color.new(color.white, 50), border_width=1 ) // Concatenate and display log inputs for p = 0 to panes-1 string content = na for i = 0 to lines-1 content += array.get(log, MAX_ENTRIES-(p+1)*lines+i) + "\n" table.cell( table_id=console, column=panes-1-p, row=0, text=content, width=100/panes, height=100, bgcolor=color.black, text_size=size.small, text_valign=text.align_bottom, text_halign=text.align_left, text_color=color.white ) // Save configuration parameters array.push(log, str.tostring(lines)) array.push(log, str.tostring(panes)) // Return log log // ███████╗██╗███╗ ███╗██████╗ ██╗ ███████╗ // ██╔════╝██║████╗ ████║██╔══██╗██║ ██╔════╝ // ███████╗██║██╔████╔██║██████╔╝██║ █████╗ // ╚════██║██║██║╚██╔╝██║██╔═══╝ ██║ ██╔══╝ // ███████║██║██║ ╚═╝ ██║██║ ███████╗███████╗ // ╚══════╝╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝╚══════╝ // // ██████╗ █████╗ ███████╗██╗ ██████╗ // ██╔══██╗██╔══██╗██╔════╝██║██╔════╝ // ██████╔╝███████║███████╗██║██║ // ██╔══██╗██╔══██║╚════██║██║██║ // ██████╔╝██║ ██║███████║██║╚██████╗ // ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ // // https://www.youtube.com/watch?v=2bjk26RwjyU
_matrix
https://www.tradingview.com/script/hXS05TdU-matrix/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
46
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Library helps visualize matrix as array of arrays and enables users to use array methods such as push, pop, shift, unshift etc along with cleanup activities on drawing objects wherever required library("_matrix") import HeWhoMustNotBeNamed/arrays/1 as pa remove_row_from_matrix(mtx, rowNumber)=>matrix.remove_row(mtx, rowNumber) delete_row_from_matrix(mtx, rowNumber)=>pa.clear(remove_row_from_matrix(mtx, rowNumber)) unshift_to_matrix(mtx, row, maxItems)=> matrix.add_row(mtx, 0, row) if(matrix.rows(mtx) > maxItems) delete_row_from_matrix(mtx, matrix.rows(mtx)-1) mtx push_to_matrix(mtx, row, maxItems)=> matrix.add_row(mtx, matrix.rows(mtx), row) if(matrix.rows(mtx) > maxItems) delete_row_from_matrix(mtx, 0) mtx // @function deletes row from a matrix // @param mtx matrix of objects // @param rowNumber row index to be deleted // @returns void export delete(simple matrix<line> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<label> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<box> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<linefill> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<table> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<int> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<float> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<bool> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<string> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) export delete(simple matrix<color> mtx, int rowNumber)=>delete_row_from_matrix(mtx, rowNumber) // @function remove row from a matrix and returns them to caller // @param mtx matrix of objects // @param rowNumber row index to be deleted // @returns type[] export remove(simple matrix<line> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<label> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<box> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<linefill> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<table> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<int> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<float> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<bool> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<string> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) export remove(simple matrix<color> mtx, int rowNumber)=>remove_row_from_matrix(mtx, rowNumber) // @function unshift array of lines to first row of the matrix // @param mtx matrix of lines // @param row array of lines to be inserted in row // @returns resulting matrix of type export unshift(simple matrix<line> mtx, line[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<label> mtx, label[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<box> mtx, box[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<linefill> mtx, linefill[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<table> mtx, table[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<int> mtx, int[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<float> mtx, float[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<bool> mtx, bool[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<string> mtx, string[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) export unshift(simple matrix<color> mtx, color[] row, simple int maxItems)=>unshift_to_matrix(mtx, row, maxItems) // @function push array of lines to end of the matrix row // @param mtx matrix of lines // @param row array of lines to be inserted in row // @returns resulting matrix of lines export push(simple matrix<line> mtx, line[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<label> mtx, label[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<box> mtx, box[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<linefill> mtx, linefill[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<table> mtx, table[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<int> mtx, int[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<float> mtx, float[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<bool> mtx, bool[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<string> mtx, string[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) export push(simple matrix<color> mtx, color[] row, simple int maxItems)=>push_to_matrix(mtx, row, maxItems) // @function shift removes first row from matrix of lines // @param mtx matrix of lines from which the shift operation need to be performed // @returns void export shift(simple matrix<line> mtx)=>delete(mtx, 0) export shift(simple matrix<label> mtx)=>delete(mtx, 0) export shift(simple matrix<box> mtx)=>delete(mtx, 0) export shift(simple matrix<linefill> mtx)=>delete(mtx, 0) export shift(simple matrix<table> mtx)=>delete(mtx, 0) export shift(simple matrix<int> mtx)=>delete(mtx, 0) export shift(simple matrix<float> mtx)=>delete(mtx, 0) export shift(simple matrix<bool> mtx)=>delete(mtx, 0) export shift(simple matrix<string> mtx)=>delete(mtx, 0) export shift(simple matrix<color> mtx)=>delete(mtx, 0) // @function rshift removes first row from matrix of lines and returns them as array // @param mtx matrix of lines from which the rshift operation need to be performed // @returns type[] export rshift(simple matrix<line> mtx)=>remove(mtx, 0) export rshift(simple matrix<label> mtx)=>remove(mtx, 0) export rshift(simple matrix<box> mtx)=>remove(mtx, 0) export rshift(simple matrix<linefill> mtx)=>remove(mtx, 0) export rshift(simple matrix<table> mtx)=>remove(mtx, 0) export rshift(simple matrix<int> mtx)=>remove(mtx, 0) export rshift(simple matrix<float> mtx)=>remove(mtx, 0) export rshift(simple matrix<bool> mtx)=>remove(mtx, 0) export rshift(simple matrix<string> mtx)=>remove(mtx, 0) export rshift(simple matrix<color> mtx)=>remove(mtx, 0) // @function pop removes last row from matrix of lines // @param mtx matrix of lines from which the pop operation need to be performed // @returns void export pop(simple matrix<line> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<label> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<box> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<linefill> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<table> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<int> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<float> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<bool> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<string> mtx)=>delete(mtx, matrix.rows(mtx)-1) export pop(simple matrix<color> mtx)=>delete(mtx, matrix.rows(mtx)-1) // @function rpop removes last row from matrix of lines and reutnrs the array to caller // @param mtx matrix of lines from which the rpop operation need to be performed // @returns void export rpop(simple matrix<line> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<label> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<box> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<linefill> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<table> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<int> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<float> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<bool> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<string> mtx)=>remove(mtx, matrix.rows(mtx)-1) export rpop(simple matrix<color> mtx)=>remove(mtx, matrix.rows(mtx)-1) clear_matrix(mtx)=> while(matrix.rows(mtx) > 0) delete(mtx, 0) rclear_matrix(mtx)=> while(matrix.rows(mtx) > 0) remove(mtx, 0) // @function clear clears the matrix // @param mtx matrix of lines which needs to be cleared // @returns void export clear(simple matrix<line> mtx)=>clear_matrix(mtx) export clear(simple matrix<label> mtx)=>clear_matrix(mtx) export clear(simple matrix<box> mtx)=>clear_matrix(mtx) export clear(simple matrix<linefill> mtx)=>clear_matrix(mtx) export clear(simple matrix<table> mtx)=>clear_matrix(mtx) export clear(simple matrix<int> mtx)=>clear_matrix(mtx) export clear(simple matrix<float> mtx)=>clear_matrix(mtx) export clear(simple matrix<bool> mtx)=>clear_matrix(mtx) export clear(simple matrix<string> mtx)=>clear_matrix(mtx) export clear(simple matrix<color> mtx)=>clear_matrix(mtx) // @function clear clears the matrix but retains the drawing objects // @param mtx matrix of lines which needs to be cleared // @returns void export rclear(simple matrix<line> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<label> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<box> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<linefill> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<table> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<int> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<float> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<bool> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<string> mtx)=>rclear_matrix(mtx) export rclear(simple matrix<color> mtx)=>rclear_matrix(mtx)
drawingutils
https://www.tradingview.com/script/A4AW15ho-drawingutils/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
22
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Private methods used in my scripts for some basic and customized drawings. library("drawingutils") import HeWhoMustNotBeNamed/utils/1 as ut export draw_line(float y1, float y2, int x1, int x2, color lineColor, int width, string style, line[] linesArray) => targetLine = line.new(y1=y1, y2=y2, x1=x1, x2=x2, color=lineColor, width=width, style=style) array.push(linesArray, targetLine) targetLine export draw_label(float y, int x, string txt, color textcolor, string style, string yloc, string size, label[] labelsArray) => targetLabel = label.new(y=y, x=x, text=txt, textcolor=textcolor, style=style, yloc=yloc, size=size) array.push(labelsArray, targetLabel) export draw_linefill(line ln1, line ln2, color fillColor, int transparency, linefill[] lineFillArray) => lnfl = linefill.new(ln1, ln2, color.new(fillColor, transparency)) array.push(lineFillArray, lnfl) export draw_labelled_line(float target, string lblText, color linecolor, color labelcolor, int index, bool highlight, line[] linesArray, label[] labelsArray, string normalSize = size.normal, string tinySize = size.tiny, string yloc = yloc.price) => x1 = bar_index + 20*index*2 x2 = x1 + 20 xloc = xloc.bar_index style = yloc == yloc.price? label.style_none : yloc == yloc.abovebar ? label.style_label_down : label.style_label_up targetLine = line.new(x1=x1, y1=target, x2=x2, y2=target, color=linecolor, xloc =xloc, extend=extend.none, style=highlight ? line.style_solid : line.style_dotted) targetLabel = label.new(x=(x1+x2)/2, y=target, text=lblText + '\n' + str.tostring(math.round_to_mintick(target)), xloc=xloc, style=style, textcolor=highlight ? labelcolor : color.new(labelcolor, 70), size=highlight ? normalSize : tinySize, color=color.new(labelcolor, 100)) array.push(linesArray, targetLine) array.push(labelsArray, targetLabel) export draw_labelled_box(float y1, float y2, color labelColor, string labelText, int index, box[] boxArray, label[] labelArray, color borderColor = color.blue, string borderStyle=line.style_dotted, int borderWidth = 1, string textAlign = text.align_right, bool highlight = true, bool highLightLabel = false) => x1 = bar_index + 20*index*2 x2 = x1 + 20 y = (y1 + y2) / 2 transp = highlight? 70 : 90 transpLabel = highlight? 0 : 50 labelSize = highLightLabel? size.normal : size.small bx = box.new(x1, y1, x2, y2, borderColor, borderWidth, borderStyle, bgcolor=color.new(labelColor, transp)) lbl = label.new(x=x2, y=y, text=labelText, yloc=yloc.price, color=labelColor, style=label.style_none, textcolor=color.new(labelColor, transpLabel), size=labelSize, textalign=textAlign) array.push(labelArray, lbl) array.push(boxArray, bx) export runTimer(simple string timerPosition = position.top_center, color backgroundColor=color.green, color textColor = color.white, string lblSize = size.small)=> var startBar = bar_index var startTime = time barDiff = bar_index - startBar [days, tHours, tMinutes, tSeconds, tmSeconds] = ut.timer(startTime) if(barstate.islast) var timer = table.new(position=timerPosition, columns=12, rows=1, border_width=0) table.cell(table_id=timer, column=0, row=0, text=str.tostring(days, "00"), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=1, row=0, text="/", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=2, row=0, text=str.tostring(tHours, "00"), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=3, row=0, text=":", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=4, row=0, text=str.tostring(tMinutes, "00"), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=5, row=0, text=":", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=6, row=0, text=str.tostring(tSeconds, "00"), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=7, row=0, text=".", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=8, row=0, text=str.tostring(tmSeconds), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=9, row=0, text="[", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=10, row=0, text=str.tostring(barDiff), bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) table.cell(table_id=timer, column=11, row=0, text="]", bgcolor=backgroundColor, text_color=textColor, text_size=lblSize) export watermark(string content, simple string tblPosition=position.middle_center, simple color textColor = color.aqua, simple int transparency=80, simple string textSize = size.huge)=> if(barstate.islast) var watermark = table.new(position=tblPosition, columns=1, rows=1, border_width=0) table.cell(table_id=watermark, column=0, row=0, text=content, text_color=color.new(textColor, transparency), text_size=textSize)
merge_pinbar
https://www.tradingview.com/script/KfC20nCV-merge-pinbar/
dandrideng
https://www.tradingview.com/u/dandrideng/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © dandrideng //@version=5 // @description merge_pinbar: merge bars and check whether the bar is a pinbar library("merge_pinbar", overlay=true) // @function merge_pinbar: merge bars and check whether the bar is a pinbar // @param simple int period: the statistic bar period // @param simple int max_bars: the max bars to be merged // @returns array: [bar_type, bar_num, pbar_strength] export merge_pinbar(simple int period, simple int max_bars) => float upperwick = open > close ? high - open: high - close float lowerwick = open > close ? close - low: open - low float candlebody = open > close ? open - close: close - open float totalbody = high - low float upperwick_ma = ta.sma(upperwick, period) float lowerwick_ma = ta.sma(lowerwick, period) float candlebody_ma = ta.sma(candlebody, period) float totalbody_ma = ta.sma(totalbody, period) int pbar_type = 0 int pbar_num = 0 float pbar_strength = 0.0 for bars = 1 to max_bars float _open = open[bars - 1] float _high = ta.highest(high, bars) float _low = ta.lowest(low, bars) float _close = close float _upperwick = _open > _close ? _high - _open: _high - _close float _lowerwick = _open > _close ? _close - _low: _open - _low float _candlebody = _open > _close ? _open - _close: _close - _open float _totalbody = _high - _low float _upperwick_ratio = _upperwick / upperwick_ma float _lowerwick_ratio = _lowerwick / lowerwick_ma float _candlebody_ratio = _candlebody / candlebody_ma float _totalbody_ratio = _totalbody / totalbody_ma if _candlebody_ratio < 3.0 and _upperwick_ratio < 2.0 and _lowerwick / _candlebody > 2.0 pbar_type := 1 pbar_num := bars pbar_strength := math.log(_lowerwick / _candlebody - _upperwick / _candlebody * 2.0) * _totalbody_ratio break else if _candlebody_ratio < 3.0 and _lowerwick_ratio < 2.0 and _upperwick / _candlebody > 2.0 pbar_type := -1 pbar_num := bars pbar_strength := math.log(_upperwick / _candlebody - _lowerwick / _candlebody * 2.0) * _totalbody_ratio break else continue [pbar_type, pbar_num, pbar_strength]
Library Common
https://www.tradingview.com/script/UJIcCeYc-Library-Common/
Wheeelman
https://www.tradingview.com/u/Wheeelman/
8
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Wheeelman // Last Updated: 9th March, 2022 //@version=5 // @description A collection of custom tools & utility functions commonly used with my scripts // @description TODO: add library description here library("MyLibrary") // --- BEGIN UTILITY FUNCTIONS { // @function Calculates how many decimals are on the quote price of the current market // @returns The current decimal places on the market quote price export getDecimals() => math.abs(math.log(syminfo.mintick) / math.log(10)) // @function Truncates (cuts) excess decimal places // @param float number The number to truncate // @param float decimalPlaces (default=2) The number of decimal places to truncate to // @returns The given number truncated to the given decimalPlaces export truncate(float number, simple float decimalPlaces = 2.0) => factor = math.pow(10, decimalPlaces) int(number * factor) / factor // @function Converts pips into whole numbers // @param float number The pip number to convert into a whole number // @returns The converted number export toWhole(float number) => _return = number < 1.0 ? number / syminfo.mintick / (10 / syminfo.pointvalue) : number _return := number >= 1.0 and number <= 100.0 ? _return * 100 : _return // @function Converts whole numbers back into pips // @param float number The whole number to convert into pips // @returns The converted number export toPips(float number) => number * syminfo.mintick * 10 // @function Gets the percentage change between 2 float values over a given lookback period // @param float value1 The first value to reference // @param float value2 The second value to reference // @param int lookback The lookback period to analyze export getPctChange(float value1, float value2, int lookback) => vChange = value1 - value2 vDiff = vChange - vChange[lookback] (vDiff / vChange) * 100 // @function Calculates OANDA forex position size for AutoView based on the given parameters // @param float balance The account balance to use // @param float risk The risk percentage amount (as a whole number - eg. 1 = 1% risk) // @param float stopPoints The stop loss distance in POINTS (not pips) // @param float conversionRate The conversion rate of our account balance currency // @returns The calculated position size (in units - only compatible with OANDA) export av_getPositionSize(float balance, float risk, float stopPoints, float conversionRate) => riskAmount = balance * (risk / 100) * conversionRate riskPerPoint = stopPoints * syminfo.pointvalue positionSize = riskAmount / riskPerPoint / syminfo.mintick math.round(positionSize) // } END UTILITY FUNCTIONS // --- BEGIN TA FUNCTIONS { // @function Calculates a bullish fibonacci value // @param priceLow The lowest price point // @param priceHigh The highest price point // @param fibRatio The fibonacci % ratio to calculate // @returns The fibonacci value of the given ratio between the two price points export bullFib(float priceLow, float priceHigh, float fibRatio = 0.382) => (priceLow - priceHigh) * fibRatio + priceHigh // @function Calculates a bearish fibonacci value // @param priceLow The lowest price point // @param priceHigh The highest price point // @param fibRatio The fibonacci % ratio to calculate // @returns The fibonacci value of the given ratio between the two price points export bearFib(float priceLow, float priceHigh, float fibRatio = 0.382) => (priceHigh - priceLow) * fibRatio + priceLow // @function Gets a Moving Average based on type (MUST BE CALLED ON EVERY CALCULATION) // @param int length The MA period // @param string maType The type of MA // @returns A moving average with the given parameters export getMA(simple int length, string maType) => switch maType "EMA" => ta.ema(close, length) "SMA" => ta.sma(close, length) "HMA" => ta.hma(close, length) "WMA" => ta.wma(close, length) "VWMA" => ta.vwma(close, length) "VWAP" => ta.vwap => e1 = ta.ema(close, length) e2 = ta.ema(e1, length) 2 * e1 - e2 // @function Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20) // @param float atr The given ATR to base the EAP SL calculation on // @returns The EAP SL converted ATR size export getEAP(float atr) => atrWhole = toWhole(atr) // First convert ATR to whole number for consistency across markets eapStopWhole = atrWhole // Then if ATR is above 1 full integer, leave it alone as it's already a whole number // If ATR is between 20 and 30 pips, set stop distance to 20 pips if atrWhole >= 20.0 and atrWhole < 30.0 eapStopWhole := 20.0 // If ATR is between 30 and 50 pips, set stop distance to 30 pips if atrWhole >= 30.0 and atrWhole < 50.0 // If ATR is between 50 and 100 pips, set stop distance to 50 pips eapStopWhole := 30.0 if atrWhole >= 50.0 and atrWhole < 100.0 eapStopWhole := 50.0 // If ATR is above 100 pips, set stop distance to 100 pips if atrWhole >= 100.0 eapStopWhole := 100.0 // Convert EAP SL from whole number back into pips toPips(eapStopWhole) // @function Performs secondary EAP stop loss size calculation (eg. ATR < 40, add 5 pips, ATR between 40-50, add 10 pips etc) // @param float atr The given ATR to base the EAP SL calculation on // @returns The EAP SL converted ATR size export getEAP2(float atr) => atrWhole = toWhole(atr) // First convert ATR to whole number for consistency across markets eapStopWhole = atrWhole // If ATR is below 40, add 5 pips if atrWhole < 40.0 eapStopWhole := eapStopWhole + 5.0 // If ATR is between 40-50, add 10 pips if atrWhole >= 40.0 and atrWhole <= 50.0 eapStopWhole := eapStopWhole + 10.0 // If ATR is between 50-200, add 20 pips if atrWhole > 50.0 and atrWhole <= 200.0 eapStopWhole := eapStopWhole + 20.0 // Convert EAP SL from whole number back into pips toPips(eapStopWhole) // @function Counts how many candles are above the MA // @param int lookback The lookback period to look back over // @param float ma The moving average to check // @returns The bar count of how many recent bars are above the MA export barsAboveMA(int lookback, float ma) => counter = 0 for i = 1 to lookback by 1 if close[i] > ma[i] counter := counter + 1 counter // @function Counts how many candles are below the MA // @param int lookback The lookback period to look back over // @param float ma The moving average to reference // @returns The bar count of how many recent bars are below the EMA export barsBelowMA(int lookback, float ma) => counter = 0 for i = 1 to lookback by 1 if close[i] < ma[i] counter := counter + 1 counter // @function Counts how many times the EMA was crossed recently // @param int lookback The lookback period to look back over // @param float ma The moving average to reference // @returns The bar count of how many times price recently crossed the EMA export barsCrossedMA(int lookback, float ma) => counter = 0 for i = 1 to lookback by 1 if open[i] > ma and close[i] < ma or open[i] < ma and close[i] > ma counter := counter + 1 counter // @function Counts how many green & red bars have printed recently (ie. pullback count) // @param int lookback The lookback period to look back over // @param int direction The color of the bar to count (1 = Green, -1 = Red) // @returns The bar count of how many candles have retraced over the given lookback & direction export getPullbackBarCount(int lookback, int direction) => recentCandles = 0 for i = 1 to lookback by 1 if direction == 1 and close[i] > open[i] // Count green bars recentCandles := recentCandles + 1 if direction == -1 and close[i] < open[i] // Count red bars recentCandles := recentCandles + 1 recentCandles // @function Gets the current candle's body size (in POINTS, divide by 10 to get pips) // @returns The current candle's body size in POINTS export getBodySize() => math.abs(close - open) / syminfo.mintick // @function 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 export getTopWickSize() => math.abs(high - (close > open ? close : open)) / syminfo.mintick // @function 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 export getBottomWickSize() => math.abs((close < open ? close : open) - low) / syminfo.mintick // @function 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 export getBodyPercent() => math.abs(open - close) / math.abs(high - low) // } END TA FUNCTIONS // --- BEGIN CANDLE SETUP DETECTION { // @function Checks if the current bar is a hammer candle based on the given parameters // @param float fib (default=0.382) The fib to base candle body on // @param bool colorMatch (default=false) Does the candle need to be green? (true/false) // @returns A boolean - true if the current bar matches the requirements of a hammer candle export isHammer(float fib = 0.382, bool colorMatch = false) => bullFib = bullFib(low, high, fib) lowestBody = close < open ? close : open lowestBody >= bullFib and (not colorMatch or close > open) // @function Checks if the current bar is a shooting star candle based on the given parameters // @param float fib (default=0.382) The fib to base candle body on // @param bool colorMatch (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 export isStar(float fib = 0.382, bool colorMatch = false) => bearFib = bearFib(low, high, fib) highestBody = close > open ? close : open highestBody <= bearFib and (not colorMatch or close < open) // @function Checks if the current bar is a doji candle based on the given parameters // @param float wickSize (default=2) The maximum top wick size compared to the bottom (and vice versa) // @param bool bodySize (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 export isDoji(float wickSize = 2.0, float bodySize = 0.05) => getTopWickSize() <= getBottomWickSize() * wickSize and getBottomWickSize() <= getTopWickSize() * wickSize and getBodyPercent() <= bodySize // @function Checks if the current bar is a bullish engulfing candle // @param float allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps) // @param float rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage // @param bool engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well? // @returns A boolean - true if the current bar matches the requirements of a bullish engulfing candle export isBullishEC(float allowance = 0.0, float rejectionWickSize = 0.0, bool engulfWick = false) => (close[1] <= open[1] and close >= open[1] and open <= close[1] + allowance) and (not engulfWick or close >= high[1]) and (rejectionWickSize == 0.0 or getTopWickSize() / getBodySize() < rejectionWickSize) // @function Checks if the current bar is a bearish engulfing candle // @param float allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps) // @param float rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage // @param bool engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well? // @returns A boolean - true if the current bar matches the requirements of a bearish engulfing candle export isBearishEC(float allowance = 0.0, float rejectionWickSize = 0.0, bool engulfWick = false) => (close[1] >= open[1] and close <= open[1] and open >= close[1] - allowance) and (not engulfWick or close <= low[1]) and (rejectionWickSize == 0.0 or getBottomWickSize() / getBodySize() < rejectionWickSize) // @function Detects inside bars // @returns Returns true if the current bar is an inside bar export isInsideBar() => high < high[1] and low > low[1] // @function Detects outside bars // @returns Returns true if the current bar is an outside bar export isOutsideBar() => high > high[1] and low < low[1] // } END CANDLE SETUP DETECTION // --- BEGIN FILTER FUNCTIONS { // @function Determines if the current price bar falls inside the specified session // @param string sess The session to check // @param bool useFilter (default=true) Whether or not to actually use this filter // @returns A boolean - true if the current bar falls within the given time session export barInSession(simple string sess, bool useFilter = true) => na(time(timeframe.period, sess + ":1234567")) == false or not useFilter // @function Determines if the current price bar falls outside the specified session // @param string sess The session to check // @param bool useFilter (default=true) Whether or not to actually use this filter // @returns A boolean - true if the current bar falls outside the given time session export barOutSession(simple string sess, bool useFilter = true) => na(time(timeframe.period, sess + ":1234567")) or not useFilter // @function Determines if this bar's time falls within date filter range // @param int startTime The UNIX date timestamp to begin searching from // @param int endTime the UNIX date timestamp to stop searching from // @returns A boolean - true if the current bar falls within the given dates export dateFilter(int startTime, int endTime) => time >= startTime and time <= endTime // @function Checks if the current bar's day is in the list of given days to analyze // @param bool monday Should the script analyze this day? (true/false) // @param bool tuesday Should the script analyze this day? (true/false) // @param bool wednesday Should the script analyze this day? (true/false) // @param bool thursday Should the script analyze this day? (true/false) // @param bool friday Should the script analyze this day? (true/false) // @param bool saturday Should the script analyze this day? (true/false) // @param bool sunday Should the script analyze this day? (true/false) // @returns A boolean - true if the current bar's day is one of the given days export dayFilter(bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, bool sunday) => dayofweek == dayofweek.monday and monday or dayofweek == dayofweek.tuesday and tuesday or dayofweek == dayofweek.wednesday and wednesday or dayofweek == dayofweek.thursday and thursday or dayofweek == dayofweek.friday and friday or dayofweek == dayofweek.saturday and saturday or dayofweek == dayofweek.sunday and sunday // @function Checks the current bar's size against the given ATR and max size // @param float atrValue (default=ATR 14 period) The given ATR to check // @param float maxSize The maximum ATR multiplier of the current candle // @returns A boolean - true if the current bar's size is less than or equal to atr x maxSize _atr = ta.atr(14) export atrFilter(float atrValue = 1111, float maxSize) => maxSize == 0.0 or math.abs(high - low) <= (atrValue == 1111 ? _atr : atrValue) * maxSize // } END FILTER FUNCTIONS // --- BEGIN DISPLAY FUNCTIONS { // @function This updates the given table's cell with the given values // @param table tableID The table ID to update // @param int column The column to update // @param int row The row to update // @param string title The title of this cell // @param string value The value of this cell // @param color bgcolor The background color of this cell // @param color txtcolor The text color of this cell // @returns A boolean - true if the current bar falls within the given dates export fillCell(table tableID, int column, int row, string title, string value, color bgcolor, color txtcolor) => cellText = title + "\n" + value table.cell(tableID, column, row, cellText, bgcolor=bgcolor, text_color=txtcolor) // } END DISPLAY FUNCTIONS
arrays
https://www.tradingview.com/script/D1igBUy9-arrays/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
32
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Library contains utility functions using arrays. These are mostly customized for personal use. Hence, will not add documentation to it. library("arrays") unshift_to_array(arr, val, maxItems)=> array.insert(arr, 0, val) if(array.size(arr) > maxItems) array.pop(arr) arr push_to_array(arr, val, maxItems)=> array.push(arr, val) if(array.size(arr) > maxItems) array.remove(arr, 0) arr export delete(simple line[] arr, int index)=>line.delete(array.remove(arr, index)) export delete(simple label[] arr, int index)=>label.delete(array.remove(arr, index)) export delete(simple box[] arr, int index)=>box.delete(array.remove(arr, index)) export delete(simple table[] arr, int index)=>table.delete(array.remove(arr, index)) export delete(simple linefill[] arr, int index)=>linefill.delete(array.remove(arr, index)) export delete(simple int[] arr, int index)=>array.remove(arr, index) export delete(simple float[] arr, int index)=>array.remove(arr, index) export delete(simple bool[] arr, int index)=>array.remove(arr, index) export delete(simple string[] arr, int index)=>array.remove(arr, index) export delete(simple color[] arr, int index)=>array.remove(arr, index) export pop(simple line[] arr)=>line.delete(array.pop(arr)) export pop(simple label[] arr)=>label.delete(array.pop(arr)) export pop(simple box[] arr)=>box.delete(array.pop(arr)) export pop(simple table[] arr)=>table.delete(array.pop(arr)) export pop(simple linefill[] arr)=>linefill.delete(array.pop(arr)) export pop(simple int[] arr)=>array.pop(arr) export pop(simple float[] arr)=>array.pop(arr) export pop(simple bool[] arr)=>array.pop(arr) export pop(simple string[] arr)=>array.pop(arr) export pop(simple color[] arr)=>array.pop(arr) unshift_to_object_array(arr, val, maxItems)=> array.insert(arr, 0, val) if(array.size(arr) > maxItems) pop(arr) arr export shift(simple line[] arr)=>line.delete(array.shift(arr)) export shift(simple label[] arr)=>label.delete(array.shift(arr)) export shift(simple box[] arr)=>box.delete(array.shift(arr)) export shift(simple table[] arr)=>table.delete(array.shift(arr)) export shift(simple linefill[] arr)=>linefill.delete(array.shift(arr)) export shift(simple int[] arr)=>array.shift(arr) export shift(simple float[] arr)=>array.shift(arr) export shift(simple bool[] arr)=>array.shift(arr) export shift(simple string[] arr)=>array.shift(arr) export shift(simple color[] arr)=>array.shift(arr) push_to_object_array(arr, val, maxItems)=> array.push(arr, val) if(array.size(arr) > maxItems) shift(arr) arr export unshift(simple int[] arr, int val, simple int maxItems)=>unshift_to_array(arr, val, maxItems) export unshift(simple float[] arr, float val, simple int maxItems)=>unshift_to_array(arr, val, maxItems) export unshift(simple bool[] arr, bool val, simple int maxItems)=>unshift_to_array(arr, val, maxItems) export unshift(simple string[] arr, string val, simple int maxItems)=>unshift_to_array(arr, val, maxItems) export unshift(simple color[] arr, color val, simple int maxItems)=>unshift_to_array(arr, val, maxItems) export unshift(simple line[] arr, line val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems) export unshift(simple label[] arr, label val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems) export unshift(simple box[] arr, box val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems) export unshift(simple table[] arr, table val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems) export unshift(simple linefill[] arr, linefill val, simple int maxItems)=>unshift_to_object_array(arr, val, maxItems) clear_array_objects(arr)=> len = array.size(arr)-1 for i=0 to len >=0 ? len:na pop(arr) export clear(simple line[] arr)=>clear_array_objects(arr) export clear(simple label[] arr)=>clear_array_objects(arr) export clear(simple box[] arr)=>clear_array_objects(arr) export clear(simple table[] arr)=>clear_array_objects(arr) export clear(simple linefill[] arr)=>clear_array_objects(arr) export clear(simple int[] arr)=>array.clear(arr) export clear(simple float[] arr)=>array.clear(arr) export clear(simple bool[] arr)=>array.clear(arr) export clear(simple string[] arr)=>array.clear(arr) export clear(simple color[] arr)=>array.clear(arr) export push(simple int[] arr, int val, simple int maxItems)=>push_to_array(arr, val, maxItems) export push(simple float[] arr, float val, simple int maxItems)=>push_to_array(arr, val, maxItems) export push(simple bool[] arr, bool val, simple int maxItems)=>push_to_array(arr, val, maxItems) export push(simple string[] arr, string val, simple int maxItems)=>push_to_array(arr, val, maxItems) export push(simple color[] arr, color val, simple int maxItems)=>push_to_array(arr, val, maxItems) export push(simple line[] arr, line val, simple int maxItems)=>push_to_object_array(arr, val, maxItems) export push(simple label[] arr, label val, simple int maxItems)=>push_to_object_array(arr, val, maxItems) export push(simple box[] arr, box val, simple int maxItems)=>push_to_object_array(arr, val, maxItems) export push(simple table[] arr, table val, simple int maxItems)=>push_to_object_array(arr, val, maxItems) export push(simple linefill[] arr, linefill val, simple int maxItems)=>push_to_object_array(arr, val, maxItems)
RicardoLibrary
https://www.tradingview.com/script/Zw6Ngdnl-RicardoLibrary/
costatrindade01
https://www.tradingview.com/u/costatrindade01/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © costatrindade01 //@version=5 // @description Ricardo's personal Library library("RicardoLibrary") // @function GetPipValue // @returns Pip value of Symbol export GetPipValue() => Currency = syminfo.currency PipValue = Currency == "JPY" ? 0.01 : 0.0001 PipValue // @function Calculate_SL: Calcultes Stop Loss // @param IsLong If true, then I am going to enter a long position, if false then Short position // @returns Stop loss Price export Calculate_SL(bool IsLong, float Pips) => sl_price = 0.0 if IsLong == true sl_price := close - Pips * GetPipValue() if IsLong == false sl_price := close + Pips * GetPipValue() sl_price
percentageLib
https://www.tradingview.com/script/DAHvut75-percentageLib/
crypto1-ejarehkhodro
https://www.tradingview.com/u/crypto1-ejarehkhodro/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © crypto1-ejarehkhodro //@version=5 // @description : every thing need anout percentage // @useage : import crypto1-ejarhkhodro/percentageLib/1.0 as percentageLib library("percentageLib") error(txt) => // Create label on the first bar. var lbl = label.new(bar_index, na, txt, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // On next bars, update the label's x and y position, and the text it displays. label.set_xy(lbl, bar_index, ta.highest(10)[1]) label.set_text(lbl, txt) // @function : get percentage change of of two value // @param entry : value of entry price // @param exit : value of exit price // @returns : negative or positive value export getPercentage(float entry,float exit,bool ignoreError = false) => var float percentage = 0 if entry!= 0 percentage := ((exit - entry) / entry ) * 100 else if ignoreError == false error("Error : getPercentage(float entry,float exit) Entry can not price is zero!") percentage := 0 percentage // @function : apply percentage change on value decrease or increase // @param price : value of price // @param percentage : percentage change can be negative or positive // @returns : return only positive value export applyPercentageNoAddUp(float price,float percentage) => ((price * percentage)/100) // @function : apply percentage change on value decrease or increase // @param price : value of price // @param percentage : percentage change can be negative or positive // @returns : return only positive value export applyPercentageAddUp(float price,float percentage) => price + applyPercentageNoAddUp(price,percentage) // @function : get percentage (positive or negative) and return the percentage need to back to previous price // @param percentage : percentage change can be negative or positive // @returns : return positive/negative value // @example : reversePercentage(-10) =>11.11111111111111111111111 , reversePercentage(10) =>9.0909090909090909 export reversePercentage(float percentage) => (100 * percentage)/(100 + percentage) //plot(reversePercentage(10)) //plot(reversePercentage(-10)) // @function : get two prices and return the percentage need to back to previous price // @param price : value of price // @param percentage : percentage change can be negative or positive // @returns : return only positive value // @example : getReversePercentage(100,90) =>11.11111111111111111111111 export getReversePercentage(float entry,float exit) => reversePercentage(getPercentage(entry,exit)) //plot(getReversePercentage(100,90)) //plot(getReversePercentage(100,110)) // @function : get array of percentage change and return final percentage change // @param percentage : array of percentage change can be positive and negative // @returns : return negative or positive percentage value // @example : following //var float[] a = array.new_float() //var bool doOnce = true //if doOnce == true // array.push(a,50) // array.push(a,20) // array.push(a,10) // array.push(a,-10.0) // array.push(a,-40.0) // doOnce := false //plot(multipeBarTotalPercentage(a)) //draw 6.92 line export multipeBarTotalPercentage(float[] percentages) => float multipeBarPercentage = 0 for i = 0 to array.size(percentages) - 1 multipeBarPercentage := multipeBarPercentage + array.get(percentages,i) + applyPercentageNoAddUp(multipeBarPercentage,array.get(percentages,i)) multipeBarPercentage
STPFunctions
https://www.tradingview.com/script/j0db5YWG-STPFunctions/
ice-e-fresh
https://www.tradingview.com/u/ice-e-fresh/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // All code writted by ice-e-fresh // Trading Strategies and Entry Signales care of Pete Renzulli and the STP Community // @version=5 // @description These functions are used as part of the STP trading strategy and include commonly used candle patterns, trade triggers and frequently monitored stock parameters library("STPFunctions", overlay=true) // @function Determines if the last price is abover or below key moving averages. MAs used on the daily are SMA20, SMA50 and SMA200. SMA20 and SMA50 are used intraday. // @returns 1 if the last price/close was over the moving averages. -1 is returned if the last price/close is below the moving averages. 0 is returned otherwise. export MAs() => SMA200 = ta.sma(close,200) SMA50 = ta.sma(close,50) SMA20 = ta.sma(close,20) timeframe.isdaily ? (((0.95 * SMA200 < close) and (SMA50 < close) and (SMA20 < close) and (SMA20 > SMA50)) ? 1 : ((1.05 * SMA200 > close) and (SMA50 > close) and (SMA20 > close) and (SMA20 < SMA50)) ? -1 : 0) : (((SMA50 < close) and (SMA20 < close) and (SMA20 > SMA50)) ? 1 : ((SMA50 > close) and (SMA20 > close) and (SMA20 < SMA50)) ? -1 : 0) // @function Determine the state of the higher time frame order flow. // @param HTF1_open float value representing the higher time frame open. // @param HTF2_open float value representing the higher time frame open. // @returns 1 if the last price/close was over the higher time frame open. -1 is returned if the last price/close is below the higher time frame open. 0 is returned otherwise. export HTFOrderFlow(float HTF1_open = 0, float HTF2_open = 0) => HTFOrderFlow = ((HTF1_open < close) and (HTF2_open < close)) ? 1 : ((HTF1_open > close) and (HTF2_open > close)) ? -1 : 0 // @function Determine the recent order flow... basically are we well bid or well offered // @returns 1 if the last 2 candles are well bid. -1 is returned if the last 2 candles are well offered. 0 is returned otherwise. export OrderFlow(float o = 0, float h = 0, float l = 0, float c = 0, float prev_h = 0, float prev_l = 0, float prev_c = 0) => previousBar = 1 (h > prev_h and l > prev_l and c > o and c > prev_c and c > prev_h) ? 1 : (h < prev_h and l < prev_l and c < o and c < prev_c and c < prev_l) ? -1 : 0 // @function Used to flag inside candles // @returns 1 if the close >= open. -1 is returned if the close <= open. 0 is returned otherwise. export isInside() => previousBar = 1 bodyStatus = (close >= open) ? 1 : -1 isInsidePattern = high < high[previousBar] and low > low[previousBar] isInsidePattern ? bodyStatus : 0 // @function Used to flag outside or engulfing candles // @returns 1 if the close >= open. -1 is returned if the close <= open. 0 is returned otherwise. export isOutside() => previousBar = 1 bodyStatus = (close >= open) ? 1 : -1 isOutsidePattern = high > high[previousBar] and low > low[previousBar] isOutsidePattern ? bodyStatus : 0 // @function Used to flag the U-turn reversal pattern // @returns 1 for a BUTN. -1 is returned for a BRUTN. 0 is returned otherwise. export isUTN() => previousBar = 1 (high < high[previousBar] and close[previousBar] < open[previousBar] and close > close[previousBar] and low < low[previousBar] and close > low[previousBar] and close > open and close < high[previousBar]) ? 1 : (low > low[previousBar] and close[previousBar] > open[previousBar] and close < close[previousBar] and high > high[previousBar] and close < high[previousBar] and close < open and close > low[previousBar]) ? -1 : 0 // @function Flag for Snapback Entries // @returns 1 for a bullish snapback setup. -1 is returned for a bearish snapback setup. 0 is returned otherwise. export isSNapBack() => //work in progress 0
mZigzag
https://www.tradingview.com/script/z6PqvzZD-mZigzag/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
192
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Matrix implementation of zigzag to allow further possibilities. // Main advantage of this library over previous zigzag methods is that you can attach any number of indicator/oscillator information to zigzag library("mZigzag", overlay=true) import HeWhoMustNotBeNamed/_matrix/5 as ma import HeWhoMustNotBeNamed/arrays/1 as pa import HeWhoMustNotBeNamed/enhanced_ta/14 as eta import HeWhoMustNotBeNamed/supertrend/6 as st pivots(length, float[] ohlc) => highSource = array.max(ohlc) lowSource = array.min(ohlc) int phighbar = ta.highestbars(highSource, length) int plowbar = ta.lowestbars(lowSource, length) float phigh = ta.highest(highSource, length) float plow = ta.lowest(lowSource, length) [phigh, phighbar, plow, plowbar] calculateDivergence(oDir, pDir, sDir) => divergence = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3) divergence getSentimentDetails(sentiment) => sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣' sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I' [sentimentSymbol, sentimentLabel, sentimentColor] addnewpivot(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, value, bar, dir, indicatorHigh, indicatorLow, numberOfPivots, supertrendDir)=> array<float> indicatorArray = dir > 0? indicatorHigh[bar_index-bar] : indicatorLow[bar_index-bar] if(na(indicatorArray)) indicatorArray := array.new_float(array.size(indicatorHigh)) newValueArray = array.from(value) array.concat(newValueArray, indicatorArray) size = array.size(newValueArray) newRatios = array.new_float(size, 1.0) newDirections = array.new_int(size, int(dir)) newDivergences = array.new_int(size, 0) newDoubleDivergences =array.new_int(size, 0) if(matrix.rows(valueMatrix)>=2) lastValues = matrix.row(valueMatrix, matrix.rows(valueMatrix)-1) llastValues = matrix.row(valueMatrix, matrix.rows(valueMatrix)-2) llastDivergence = matrix.row(divergenceMatrix, matrix.rows(divergenceMatrix)-2) for i = 0 to array.size(lastValues)-1 cValue = array.get(newValueArray, i) lastPoint = array.get(lastValues, i) llastPoint = array.get(llastValues, i) newDir = dir * cValue > dir * llastPoint ? dir * 2 : dir newRatio = math.round(math.abs(cValue-lastPoint)/math.abs(llastPoint-lastPoint), 2) array.set(newDirections, i, int(newDir)) array.set(newRatios, i, newRatio) pDir = array.get(newDirections, 0) divergence = calculateDivergence(newDir, pDir, supertrendDir) array.set(newDivergences, i, divergence) doubleDivergence = 0 if(matrix.rows(valueMatrix) >= 4) lastDivergence = array.get(llastDivergence, i) doubleDivergence := divergence == lastDivergence ? divergence : 0 array.set(newDoubleDivergences, i, doubleDivergence) ma.push(valueMatrix, newValueArray, numberOfPivots) ma.push(directionMatrix, newDirections, numberOfPivots) ma.push(ratioMatrix, newRatios, numberOfPivots) ma.push(divergenceMatrix, newDivergences, numberOfPivots) ma.push(doubleDivergenceMatrix, newDoubleDivergences, numberOfPivots) pa.push(barArray, bar, numberOfPivots) pa.push(trendArray, supertrendDir, numberOfPivots) addnewpivotplain(valueMatrix, directionArray, barArray, value, bar, dir, indicatorHigh, indicatorLow, numberOfPivots)=> array<float> indicatorArray = dir > 0? indicatorHigh[bar_index-bar] : indicatorLow[bar_index-bar] if(na(indicatorArray)) indicatorArray := array.new_float(array.size(indicatorHigh)) newValueArray = array.from(value) array.concat(newValueArray, indicatorArray) size = array.size(newValueArray) newDir = dir if(matrix.rows(valueMatrix)>=2) llastValue = matrix.get(valueMatrix, 1, 0) newDir := dir * value > dir * llastValue ? dir * 2 : dir ma.unshift(valueMatrix, newValueArray, numberOfPivots) pa.unshift(directionArray, newDir, numberOfPivots) pa.unshift(barArray, bar, numberOfPivots) zigzagcore(int length, float[] ohlc, float[] indicatorHigh, float[] indicatorLow, simple int numberOfPivots=20, simple int supertrendLength=5) => var matrix<float> valueMatrix = matrix.new<float>() var matrix<int> directionMatrix = matrix.new<int>() var matrix<float> ratioMatrix = matrix.new<float>() var matrix<int> divergenceMatrix = matrix.new<int>() var matrix<int> doubleDivergenceMatrix = matrix.new<int>() var array<int> barArray = array.new<int>() var array<int> trendArray = array.new<int>() [phigh, phighbar, plow, plowbar] = pivots(length, ohlc) float pDir = 1 newPivot = phighbar == 0 or plowbar == 0 doublePivot = phighbar == 0 and plowbar == 0 updateLastPivot = false int supertrendDir = na float supertrend = na if(matrix.rows(valueMatrix) > supertrendLength*2 + 1) zigzagpivotArray = array.copy(matrix.col(valueMatrix, 0)) array.reverse(zigzagpivotArray) [sDir, sTrend] = st.zsupertrend(zigzagpivotArray, supertrendLength) supertrendDir := sDir supertrend := sTrend if(matrix.columns(directionMatrix) >=1) pDir := math.sign(matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0)) newBar = bar_index if ((pDir == 1 and phighbar == 0) or (pDir == -1 and plowbar == 0)) and matrix.rows(valueMatrix)>=1 value = pDir == 1 ? phigh : plow ipivot = pDir == 1? plow : phigh pivotbar = array.get(barArray, matrix.rows(valueMatrix)-1) pivot = matrix.get(valueMatrix, matrix.rows(valueMatrix)-1, 0) pivotdir = matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0) removeOld = value * pivotdir > pivot * pivotdir addInverse = false if(removeOld) updateLastPivot := true ma.pop(valueMatrix) ma.pop(ratioMatrix) ma.pop(directionMatrix) ma.pop(divergenceMatrix) ma.pop(doubleDivergenceMatrix) pa.pop(barArray) pa.pop(trendArray) addnewpivot(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, value, newBar, pDir, indicatorHigh, indicatorLow, numberOfPivots, supertrendDir) if(matrix.rows(valueMatrix) > 1 and doublePivot) llastPivot = matrix.get(valueMatrix, matrix.rows(valueMatrix)-2, 0) if(-pDir*llastPivot >= -pDir*ipivot) addInverse := true else if (not removeOld and not doublePivot) or addInverse ipivotbar = pDir == 1? newBar+plowbar : newBar+phighbar ipivottime = time[newBar-ipivotbar] addnewpivot(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, ipivot, ipivotbar, -pDir, indicatorHigh, indicatorLow, numberOfPivots, supertrendDir) doublePivot := true if (pDir == 1 and plowbar == 0) or (pDir == -1 and phighbar == 0) value = pDir == 1 ? plow : phigh addnewpivot(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, value, newBar, -pDir, indicatorHigh, indicatorLow, numberOfPivots, supertrendDir) [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newPivot, doublePivot] zigzagcoreplain(int length, float[] ohlc, float[] indicatorHigh, float[] indicatorLow, simple int numberOfPivots=20, simple int offset=0) => var matrix<float> valueMatrix = matrix.new<float>() var array<int> directionArray = array.new<int>() var array<int> barArray = array.new<int>() [phigh, phighbar, plow, plowbar] = pivots(length, ohlc) float pDir = 1 newZG = false doubleZG = phigh and plow if(array.size(directionArray) > 0) pDir := math.sign(array.get(directionArray, 0)) if ((pDir == 1 and phigh) or (pDir == -1 and plow)) and matrix.rows(valueMatrix)>=1 pivotbar = array.shift(barArray) pivot = matrix.get(valueMatrix, 0, 0) pivotdir = array.shift(directionArray) ma.shift(valueMatrix) value = pDir == 1 ? phigh : plow useNewValues = value * pivotdir > pivot * pivotdir value := useNewValues ? value : pivot bar = useNewValues ? (bar_index-offset) : pivotbar newZG := useNewValues addnewpivotplain(valueMatrix, directionArray, barArray, value, bar, pDir, indicatorHigh, indicatorLow, numberOfPivots) if (pDir == 1 and plow) or (pDir == -1 and phigh) value = pDir == 1 ? plow : phigh bar = bar_index-offset dir = pDir == 1 ? -1 : 1 newZG := true addnewpivotplain(valueMatrix, directionArray, barArray, value, bar, dir, indicatorHigh, indicatorLow, numberOfPivots) [valueMatrix, directionArray, barArray, newZG, doubleZG] draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, indicatorLabels, lineColor, lineWidth, lineStyle, showLabel, showIndicators) => if matrix.rows(valueMatrix) > 2 idxLen1 = matrix.rows(valueMatrix)-idx1 idxLen2 = matrix.rows(valueMatrix)-idx2 lastValues = matrix.row(valueMatrix, idxLen1) llastValues = matrix.row(valueMatrix, idxLen2) lastDirections = matrix.row(directionMatrix, idxLen1) lastRatios = matrix.row(ratioMatrix, idxLen1) lastDivergence = matrix.row(divergenceMatrix, idxLen1) lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1) y1 = array.get(lastValues, 0) y2 = array.get(llastValues, 0) x1 = array.get(barArray, idxLen1) x2 = array.get(barArray, idxLen2) zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle) currentDir = y1 > y2? 1 : -1 label zlabel = na if(showLabel) allLabels = array.from('Price') array.concat(allLabels, indicatorLabels) color lblColor = na array<string> allLabelsArray = array.new<string>() for int i = 0 to array.size(allLabels)-1 dir = array.get(lastDirections, i) ratio = array.get(lastRatios, i) [hhllText, labelColor] = switch dir 1 => ["LH", color.orange] 2 => ["HH", color.green] -1 => ["HL", color.lime] -2 => ["LL", color.red] => ["NA", color.silver] lblColor := na(lblColor)? labelColor : lblColor lbl = array.get(allLabels, i) + " : " + str.tostring(array.get(lastValues, i)) + (i==0 ? " - " +str.tostring(array.get(lastRatios, i)) : "") + " ( " + hhllText + " )" if(i!=0) divergence = array.get(lastDivergence, i) doubleDivergence = array.get(lastDoubleDivergence, i) [dSymbol, dLabel, dColor] = getSentimentDetails(divergence) [ddSymbol, ddLabel, ddColor] = getSentimentDetails(doubleDivergence) lbl := lbl + ' ' + str.tostring(dSymbol) + ' ' + str.tostring(ddSymbol) array.push(allLabelsArray, lbl) finalLabel = showIndicators? array.join(allLabelsArray, '\n') : array.get(allLabelsArray, 0) tooltip = showIndicators? '' : array.join(allLabelsArray, '\n') labelStyle = currentDir > 0? label.style_label_down : label.style_label_up zlabel := label.new(x=x1, y=y1, yloc=yloc.price, color=lblColor, style=labelStyle, text=finalLabel, textcolor=color.black, size = size.small, tooltip=tooltip) if array.size(zigzaglines) > 0 lastLine = array.get(zigzaglines, array.size(zigzaglines)-1) if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1 pa.pop(zigzaglines) pa.pop(zigzaglabels) pa.push(zigzaglines, zline, 500) pa.push(zigzaglabels, zlabel, 500) // @function calculates zigzag and related information // @param length is zigzag length // @param ohlc array of OHLC values to be used for zigzag calculation // @param indicatorHigh Array of indicator values calculated based on high price of OHLC // @param indicatorLow Array of indicators values calculated based on low price of OHLC // @param numberOfPivots Number of pivots to be returned // @param supertrendLength is number of pivot history to calculate supertrend // @returns valueMatrix Matrix containing zigzag pivots for price and indicators // directionMatrix Matrix containing direction of price and indicator values at pivots // ratioMatrix Matrix containing ratios of price and indicator values at pivots // divergenceMatrix matrix containing divergence details for each indicators // doubleDivergenceMatrix matrix containing double divergence details for each indicators // barArray Array containing pivot bars // supertrendDir is direction of zigzag based supertrend // supertrend is supertrend value of zigzag based supertrend // newZG is true if a new pivot is added to array // doubleZG is true if last calculation returned two new pivots (Happens on extreme price change) export calculate(simple int length, float[] ohlc, float[] indicatorHigh, float[] indicatorLow, simple int numberOfPivots=20, simple int supertrendLength = 5) => zigzagcore(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots, supertrendLength) // @function calculates zigzag and related information uses shift/unshift rather than pop and push. Also does not calculate divergence and ratios. // @param length is zigzag length // @param ohlc array of OHLC values to be used for zigzag calculation // @param indicatorHigh Array of indicator values calculated based on high price of OHLC // @param indicatorLow Array of indicators values calculated based on low price of OHLC // @param numberOfPivots Number of pivots to be returned // @returns valueMatrix Matrix containing zigzag pivots for price and indicators // directionArray Matrix containing direction of price and indicator values at pivots // barArray Array containing pivot bars // newZG is true if a new pivot is added to array // doubleZG is true if last calculation returned two new pivots (Happens on extreme price change) export calculateplain(simple int length, float[] ohlc, float[] indicatorHigh, float[] indicatorLow, simple int numberOfPivots=20, simple int offset=0) => zigzagcoreplain(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots, offset) // @function draws zigzag and related information based on preprocessed values // @param valueMatrix is matrix containing values of price and indicators // @param directionMatrix is matrix containing direction of price and indicators // @param ratioMatrix is matrix containing retracement ratios of price and indicators // @param barArray is array of pivot bars // @param newZG is bool which tells whether new zigzag pivot is formed or not // @param doubleZG is bool which teels us if the bar has both high and low zigzag // @param lineColor zigzag line color. set to blue by default // @param lineWidth zigzag line width. set to 1 by default // @param lineStyle zigzag line style. set to line.style_solid by default // @param showLabel Show pivot label // @param showIndicators Include indicators in labels. If set to false, indicators are shown as tooltips // @returns valueMatrix Matrix containing zigzag pivots for price and indicators // directionMatrix Matrix containing direction of price and indicator values at pivots // ratioMatrix Matrix containing ratios of price and indicator values at pivots // divergenceMatrix matrix containing divergence details for each indicators // doubleDivergenceMatrix matrix containing double divergence details for each indicators // barArray Array containing pivot bars // zigzaglines array of zigzag lines // zigzaglabels array of zigzag labels export draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, bool newZG, bool doubleZG, string[] indicatorLabels, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid, bool showLabel=true, bool showIndicators=true)=> var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newZG) if doubleZG draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, indicatorLabels, lineColor, lineWidth, lineStyle, showLabel, showIndicators) if matrix.rows(valueMatrix) >= 2 draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, indicatorLabels, lineColor, lineWidth, lineStyle, showLabel, showIndicators) [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels] // @function draws zigzag and related information // @param length is zigzag length // @param ohlc array of OHLC values to be used for zigzag calculation // @param indicatorLabels Array of name of indicators passed // @param indicatorHigh Array of indicator values calculated based on high price of OHLC // @param indicatorLow Array of indicators values calculated based on low price of OHLC // @param numberOfPivots Number of pivots to be returned // @param lineColor zigzag line color. set to blue by default // @param lineWidth zigzag line width. set to 1 by default // @param lineStyle zigzag line style. set to line.style_solid by default // @param showLabel Show pivot label // @param showIndicators Include indicators in labels. If set to false, indicators are shown as tooltips // @returns valueMatrix Matrix containing zigzag pivots for price and indicators // directionMatrix Matrix containing direction of price and indicator values at pivots // ratioMatrix Matrix containing ratios of price and indicator values at pivots // divergenceMatrix matrix containing divergence details for each indicators // doubleDivergenceMatrix matrix containing double divergence details for each indicators // barArray Array containing pivot bars // zigzaglines array of zigzag lines // zigzaglabels array of zigzag labels export draw(simple int length, float[] ohlc, string[] indicatorLabels, float[] indicatorHigh, float[] indicatorLow, simple int numberOfPivots=20, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid, bool showLabel=true, bool showIndicators=true) => [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newZG, doubleZG] = zigzagcore(length, ohlc, indicatorHigh, indicatorLow, numberOfPivots) draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, newZG, doubleZG, indicatorLabels, lineColor, lineWidth, lineStyle, showLabel, showIndicators) // Usage Example(s) // //*********************** Debug method *************************// // i_start = 0 // i_page = 100 // i_maxLogSize = 1000 // i_showHistory = false // i_showBarIndex = false // var DebugArray = array.new_string(0) // var DebugBarArray = array.new_string(0) // add_to_debug_array(arr, val, maxItems) => // array.unshift(arr, str.tostring(val)) // if array.size(arr) > maxItems // array.pop(arr) // debug(debugMsg) => // if barstate.islast or i_showHistory // barTimeString = str.tostring(year, '0000') + '/' + str.tostring(month, '00') + '/' + str.tostring(dayofmonth, '00') + (timeframe.isintraday ? '-' + str.tostring(hour, '00') + ':' + str.tostring(minute, '00') + ':' + str.tostring(second, '00') : '') // add_to_debug_array(DebugBarArray, i_showBarIndex ? str.tostring(bar_index) : barTimeString, i_maxLogSize) // add_to_debug_array(DebugArray, debugMsg, i_maxLogSize) // //*********************** Debug method *************************// // length = input.int(8) // showIndicators = input.bool(false) // includeMa = input.bool(true, "Moving Average", inline="ma", group="Indicators") // matype = input.string("sma", title="", group="Indicators", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "median"], inline="ma") // malength = input.int(20, title="", group="Indicators", inline="ma") // includeOscillator = input.bool(true, "Oscillator", inline="osc", group="Indicators") // oscillatorType = input.string("rsi", title="", group="Indicators", inline="osc", options=["cci", "cmo", "cog", "mfi", "roc", "rsi"]) // oscLength = input.int(14, title="", group="Indicators", inline="osc") // includeVolume = input.bool(true, "Volume", inline="vol", group="Indicators") // volType = input.string("obv", title="", group="Indicators", inline="vol", options=["obv", "pvi", "nvi", "pvt", "vwap"]) // drawSupertrend = input.bool(true, "Draw Zigzag Supertrend", inline='st', group="Trend") // supertrendLength = input.int(5, '', inline='st', group='Trend') // indicatorHigh = array.new_float() // indicatorLow = array.new_float() // indicatorLabels = array.new_string() // if(includeMa) // maHigh = eta.ma(high, matype, malength) // maLow = eta.ma(low, matype, malength) // array.push(indicatorHigh, maHigh) // array.push(indicatorLow, maLow) // array.push(indicatorLabels, matype+str.tostring(malength)) // if(includeOscillator) // [oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high) // [oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low) // array.push(indicatorHigh, oscHigh) // array.push(indicatorLow, oscLow) // array.push(indicatorLabels, oscillatorType+str.tostring(oscLength)) // if(includeVolume) // volHigh = volType == "obv"? ta.obv: // volType == "pvi"? ta.pvi: // volType == "nvi"? ta.nvi: // volType == "pvt"? ta.pvt: ta.vwap(high) // volLow = volType == "obv"? ta.obv: // volType == "pvi"? ta.pvi: // volType == "nvi"? ta.nvi: // volType == "pvt"? ta.pvt: ta.vwap(low) // array.push(indicatorHigh, volHigh) // array.push(indicatorLow, volLow) // array.push(indicatorLabels, volType) // ohlc = array.from(open, high, low, close) // //Zigzag with any number of indicators // // draw(length, ohlc, indicatorLabels, indicatorHigh, indicatorLow, showIndicators = showIndicators) // // Simple zigzag without adding any indicators // // [pivotMatrix, zigzaglines, zigzaglabels] = draw(length, ohlc, array.new_string(), array.new_float(), array.new_float()) // // Just calculate without drawing zigzag // [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, supertrendDir, supertrend, newZG, doubleZG] = // calculate(length, ohlc, indicatorHigh, indicatorLow, supertrendLength = supertrendLength) // // [valueMatrix2, directionArray2, barArray2, newZG2, doubleZG2] = // // calculateplain(length, ohlc, indicatorHigh, indicatorLow) // // debug(directionMatrix) // // debug(directionArray2) // draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, newZG, doubleZG, indicatorLabels, showIndicators=showIndicators) // //drawplain(valueMatrix2, directionArray2, barArray2, newZG2, doubleZG2) - yet to be implemented // debug(ratioMatrix) // plot(drawSupertrend? supertrend:na, color=supertrendDir>0? color.green:color.red, style=plot.style_linebr) // //************************************************************ Print debug message on table ********************************************************/ // var debugTable = table.new(position=position.top_right, columns=2, rows=i_page + 1, border_width=1) // if array.size(DebugArray) > 0 // table.cell(table_id=debugTable, column=0, row=0, text=i_showBarIndex ? 'Bar Index' : 'Bar Time', bgcolor=color.teal, text_color=color.white, text_size=size.normal) // table.cell(table_id=debugTable, column=1, row=0, text='Debug Message', bgcolor=color.teal, text_color=color.white, text_size=size.normal) // for i = 0 to math.min(array.size(DebugArray) - 1 - i_start, i_page - 1) by 1 // table.cell(table_id=debugTable, column=0, row=i + 1, text=array.get(DebugBarArray, i + i_start), bgcolor=color.black, text_color=color.white, text_size=size.normal) // table.cell(table_id=debugTable, column=1, row=i + 1, text=array.get(DebugArray, i + i_start), bgcolor=color.black, text_color=color.white, text_size=size.normal) // //************************************************************ Finish Printing ********************************************************/
Strings
https://www.tradingview.com/script/rYX3lueB-Strings/
PineCoders
https://www.tradingview.com/u/PineCoders/
63
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © PineCoders //@version=5 // @description This library provides string manipulation functions to complement the Pine Script™ `str.*()` built-in functions. library("Strings", true) // Strings Library // v1, 2022.04.09 13:26 // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html // ———————————————————— Library functions { // @function Extracts the part of the `str` string that is left of the nth `occurrence` of the `separator` string. // @param str (series string) Source string. // @param separator (series string) Separator string. // @param occurrence (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence). // @returns (string) The extracted string. export leftOf(simple string str, simple string separator, simple int occurrence = 0) => str.match(str, "(?:[^" + separator + "]*" + separator + "){" + str.tostring(occurrence) + "}[^" + separator + "]*") export leftOf(series string str, series string separator, series int occurrence = 0) => str.match(str, "(?:[^" + separator + "]*" + separator + "){" + str.tostring(occurrence) + "}[^" + separator + "]*") // @function Extracts the part of the `str` string that is right of the nth `occurrence` of the `separator` string. // @param str (series string) Source string. // @param separator (series string) Separator string. // @param occurrence (series int) Occurrence of the separator string. Optional. The default value is zero (the 1st occurrence). // @returns (string) The extracted string. export rightOf(simple string str, simple string separator, simple int occurrence = 0) => string match = str.match(str, "([^" + separator + "]*" + separator + "\s*){" + str.tostring(occurrence + 1) + "}") string result = str.replace(str, match, "") export rightOf(series string str, series string separator, series int occurrence = 0) => string match = str.match(str, "([^" + separator + "]*" + separator + "\s*){" + str.tostring(occurrence + 1) + "}") string result = str.replace(str, match, "") // } // ———————————————————— Example Code { // Function to display one table cell. printCell(id, col, row, str, clr) => table.cell(id, col, row, str, text_color = clr, text_halign = text.align_left, text_size = size.normal) // Determine if the last chart price is high, in which case we will position the table at the bottom. bool lastPriceIsHigh = ta.percentrank(ohlc4, 100) > 50 // Display examples using a table. if barstate.islast string tablePosition = lastPriceIsHigh ? position.bottom_right : position.top_right var table display = table.new(tablePosition, 2, 3, color.new(color.black, 100), color.gray, 1, color.gray, 1) color codeColor = color.blue color resultColor = color.gray // Headers table.cell(display, 0, 0, "Code", bgcolor = color.new(color.fuchsia, 60), text_color = color.white, text_halign = text.align_left, text_size = size.normal) table.cell(display, 1, 0, "Result", bgcolor = color.new(color.lime, 60), text_color = color.white, text_halign = text.align_left, text_size = size.normal) // Left column printCell(display, 0, 1, 'leftOf("NASDAQ:MSFT", ":")\nleftOf("yyyy-mm-dd", "-", 2)', codeColor) printCell(display, 0, 2, 'rightOf("NASDAQ:MSFT", ":")\nrightOf("NASDAQ:MSFT, NASDAQ:TSLA", ":", 2)', codeColor) // Right column printCell(display, 1, 1, leftOf("NASDAQ:MSFT", ":") + "\n" + leftOf("yyyy-mm-dd", "-", 1), resultColor) printCell(display, 1, 2, rightOf("NASDAQ:MSFT", ":") + "\n" + rightOf("NASDAQ:MSFT, NASDAQ:TSLA", ":", 1), resultColor) // }
AutoFiboRetrace
https://www.tradingview.com/script/q8dfSHiE/
ZoomerXeus
https://www.tradingview.com/u/ZoomerXeus/
15
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © ZoomerXeus //@version=5 // @description TODO: This library is fibonacci calculator helper library("AutoFiboRetrace") // @function TODO: auto calculate fibnacci retrace by Highest and Lowest of Price // @param FPeriod TODO: lenght of candle for find highest and lowest // @param sourceLow TODO: source for find lowest value // @param sourceHigh TODO: source for find highest value // @param isUptrend : is uptrend // @returns TODO: List of Level price export autoCalculate(int FPeriod, float sourceLow, float sourceHigh, bool isUptrend) => Fhigh=ta.highest(sourceHigh, FPeriod) Flow=ta.lowest(sourceLow, FPeriod) Diff = Fhigh-Flow FL_0 = isUptrend ? Fhigh :Flow FL_236 = isUptrend ? Fhigh - (Diff*0.236) : Flow + (Diff*0.236) FL_382 = isUptrend ? Fhigh - (Diff*0.382) : Flow + (Diff*0.382) FL_500 = isUptrend ? Fhigh - (Diff*0.500) : Flow + (Diff*0.500) FL_618 = isUptrend ? Fhigh - (Diff*0.618) : Flow + (Diff*0.618) FL_786 = isUptrend ? Fhigh - (Diff*0.786) : Flow + (Diff*0.786) FL_1000 = isUptrend ? Fhigh - (Diff*1.000) : Flow + (Diff*1.000) FL_1236 = isUptrend ? Fhigh - (Diff*1.236) : Flow + (Diff*1.236) FL_1382 = isUptrend ? Fhigh - (Diff*1.382) : Flow + (Diff*1.382) FL_1500 = isUptrend ? Fhigh - (Diff*1.500) : Flow + (Diff*1.500) FL_1618 = isUptrend ? Fhigh - (Diff*1.618) : Flow + (Diff*1.618) FL_1786 = isUptrend ? Fhigh - (Diff*1.786) : Flow + (Diff*1.786) FL_2 = isUptrend ? Fhigh - (Diff*2) : Flow + (Diff*2) [FL_0,FL_236, FL_382, FL_500, FL_618, FL_786, FL_1000, FL_1236, FL_1382, FL_1500, FL_1618, FL_1786, FL_2] // @function TODO: calculate fibnacci retrace by fix high low value // @param lowValue TODO: low value // @param highValue TODO: high value // @param isUptrend : is uptrend // @returns TODO: List of Level price export fixCalculate(float lowValue, float highValue, bool isUptrend) => Fhigh=highValue Flow=lowValue Diff = Fhigh-Flow FL_0 = isUptrend ? Fhigh :Flow FL_236 = isUptrend ? Fhigh - (Diff*0.236) : Flow + (Diff*0.236) FL_382 = isUptrend ? Fhigh - (Diff*0.382) : Flow + (Diff*0.382) FL_500 = isUptrend ? Fhigh - (Diff*0.500) : Flow + (Diff*0.500) FL_618 = isUptrend ? Fhigh - (Diff*0.618) : Flow + (Diff*0.618) FL_786 = isUptrend ? Fhigh - (Diff*0.786) : Flow + (Diff*0.786) FL_1000 = isUptrend ? Fhigh - (Diff*1.000) : Flow + (Diff*1.000) FL_1236 = isUptrend ? Fhigh - (Diff*1.236) : Flow + (Diff*1.236) FL_1382 = isUptrend ? Fhigh - (Diff*1.382) : Flow + (Diff*1.382) FL_1500 = isUptrend ? Fhigh - (Diff*1.500) : Flow + (Diff*1.500) FL_1618 = isUptrend ? Fhigh - (Diff*1.618) : Flow + (Diff*1.618) FL_1786 = isUptrend ? Fhigh - (Diff*1.786) : Flow + (Diff*1.786) FL_2 = isUptrend ? Fhigh - (Diff*2) : Flow + (Diff*2) [FL_0,FL_236, FL_382, FL_500, FL_618, FL_786, FL_1000, FL_1236, FL_1382, FL_1500, FL_1618, FL_1786, FL_2] // @function TODO: auto calculate fibnacci retrace by Highest and Lowest of Price // @param FPeriod TODO: lenght of candle for find highest and lowest // @param sourceLow TODO: source for find lowest value // @param sourceHigh TODO: source for find highest value // @returns TODO: List of Level price export autoCalculateActionZone(int FPeriod, float sourceLow, float sourceHigh) => Fhigh=ta.highest(sourceHigh, FPeriod) Flow=ta.lowest(sourceLow, FPeriod) Diff = Fhigh-Flow FL_0 = Flow FL_236 = Flow + (Diff*0.236) FL_382 = Flow + (Diff*0.382) FL_618 = Flow + (Diff*0.618) FL_786 = Flow + (Diff*0.786) FL_1000 = Flow + (Diff*1.000) [FL_0,FL_236, FL_382, FL_618, FL_786, FL_1000] // @function TODO: calculate fibnacci retrace by fix high low value // @param lowValue TODO: low value // @param highValue TODO: high value // @returns TODO: List of Level price export fixCalculateActionZone(float lowValue, float highValue) => Fhigh=highValue Flow=lowValue Diff = Fhigh-Flow FL_0 = Flow FL_236 = Flow + (Diff*0.236) FL_382 = Flow + (Diff*0.382) FL_618 = Flow + (Diff*0.618) FL_786 = Flow + (Diff*0.786) FL_1000 = Flow + (Diff*1.000) [FL_0,FL_236, FL_382, FL_618, FL_786, FL_1000] // @function TODO: calculate fibnacci retrace by fix high low value // @param lowValue TODO: low value // @param highValue TODO: high value // @returns TODO: List of Level price export getSigmaFixCalculated(float lowValue, float highValue) => Fhigh=highValue Flow=lowValue Diff = Fhigh-Flow FL_0 = Flow FL_236 = Flow + (Diff*0.236) FL_382 = Flow + (Diff*0.382) FL_618 = Flow + (Diff*0.618) FL_786 = Flow + (Diff*0.786) FL_1000 = Flow + (Diff*1.000) openP = ta.ema(FL_382, 26) closeP = ta.ema(FL_382, 12) highP = ta.highest(closeP, 4) lowP = ta.lowest(closeP, 4) [openP, highP, lowP, closeP] // @function TODO: auto calculate fibnacci retrace by Highest and Lowest of Price // @param FPeriod TODO: lenght of candle for find highest and lowest // @param sourceLow TODO: source for find lowest value // @param sourceHigh TODO: source for find highest value // @returns TODO: List of Level price export getSigmaAutoCalculate(int FPeriod, float sourceLow, float sourceHigh) => Fhigh=ta.highest(sourceHigh, FPeriod) Flow=ta.lowest(sourceLow, FPeriod) Diff = Fhigh-Flow FL_0 = Flow FL_236 = Flow + (Diff*0.236) FL_382 = Flow + (Diff*0.382) FL_618 = Flow + (Diff*0.618) FL_786 = Flow + (Diff*0.786) FL_1000 = Flow + (Diff*1.000) openP = ta.ema(FL_382, 26) closeP = ta.ema(FL_382, 12) highP = ta.highest(closeP, 4) lowP = ta.lowest(closeP, 4) [openP, highP, lowP, closeP]
Canvas
https://www.tradingview.com/script/eJao1ymR-Canvas/
lejmer
https://www.tradingview.com/u/lejmer/
22
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © lejmer //@version=5 //@description A library implementing a kind of "canvas" using a table where each pixel is represented by a table cell and the pixel color by the background color of each cell. // To use the library, you need to create a color matrix (represented as an array) and a canvas table. // The canvas table is the container of the canvas, and the color matrix determines what color each pixel in the canvas should have. library("Canvas") var int BG_CLR_INDEX = 0 var int FG_CLR_INDEX = 1 var int META_DATA_ROWS = 2 var int MAX_ROWS = 100 //@function Function that returns the maximum size of the canvas (100). The canvas is always square, so the size is equal to rows (as opposed to not rows multiplied by columns). //@returns The maximum size of the canvas (100). export max_canvas_size() => //{ MAX_ROWS //} //@function Get the current background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas. //@param color_matrix The color matrix. //@returns The current background color. export get_bg_color(array<color> color_matrix) => //{ array.get(color_matrix, BG_CLR_INDEX) //} //@function Get the current foreground color of the color matrix. This is the default color used when drawing pixels. //@param color_matrix The color matrix. //@returns The current foreground color. export get_fg_color(array<color> color_matrix) => //{ array.get(color_matrix, FG_CLR_INDEX) //} //@function Set the background color of the color matrix. This is the default color used when erasing pixels or clearing a canvas. //@param color_matrix The color matrix. //@param bg_color The new background color. export set_bg_color(array<color> color_matrix, color bg_color) => //{ array.set(color_matrix, BG_CLR_INDEX, bg_color) //} //@function Set the foreground color of the color matrix. This is the default color used when drawing pixels. //@param color_matrix The color matrix. //@param fg_color The new foreground color. export set_fg_color(array<color> color_matrix, color fg_color) => //{ array.set(color_matrix, FG_CLR_INDEX, fg_color) //} //@function Function that returns how many rows a color matrix consists of. //@param color_matrix The color matrix. //@param rows (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. //@returns The number of rows a color matrix consists of. export color_matrix_rows(array<color> color_matrix, int rows = na) => //{ math.min(MAX_ROWS, na(rows) ? int(math.sqrt(array.size(color_matrix) - META_DATA_ROWS)) : rows) //} //@function Get the color of the pixel at the specified coordinates. //@param color_matrix The color matrix. //@param x The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param y The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param rows (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. //@returns The color of the pixel at the specified coordinates. export pixel_color(array<color> color_matrix, int x, int y, int rows = na) => //{ int matrix_rows = color_matrix_rows(color_matrix, rows) int index = x * matrix_rows + y + META_DATA_ROWS if (index >= 0 and index < array.size(color_matrix)) array.get(color_matrix, index) //} //@function Draw a pixel at the specified X and Y coordinates. Uses the specified color. //@param color_matrix The color matrix. //@param x The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param y The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param pixel_color The color of the pixel. //@param rows (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. export draw_pixel(array<color> color_matrix, int x, int y, color pixel_color, int rows = na) => //{ int matrix_rows = color_matrix_rows(color_matrix, rows) int index = x * matrix_rows + y + META_DATA_ROWS if (index >= 0 and index < array.size(color_matrix)) array.set(color_matrix, index, pixel_color) //} //@function Draw a pixel at the specified X and Y coordinates. Uses the current foreground color. //@param color_matrix The color matrix. //@param x The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param y The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param rows (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. export draw_pixel(array<color> color_matrix, int x, int y, int rows = na) => //{ draw_pixel(color_matrix, x, y, get_fg_color(color_matrix), rows) //} //@function Erase a pixel at the specified X and Y coordinates, replacing it with the background color. //@param color_matrix The color matrix. //@param x The X coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param y The Y coordinate for the pixel. Must be between 0 and "color_matrix_rows() - 1". //@param rows (Optional) The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. export erase_pixel(array<color> color_matrix, int x, int y, int rows = na) => //{ int matrix_rows = color_matrix_rows(color_matrix, rows) int index = x * matrix_rows + y + META_DATA_ROWS if (index >= 0 and index < array.size(color_matrix)) array.set(color_matrix, x * matrix_rows + y + META_DATA_ROWS, get_bg_color(color_matrix)) //} //@function Create and initialize a color matrix with the specified number of rows. The number of columns will be equal to the number of rows. //@param rows The number of rows the color matrix should consist of. This can be omitted, but if used, can speed up execution. It can never be greater than "max_canvas_size()". //@param bg_color (Optional) The initial background color. The default is black. //@param fg_color (Optional) The initial foreground color. The default is white. //@returns The array representing the color matrix. export init_color_matrix(simple int rows, color bg_color = #101010, color fg_color = #d6d6d6) => //{ array<color> color_matrix = array.new<color>(rows * rows + META_DATA_ROWS, bg_color) array.set(color_matrix, BG_CLR_INDEX, bg_color) array.set(color_matrix, FG_CLR_INDEX, fg_color) color_matrix //} //@function Create and initialize a canvas table. //@param color_matrix The color matrix. //@param pixel_width (Optional) The pixel width (in % of the pane width). The default width is 0.35%. //@param pixel_height (Optional) The pixel width (in % of the pane height). The default width is 0.60%. //@param position (Optional) The position for the table representing the canvas. The default is "position.middle_center". //@returns The canvas table. export init_canvas(array<color> color_matrix, float pixel_width = 0.35, float pixel_height = 0.6, string position = position.middle_center) => //{ int matrix_rows = color_matrix_rows(color_matrix) color bg_color = get_bg_color(color_matrix) float cell_width = math.min(math.max(pixel_width, 1e-16), 100 / float(matrix_rows)) float cell_height = math.min(math.max(pixel_height, 1e-16), 100 / float(matrix_rows)) table canvas = table.new( position = position, columns = matrix_rows, rows = matrix_rows, bgcolor = color.rgb(0, 0, 0, 100), border_color = bg_color, border_width = 0) for i = 0 to matrix_rows - 1 //{ for j = 0 to matrix_rows - 1 //{ table.cell(canvas, column = j, row = i, text = "", width = cell_width, height = cell_height, bgcolor = bg_color, text_color = bg_color) //} //} canvas //} //@function Clear a color matrix, replacing all pixels with the current background color. //@param color_matrix The color matrix. //@param rows The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. export clear(array<color> color_matrix, int rows = na) => //{ if (barstate.islast) //{ int matrix_rows = color_matrix_rows(color_matrix, rows) color bg_color = get_bg_color(color_matrix) for i = 0 to matrix_rows - 1 //{ for j = 0 to matrix_rows - 1 draw_pixel(color_matrix, i, j, bg_color, matrix_rows) //} //} //} //@function This updates the canvas with the colors from the color matrix. No changes to the canvas gets plotted until this function is called. //@param canvas The canvas table. //@param color_matrix The color matrix. //@param rows The number of rows of the color matrix. This can be omitted, but if used, can speed up execution. export update(table canvas, array<color> color_matrix, int rows = na) => //{ if (barstate.islast) //{ int matrix_rows = color_matrix_rows(color_matrix, rows) for i = 0 to matrix_rows - 1 //{ for j = 0 to matrix_rows - 1 table.cell_set_bgcolor(canvas, j, i, pixel_color(color_matrix, j, i, matrix_rows)) //} //} //} // ---------------------------------------------------------------------------------------------------------------------------- // Test code for the library. // ---------------------------------------------------------------------------------------------------------------------------- // Get the maximum canvas size possible. var int CANVAS_SIZE = max_canvas_size() // Create and initialize the color matrix. var array<color> color_matrix = init_color_matrix(CANVAS_SIZE) // Create and initialize the canvas table. var table canvas = init_canvas(color_matrix) // Clear the color matrix. clear(color_matrix) // Draw a face. if (barstate.islast) //{ // The left eye. draw_pixel(color_matrix, int(CANVAS_SIZE * 0.3), int(CANVAS_SIZE * 0.2)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.3 + 1), int(CANVAS_SIZE * 0.2)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.3 + 1), int(CANVAS_SIZE * 0.2 + 1)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.3), int(CANVAS_SIZE * 0.2 + 1)) // The right eye. draw_pixel(color_matrix, int(CANVAS_SIZE * 0.7), int(CANVAS_SIZE * 0.2)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.7 - 1), int(CANVAS_SIZE * 0.2)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.7 - 1), int(CANVAS_SIZE * 0.2 + 1)) draw_pixel(color_matrix, int(CANVAS_SIZE * 0.7), int(CANVAS_SIZE * 0.2 + 1)) // The mouth. float radius = CANVAS_SIZE * 0.3 for i = 0 to 180 //{ float radians = i * math.pi / 180 int pixel_x = int(CANVAS_SIZE * 0.5) + int(math.round(radius * math.cos(radians))) int pixel_y = int(CANVAS_SIZE * 0.5) + int(math.round(radius * math.sin(radians))) draw_pixel(color_matrix, pixel_x, pixel_y) //} //} // Plot the canvas. update(canvas, color_matrix)
Time
https://www.tradingview.com/script/tyeeNU9I-Time/
PineCoders
https://www.tradingview.com/u/PineCoders/
230
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © PineCoders //@version=5 library("Time", true) // Time Library // v4, 2023.03.10 // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html //#region ———————————————————— Library functions // @function Converts a UNIX timestamp (in milliseconds) to a formatted time string. // @param timeInMs (series float) Timestamp to be formatted. // @param format (series string) Format for the time. Optional. The default value is "HH:mm:ss". // @returns (string) A string containing the formatted time. export formattedTime(series float timeInMs, series string format = "HH:mm:ss") => string result = str.format("{0,time," + format + "}", int(timeInMs)) // EXAMPLES RESULT // formattedTime(timenow) >>> 00:40:35 // formattedTime(timenow, "short") >>> 12:40 AM // formattedTime(timenow, "full") >>> 12:40:35 AM UTC // formattedTime(1000 * 60 * 60 * 3.5, "HH:mm") >>> "03:30" // @function Converts a UNIX timestamp (in milliseconds) to a formatted date string. // @param timeInMs (series float) Timestamp to be formatted. // @param format (series string) Format for the date. Optional. The default value is "yyyy-MM-dd". // @returns (string) A string containing the formatted date. export formattedDate(series float timeInMs, series string format = "yyyy-MM-dd") => string result = str.format("{0,date," + format + "}", int(timeInMs)) // EXAMPLES RESULT // formattedDate(timenow, "short") >>> 4/5/22 // formattedDate(timenow, "medium") >>> Apr 5, 2022 // formattedDate(timenow, "full") >>> Tuesday, April 5, 2022 // @function Converts a UNIX timestamp (in milliseconds) to the name of the day of the week. // @param timeInMs (series float) Timestamp to be formatted. // @param format (series string) Format for the day of the week. Optional. The default value is "EEEE" (complete day name). // @returns (string) A string containing the day of the week. export formattedDay(series float timeInMs, series string format = "EEEE") => string result = str.format("{0,time," + format + "}", int(timeInMs)) // EXAMPLES RESULT // formattedDay(timenow, "E") >>> Tue // formattedDay(timenow, "dd.MM.yy") >>> 05.04.22 // formattedDay(timenow, "yyyy.MM.dd G 'at' hh:mm:ss z") >>> 2022.04.05 AD at 12:40:35 UTC // @function The duration in seconds that a condition has been true. // @param cond (series bool) Condition to time. // @param resetCond (series bool) When `true`, the duration resets. Optional. Default is `barstate.isnew`. // @returns (int) The duration in seconds for which `cond` is continuously true. export secondsSince(series bool cond, series bool resetCond = barstate.isnew) => varip int timeBegin = na varip bool lastCond = false if resetCond timeBegin := cond ? timenow : na else if cond if not lastCond timeBegin := timenow else timeBegin := na lastCond := cond int result = (timenow - timeBegin) / 1000 // @function Calculates a +/- time offset in variable units from the current bar's time or from the current time. // @param from (series string) Starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time. // @param qty (series int) The +/- qty of units of offset required. A "series float" can be used but it will be cast to a "series int". // @param units (series string) String containing one of the seven allowed time units: "chart" (chart's timeframe), "seconds", "minutes", "hours", "days", "months", "years". // @returns (int) The resultant time offset `from` the `qty` of time in the specified `units`. export timeFrom(series string from = "bar", series int qty, series string units) => int result = na string unit = str.match(units, ".*[^s]") int t = from == "bar" ? time : from == "close" ? time_close : timenow if units == "chart" result := int(t + (timeframe.in_seconds() * 1000 * qty)) else int y = year(t) + (unit == "year" ? qty : 0) int m = month(t) + (unit == "month" ? qty : 0) int d = dayofmonth(t) + (unit == "day" ? qty : 0) int hr = hour(t) + (unit == "hour" ? qty : 0) int min = minute(t) + (unit == "minute" ? qty : 0) int sec = second(t) + (unit == "second" ? qty : 0) result := timestamp(y, m, d, hr, min, sec) result // @function Converts a time value in ms to a quantity of time units. // @param ms (series int) Value of time to be formatted. // @param unit (series string) The target unit of time measurement. Options are "seconds", "minutes", "hours", "days", "weeks", "months". If not used one will be automatically assigned. // @returns (string) A formatted string from the number of `ms` in the specified `unit` of time measurement export formattedNoOfPeriods(series int ms, series string unit = na) => [tf, denominator] = if na(unit) switch ms < 60000 => ["seconds", 1000 ] ms < 3600000 => ["minutes", 60000 ] ms < 86400000 => ["hours", 3600000 ] ms < 604800000 => ["days", 86400000 ] ms < 2628003000 => ["weeks", 604800000 ] => ["months", 2628003000] else switch unit "seconds" => [unit, 1000 ] "minutes" => [unit, 60000 ] "hours" => [unit, 3600000 ] "days" => [unit, 86400000 ] "weeks" => [unit, 604800000 ] => [unit, 2628003000] float qty = math.round(ms / denominator, 2) string unitString = qty >= 2 ? tf : str.match(tf, ".*[^s]") string result = str.tostring(qty) + " " + unitString // @function Convert an input time in seconds to target string TF in `timeframe.period` string format. // @param tfInSeconds (simple int) a timeframe in seconds to convert to a string. // @param mult (simple float) Multiple of `tfInSeconds` to be calculated. Optional. 1 (no multiplier) is default. // @returns (string) The `tfInSeconds` in `timeframe.period` format usable with `request.security()`. export secondsToTfString(simple int tfInSeconds, simple float mult = 1.0) => float tfInMin = tfInSeconds / 60 * math.max(mult, 1) string result = switch tfInMin <= 0.017 => "1S" tfInMin <= 0.084 => "5S" tfInMin <= 0.167 => "10S" tfInMin <= 0.251 => "15S" tfInMin <= 0.501 => "30S" tfInMin < 1440 => str.tostring(math.round(tfInMin)) tfInMin % 10080 == 0 => str.tostring(tfInMin / 10080) + "W" tfInMin % 43800 == 0 => str.tostring(tfInMin / 43800) + "M" tfInMin <= 43800 => str.tostring(math.round(math.min(tfInMin / 1440, 365))) + "D" => str.tostring(math.round(math.min(tfInMin / 43800, 12))) + "M" //#endregion //#region ———————————————————— Example Code // —————————— Constants string SI1 = "tiny", string TP1 = "top" string SI2 = "small", string TP2 = "middle" string SI3 = "normal", string TP3 = "bottom" string SI4 = "large", string TP4 = "left" string SI5 = "huge", string TP5 = "center" string SI6 = "auto", string TP6 = "right" string TU1 = "chart", string OF1 = "Bar's Open Time" string TU2 = "seconds", string OF2 = "Bar's Close Time" string TU3 = "minutes", string OF3 = "Current Time" string TU4 = "hours", string TU5 = "days" string TU6 = "weeks", string TU7 = "months" string TU8 = "years", string N_TT = "Number of time units to calculate the line offset. Example: 20 hours." string UNITS_TT = "Unit of time to calculate the offset for lines in." string FROM_TT = "Starting time from where the offset for lines is calculated." string TICKS_TT = "The number of ticks between the open and the high to trigger the alert. Once the value is exceeded the timer will start." string SEC_TT = "Seconds for which the condition must be continuously true before the alert triggers." string RESET_TT = "When checked, the duration will reset every time a new realtime bar begins." string INPUT_TT = "When checked, will measure the length of the lines in the following units of time, otherwise will select a unit of time automatically." string TIME_TT = "Units to measure the length of the lines in." string MULT_TT = "Multiplier for the chart timeframe string. \nExample: 1 will display the current time, 2 will display 2 times the chart time, etc." string SIZE_TT = "Changes the size of the display table." string POS_TT = "Changes the position of the display table on the screen." int LEFT_BARS = 20 int RIGHT_BARS = 20 // —————————— Inputs string GRP1 = "══════════ Seconds since ══════════" int ticksInput = input.int(0, "Number Of Ticks From Open", group = GRP1, tooltip = TICKS_TT) float secondsInput = input.int(20, "Seconds condition must last", group = GRP1, tooltip = SEC_TT, minval = 1) bool resetInput = input.bool(true, "Reset timing on new bar", group = GRP1, tooltip = RESET_TT) string GRP2 = "═══════════   Time from   ═══════════" int nInput = input.int(20, "Lines End At Offset n (+/-)", group = GRP2, tooltip = N_TT) string unitsInput = input.string(TU1, "Offset Units", group = GRP2, tooltip = UNITS_TT, options = [TU1, TU2, TU3, TU4, TU5, TU7, TU8]) string fromInput = input.string(OF1, "Calculated from", group = GRP2, tooltip = FROM_TT, options = [OF1, OF2, OF3]) string GRP3 = "══════ Formatted number of periods ══════" bool useTimeInput = input.bool(false, "Use Input Time", group = GRP3, tooltip = INPUT_TT) string timeInput = input.string("seconds", "Unit of Time", group = GRP3, tooltip = TIME_TT, options = [TU2, TU3, TU4, TU5, TU6, TU7]) string GRP4 = "═════════   Seconds to string   ═════════" float tfMultInput = input.float(1.0, "Timeframe Multiplier", group = GRP4, tooltip = MULT_TT) string textSizeInput = input.string("large", "Text size", group = GRP4, tooltip = SIZE_TT, options = [SI1, SI2, SI3, SI4, SI5, SI6]) string tableYposInput = input.string("bottom", "Position  ", group = GRP4, tooltip = POS_TT, options = [TP1, TP2, TP3], inline = "41") string tableXposInput = input.string("right", "", group = GRP4, options = [TP4, TP5, TP6], inline = "41") // —————————— Conditions and Display // Condition triggering the display of lines. float pivotHi = ta.pivothigh(LEFT_BARS, RIGHT_BARS) float pivotLo = ta.pivotlow(LEFT_BARS, RIGHT_BARS) // Base to calculate offset from. string from = switch fromInput OF1 => "bar" OF2 => "close" => "now" // Calculate offset. int timeTo = timeFrom(from, nInput, unitsInput) int pivotTime = time[RIGHT_BARS] int offsetTime = timeTo[RIGHT_BARS] // Set time unit for `formattedNoOfPeriods()` time measurement. string timeUnit = useTimeInput ? timeInput : na // Check for new pivots and draw labels and lines when found. if not na(pivotHi) line.new(pivotTime, pivotHi, offsetTime, pivotHi, xloc.bar_time, color = color.fuchsia, style = line.style_arrow_right, width = 2) label.new(pivotTime, pivotHi, formattedDate(pivotTime, "full"), xloc.bar_time, color = color.new(color.gray, 85), style = label.style_label_down, textcolor = color.lime) label.new(time, pivotHi, formattedNoOfPeriods(offsetTime - pivotTime, timeUnit), xloc.bar_time, color = color(na), style = label.style_label_up, textcolor = color.fuchsia, size = size.small) if not na(pivotLo) line.new(pivotTime, pivotLo, offsetTime, pivotLo, xloc.bar_time, color = color.gray, style = line.style_arrow_right, width = 2) label.new(pivotTime, pivotLo, formattedDay(pivotTime, "yyyy.MM.dd G 'at' hh:mm:ss z"), xloc.bar_time, color = color.new(color.gray, 85), style = label.style_label_up, textcolor = color.fuchsia) label.new(time, pivotLo, formattedNoOfPeriods(offsetTime - pivotTime, timeUnit), xloc.bar_time, color = color(na), style = label.style_label_down, textcolor = color.gray, size = size.small) // Condition to check for the difference in ticks from the high and the open. bool cond = math.abs(high - open) > syminfo.mintick * ticksInput // Time the duration the condition has been true. int secFromOpen = secondsSince(cond, resetInput and barstate.isnew) // Condition to check if the duration is greater than the input timer. bool timeAlert = secFromOpen > secondsInput // Format a time string for the timer label. string alertTime = formattedTime(secFromOpen * 1000, "mm:ss") // Set the contents for the label depending on the stage of the alert timer. string alertString = switch timeAlert => "Timed Alert Triggered\n\n" + alertTime cond => "Condition Detected...\n\nTimer count\n" + alertTime => "Waiting for condition..." // Display examples using a table and a label. Update values on the last bar for efficiency. if barstate.islast // Declare a basic label once. var label condTime = label.new(na, na, yloc = yloc.abovebar, style = label.style_label_lower_left, textcolor = color.white) // Update label for changes to location, color, and text. label.set_x(condTime, bar_index) label.set_text(condTime, alertString) label.set_color(condTime, timeAlert ? color.new(color.green, 50) : cond ? color.new(color.orange, 0) : color.new(color.red, 50)) if barstate.islastconfirmedhistory // Declare a basic table once. var table tfDisplay = table.new(tableYposInput + "_" + tableXposInput, 1, 1) // Set table to show tf on last historical bar. table.cell(tfDisplay, 0, 0, secondsToTfString(timeframe.in_seconds(), tfMultInput), bgcolor = color.yellow, text_color = color.black, text_size = textSizeInput) //#endregion
Pivot
https://www.tradingview.com/script/UqdZQJyx-Pivot/
NeoDaNomad
https://www.tradingview.com/u/NeoDaNomad/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © NeoDaNomad //@version=5 library("Pivot", overlay=false) XLR=2 export init(int XLR)=> //init arrays var string[] H=array.new_string(0) var string[] L=array.new_string(0) var string[] A=array.new_string(0) //conditions locate pivot points h=ta.pivothigh(XLR,XLR)==high[XLR]and barstate.isconfirmed l=ta.pivotlow(XLR,XLR)==low[XLR]and barstate.isconfirmed //finds pivots and compresses bar_index, direction variable, and high/low value into a single string to protect data //pivot highs and lows are placed into separate arrays, organized by bar_index for i=0 to 1 bar=bar_index[i]==bar_index if h and bar string str = str.tostring(bar_index[XLR])+"_H_"+str.tostring(high[XLR]) array.unshift(H,str) if l and bar string str = str.tostring(bar_index[XLR])+"_L_"+str.tostring(low[XLR]) array.unshift(L,str) //checks to see which array is shorter before merging them together [long,shrt]=if array.size(H)>array.size(L) [H,L] else [L,H] //merges H and L arrays, maintining the bar_index order //seperate counters initialized for each array index var j=0 var i=0 //counters get incremented individually until all elements from H and L arrays are added to A array. while i<array.size(long) if j<array.size(shrt) //bar_index data briefly exposed for comparison between arrays x1=array.get(str.split(array.get(shrt,j),"_"),0) x2=array.get(str.split(array.get(long,i),"_"),0) if str.tonumber(x1) > str.tonumber(x2) array.push(A,array.get(shrt,j)) j:=j+1 else array.push(A,array.get(long,i)) i:=i+1 else x2=array.get(long,i) array.push(A,x2) i:=i+1 //returns all three arrays [H,L,A] export get(string[] ID,int index) => if barstate.islastconfirmedhistory or barstate.islast x = str.tonumber( array.get( str.split( array.get( ID, index ), "_"), 0) ) d = array.get( str.split( array.get( ID, index ), "_"), 1) y = str.tonumber( array.get( str.split( array.get( ID, index ), "_"), 2) ) [int(x),d,y] //example of deconstructed pivot arrays [H,L,A]=init(XLR) //accessing data in this way is possible but not encouraged [x, d, y ]=get(H,0) [x1,d1,y1]=get(H,0) [x2,d2,y2]=get(H,3) [x3,d3,y3]=get(H,4) label.new( x=barstate.islast?bar_index:na, y=barstate.islast?high:na, text=str.tostring(x), textcolor=color.rgb(0,0,0), size=size.huge, style=label.style_label_down )
PriceTimeInteractive
https://www.tradingview.com/script/cKg4riOO-PriceTimeInteractive/
RozaniGhani-RG
https://www.tradingview.com/u/RozaniGhani-RG/
23
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RozaniGhani-RG //@version=5 // @description TODO: Get price of given time.input library('PriceTimeInteractive', true) // 0. ohlc_time // 1. hlc_time // 2. hl_time // 3. o_time // 4. h_time // 5. l_time // 6. c_time // 7. price_time // Functions // ————————————————————————————————————————————————————————————————————————————— 0. ohlc_time { // @function : Get OHLC price of given time.input // @param : Time (t) must be using time.input // @returns : OHLC export ohlc_time(int t = na)=> var float o = na var float h = na var float l = na var float c = na if time[1] <= t and time >= t and na(c) o := open h := high l := low c := close [o, h, l, c] // } // ————————————————————————————————————————————————————————————————————————————— 1. hlc_time { // @function : Get HLC price of given time.input // @param : Time (t) must be using time.input // @returns : HLC export hlc_time(int t = na)=> var float h = na var float l = na var float c = na if time[1] <= t and time >= t and na(c) h := high l := low c := close [h, l, c] // } // ————————————————————————————————————————————————————————————————————————————— 2. hl_time { // @function : Get HL price of given time.input // @param : Time (t) must be using time.input // @returns : HL export hl_time(int t = na)=> var float h = na var float l = na if time[1] <= t and time >= t and na(l) h := high l := low [h, l] // } // ————————————————————————————————————————————————————————————————————————————— 3. o_time { // @function : Get Open price of given time // @param : Time (t) // @returns : Open export o_time(int t = na)=> var float o = na if time[1] <= t and time >= t and na(o) o := open o // } // ————————————————————————————————————————————————————————————————————————————— 4. h_time { // @function : Get High price of given time // @param : Time (t) // @returns : High export h_time(int t = na)=> var float h = na if time[1] <= t and time >= t and na(h) h := high h // } // ————————————————————————————————————————————————————————————————————————————— 5. l_time { // @function : Get Low price of given time // @param : Time (t) // @returns : Low export l_time(int t = na)=> var float l = na if time[1] <= t and time >= t and na(l) l := low l // } // ————————————————————————————————————————————————————————————————————————————— 6. c_time { // @function : Get Close price of given time // @param : Time (t) // @returns : Close export c_time(int t = na)=> var float c = na if time[1] <= t and time >= t and na(c) c := close c // } // ————————————————————————————————————————————————————————————————————————————— 7. price_time { // @function : Get any OHLC price of given time // @param : Time (t) // @returns : OHLC export price_time(int a = 0, int t = na)=> float expr = switch a 0 => open 1 => high 2 => low 3 => close var float price = na if time[1] <= t and time >= t and na(price) price := expr price // } // Examples // ————————————————————————————————————————————————————————————————————————————— 0. ohlc_time { int point_X = timestamp('2022-03') int time_X = input.time(point_X, 'Point X', confirm = true) [open_X, high_X, low_X, close_X] = ohlc_time(time_X) plot( open_X, 'open_X = ohlc_time(time_X)', trackprice = true) plot( high_X, 'high_X = ohlc_time(time_X)', trackprice = true) plot( low_X, 'low_X = ohlc_time(time_X)', trackprice = true) plot(close_X, 'close_X = ohlc_time(time_X)', trackprice = true) label.new(time_X, open_X, 'Open X', xloc.bar_time, style =label.style_label_right) label.new(time_X, high_X, 'High X', xloc.bar_time, style =label.style_label_lower_right) label.new(time_X, low_X, 'Low X', xloc.bar_time, style =label.style_label_upper_right) label.new(time_X, close_X, 'Close X', xloc.bar_time, style =label.style_label_right) // } // ————————————————————————————————————————————————————————————————————————————— 0. ohlc_time with _ { int point_Y = timestamp('2022-03') int time_Y = input.time(point_Y, 'Point Y', confirm = true) [open_Y, _, _, close_Y] = ohlc_time(time_Y) plot( open_Y, 'open_Y = ohlc_time(time_Y)', color.purple, trackprice = true) plot(close_Y, 'close_Y = ohlc_time(time_Y)', color.purple, trackprice = true) label.new(time_Y, open_Y, 'Open Y', xloc.bar_time, color = color.purple, style =label.style_label_right) label.new(time_Y, close_Y, 'Close Y', xloc.bar_time, color = color.purple, style =label.style_label_right) // } // ————————————————————————————————————————————————————————————————————————————— 1. hlc_time { int point_A = timestamp('2022-04') int time_A = input.time(point_A, 'Point A', confirm = true) [high_A, low_A, close_A] = hlc_time(time_A) plot( high_A, 'high_A = hlc_time(time_A)', color.red, trackprice = true) plot( low_A, 'low_A = hlc_time(time_A)', color.red, trackprice = true) plot(close_A, 'close_A = hlc_time(time_A)', color.red, trackprice = true) label.new(time_A, high_A, 'High A', xloc.bar_time, color = color.red, style =label.style_label_lower_right) label.new(time_A, low_A, 'Low A', xloc.bar_time, color = color.red, style =label.style_label_upper_right) label.new(time_A, close_A, 'Close A', xloc.bar_time, color = color.red, style =label.style_label_right) // } // ————————————————————————————————————————————————————————————————————————————— 2. hl_time { int point_B = timestamp('2022-04') int time_B = input.time(point_B, 'Point B', confirm = true) [high_B, low_B] = hl_time(time_B) plot( high_B, 'high_B = hl_time(time_B)', color.green, trackprice = true) plot( low_B, 'low_B = hl_time(time_B)', color.green, trackprice = true) label.new(time_B, high_B, 'High B', xloc.bar_time, color = color.green, style =label.style_label_lower_right) label.new(time_B, low_B, 'Low B', xloc.bar_time, color = color.green, style =label.style_label_upper_right) // } // ————————————————————————————————————————————————————————————————————————————— 6. c_time { int point_C = timestamp('2022-04') int time_C = input.time(point_C, 'Point C', confirm = true) close_C = c_time(time_C) plot(close_C, 'close_C = c_time(time_C)', color.orange, trackprice = true) label.new(time_C, close_C, 'Close C', xloc.bar_time, color = color.orange, style =label.style_label_right) // } // ————————————————————————————————————————————————————————————————————————————— 7. price_time { int point_O = timestamp('2022-04') int time_O = input.time(point_O, 'Point O', confirm = true) open_O = price_time(0, time_O) plot(open_O, 'open_C = price_time(0, time_O)', color.yellow, trackprice = true) label.new(time_O, open_O, 'Open O', xloc.bar_time, color = color.yellow, style =label.style_label_right) // }
HTV_Library
https://www.tradingview.com/script/ZzobDvCX-HTV-Library/
HyperTV_BRotem
https://www.tradingview.com/u/HyperTV_BRotem/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HyperTV_BRotem //@version=5 library("HTV_LibraryV2") // ┌─── CANDLE STICK ANALYSIS ───┐ { // @function 'up_bar' checks true for every candle that closed above open price. // @returns custom Series Bool export up_bar()=> (open < close) // @function 'last_up_bar' checks true for every last candle that closed above open price. // @returns custom Series Bool export last_up_bar() => open[1] < close[1] // @function 'down_bar' checks true for every candle that closed below open price. // @returns custom Series Bool export down_bar() => open > close // @function 'last_down_bar' checks true for every last candle that closed below open price. // @returns custom Series Bool export last_down_bar() => open[1] > close[1] // @function 'TBR_Up' checks true for every last confirmed 2 Bar Reversal. // @returns custom Series Bool export TBR_Up() => open[1] > close[1] and low > low[1] and ta.crossover(close, high[1]) // @function 'TBR_Down' checks true for every last confirmed 2 Bar Reversal. // @returns custom Series Bool export TBR_Down() => open[1] < close[1] and high < high[1] and ta.crossunder(close, low[1]) // @function 'TCR_Up' checks true for every last confirmed 3 Candle Reversal. // @returns custom Series Bool export TCR_Up() => open[2] > close[2] and close[1] > open[2] and ta.crossover(open, close[1]) // @function 'TCR_Down' checks true for every last confirmed 3 Candle Reversal. // @returns custom Series Bool export TCR_Down() => open[2] < close[2] and close[1] < open[2] and ta.crossunder(open, close[1]) // ●═══───► ∴ ◄───═══● } // ┌─── FIBONACCI SEQUENCE ───┐ { // @function 'f_fib' gives a fibonacci number based on rising numericial order starting from 0 // @returns custom Series Bool export f_fib(int _nth) => _nth == 00 ? 0 : _nth == 01 ? 1 : _nth == 02 ? 1 : _nth == 03 ? 2 : _nth == 04 ? 3 : _nth == 05 ? 5 : _nth == 06 ? 8 : _nth == 07 ? 13 : _nth == 08 ? 21 : _nth == 09 ? 34 : _nth == 10 ? 55 : _nth == 11 ? 89 : _nth == 12 ? 144 : _nth == 13 ? 233 : _nth == 14 ? 377 : _nth == 15 ? 610 : _nth == 16 ? 987 : _nth == 17 ? 1597 : _nth == 18 ? 2584 : _nth == 19 ? 4181 : _nth == 20 ? 6765 : _nth == 21 ? 10946 : _nth == 22 ? 17711 : _nth == 23 ? 28657 : _nth == 24 ? 46368 : _nth == 25 ? 75025 : na // ●═══───► ∴ ◄───═══● } // ┌─── CUSTOM COLOR.RGB ───┐ { // @function uses color.rgb(r,g,b,t) function // @returns literal color export WHITE() => color.rgb(255,255,255,0) export WHITE_25T() => color.rgb(255,255,255,25) export WHITE_50T() => color.rgb(255,255,255,50) export WHITE_90T() => color.rgb(255,255,255,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export BLACK() => color.rgb(0,0,0,0) export BLACK_25T() => color.rgb(0,0,0,25) export BLACK_50T() => color.rgb(0,0,0,50) export BLACK_90T() => color.rgb(0,0,0,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export RED() => color.rgb(255,0,100) export RED_25T() => color.rgb(255,0,100,25) export RED_50T() => color.rgb(255,0,100,50) export RED_90T() => color.rgb(255,0,100,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export GREEN() => color.rgb(0,185,150) export GREEN_25T() => color.rgb(0,185,150,25) export GREEN_50T() => color.rgb(0,185,150,50) export GREEN_90T() => color.rgb(0,185,150,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export BLUE() => color.rgb(40,0,250,0) export BLUE_25T() => color.rgb(40,0,250,25) export BLUE_50T() => color.rgb(40,0,250,50) export BLUE_90T() => color.rgb(40,0,250,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export GREY() => color.rgb(120,123,134,0) export GREY_25T() => color.rgb(120,123,134,25) export GREY_50T() => color.rgb(120,123,134,50) export GREY_90T() => color.rgb(120,123,134,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export NEON_YELLOW() => color.rgb(255,255,0,0) export NEON_YELLOW_25T() => color.rgb(255,255,0,25) export NEON_YELLOW_50T() => color.rgb(255,255,0,50) export NEON_YELLOW_90T() => color.rgb(255,255,0,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export NEON_GREEN() => color.rgb(0,255,100,0) export NEON_GREEN_25T() => color.rgb(0,255,100,25) export NEON_GREEN_50T() => color.rgb(0,255,100,50) export NEON_GREEN_90T() => color.rgb(0,255,100,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export NEON_PINK() => color.rgb(255,0,255,0) export NEON_PINK_25T() => color.rgb(255,0,255,25) export NEON_PINK_50T() => color.rgb(255,0,255,50) export NEON_PINK_90T() => color.rgb(255,0,255,90) // @function uses color.rgb(r,g,b,t) function // @returns literal color export PURPLE() => color.rgb(100,0,255,0) export PURPLE_25T() => color.rgb(100,0,235,50) export PURPLE_50T() => color.rgb(100,0,235,50) export PURPLE_90T() => color.rgb(100,0,235,90) // ●═══───► ∴ ◄───═══● } // ┌─── MA TYPES ───┐ { // @function Simple Moving Average Code // @returns (Local Function) export SMA(float source, int length) => ta.sma(source, length) // @function Exponential Moving Average Code // @returns (Local Function) export EMA(float source, int length) => var _a0 = 2 / (length + 1) _sum = 0.0 _sum := _a0 * source + (1 - _a0) * nz(_sum[1], source) _sum // @function Weighted Moving Average Code // @returns (Local Function) export WMA(float source, int length) => ta.wma(source, length) // @function Volume Weighted Moving Average Code // @returns (Local Function) export VWMA(float source, int length) => ta.vwma(source, length) // @function Relative Moving Average Code // @returns (Local Function) export RMA(float source, int length) => ta.rma(source, length) // @function Hull Moving Average Code // @returns (Local Function) export HMA(float source, int length) => ta.hma(source, length) // @function Simple Triangular Moving Average Code // @returns (Local Function) export STMA(float source, int length) => ta.sma(ta.sma(source, length), length) // @function Exponential Triangular Moving Average Code // @returns (Local Function) export ETMA(float source, int length) => ta.ema(ta.ema(source, length), length) // ●═══───► ∴ ◄───═══● } plot(close)
BE_CustomFx_Library
https://www.tradingview.com/script/YIlFYi9e-BE-CustomFx-Library/
TradeWiseWithEase
https://www.tradingview.com/u/TradeWiseWithEase/
5
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TradeWiseWithEase //@version=5 //New // @description A handful collection of regular functions, Custom Tools & Utility Functions could be used in regular Scripts. hope these functions can be understood by a non programmer like me too. library("BE_CustomFx_Library",overlay=true) //Test1 import PineCoders/Time/3 as pcTimeLib export type Info_ScriptExpiry float IAO_Value string IAO_ValueText string API_Bridge_Format string FyersFormat string FinvasiaFormat string DhanStrikeFormat export type Trade_Info int AllTrades = 0 int LongTrades = 0 int ShortTrades = 0 int AllProfitableTrade = 0 float TotalPNL = 0 int TodayTrades = 0 int TodayProfitableTrade = 0 float TodayPNL = 0 bool IsFirstTradeForTheDay = true int NextTradeAfter = 0 string HedgeCEOTM = "" string HedgePEOTM = "" string T_Symbol = "" int T_Direction = 0 float T_PNL = 0 float T_EnPrice = 0 int T_EnCandle = 0 float T_TGTPrice = 0 float T_SLPrice = 0 float T_ExPrice = 0 int T_ExCandle = 0 int T_Qty = 0 string T_Type = "" string T_QtyString = "" string T_Account_Name = "" string T_En_Date_Time = "" string T_Ex_Date_Time = "" int T_HasEntered = 0 int T_HasExited = 0 int ExitCandleCheck = 0 float Price2MoveForTrailing = 0 float TrailSL_Val = 0 float MaxTradeROI = 0 int SL_Lock_Level = 0 string Gen_EnMsg = "" string Gen_ExMsg = "" string LastLegAlert = "" export type Info_Account_Expiry bool IsExpired string Expirydate int ExpiryDateInt float DaysDiff export type Info_CalculatedSLTP_Level string SL_Text string TP_Text float SL_Value float TP_Value //#region RegularUsuage //#region EntryAlertInfoText // @function to combine couple of basic Entry alert text export EntryAlertInfoText(string TradeTypeOrScriptName, int TradeDirection, float EnPrice , string EntryDateTime, int TQTY, float LTP = close, string OtherInfo = "")=> str.upper(str.format('{0} {1} Trade Entered at:{2, number, #.##}, Delta:{3, number, #.##}, on {4} with Qty:{5, number, integer} {6}', TradeTypeOrScriptName, (TradeDirection == 1 ? "Long" : "Short"), EnPrice, EnPrice - LTP, EntryDateTime, TQTY, OtherInfo)) //#endregion //#region ExitAlertInfoText // @function to combine couple of basic Exit alert text export ExitAlertInfoText(string TradeTypeOrScriptName, int TradeDirection, float ExPrice , string ExitDateTime, float ProfitOrLossValue, int TQTY, float LTP = close, string OtherInfo = "")=> str.upper(str.format('{0} {1} Trade Exited at:{2, number, #.##}, Delta:{3, number, #.##}, on {4} with PNL:{5, number, #.##} | Qty:{6, number, integer} {7}', TradeTypeOrScriptName, (TradeDirection == 1 ? "Long" : "Short"), ExPrice, ExPrice - LTP, ExitDateTime, ProfitOrLossValue, TQTY, OtherInfo)) //#endregion //#region OperatorChk // @function to compare the value against and provide the boolean output // @param flot val2chk = Number to check // @param string OperatorTxt = Set to E for ==, NE for !=, G for >, GE for >=, L for <, LE for <= , BE for <= and >= (Between with Equal) and ather string for >< (Between with greater Lesser) // @param float CompareVal1 = single input to compare against Val2Chk // @param float CompareVal2 = incase of between scenarios thsi will be used // @returns Returns bool Output if compared value found to be true export OperatorChk(float val2chk,string OperatorTxt, float CompareVal1,float CompareVal2 = 0) => bool isAboveWithE = val2chk >= math.min(CompareVal1,CompareVal2) ? true : false bool isBelowWithE = val2chk <= math.max(CompareVal1,CompareVal2) ? true : false bool isAboveWithOutE = val2chk > math.min(CompareVal1,CompareVal2) ? true : false bool isBelowWithOutE = val2chk < math.max(CompareVal1,CompareVal2) ? true : false a = switch OperatorTxt "E" => val2chk == CompareVal1 ? true : false "NE" => val2chk != CompareVal1 ? true : false "NEOR" => val2chk != CompareVal1 or val2chk != CompareVal2 ? true : false "G" => val2chk > CompareVal1 ? true : false "GE" => val2chk >= CompareVal1 ? true : false "L" => val2chk < CompareVal1 ? true : false "LE" => val2chk <= CompareVal1 ? true : false "B" => isAboveWithOutE and isBelowWithOutE ? true : false "BE" => isAboveWithE and isBelowWithE ? true : false "OSE" => (val2chk < math.min(CompareVal1,CompareVal2)) or (val2chk > math.max(CompareVal1,CompareVal2)) ? true : false "OSI" => (val2chk <= math.min(CompareVal1,CompareVal2)) or (val2chk >= math.max(CompareVal1,CompareVal2)) ? true : false => false //#endregion //#region CustomCandleInfoFx // Supporting tuple function to calculate the candle co-ordinates. CustomCandleInfoFx(Repainting, Gaps) => bool Rpnt = barstate.ishistory or barstate.isconfirmed float C_Open = na float C_Close = na float C_High = na float C_Low = na float R_Open = Rpnt ? open[0] : nz(open[1]) float R_Close = Rpnt ? close[0] : nz(close[1]) float R_High = Rpnt ? high[0] : nz(high[1]) float R_Low = Rpnt ? low[0] : nz(low[1]) if barstate.isfirst and Gaps == false C_Open := open C_Close := close C_High := high C_Low := low else if Repainting and Gaps == false C_Open := open C_Close := close C_High := high C_Low := low else if Repainting == false and Gaps == false C_Open := nz(open[1]) C_Close := nz(close[1]) C_High := nz(high[1]) C_Low := nz(low[1]) else if Repainting and Gaps C_Open := open[0] > high[1] or open[0] < low[1] ? close[1] : open[0] C_Close := close C_High := math.max(high,C_Open) C_Low := math.min(low,C_Open) else C_Open := R_Open > R_High[1] or R_Open < R_Low[1] ? R_Close[1] : R_Open C_Close := R_Close C_High := math.max(R_High,C_Open) C_Low := math.min(R_Low,C_Open) [C_Open, C_Close, C_High, C_Low] // [Opn,cls,hgh,lw] = CustomCandleInfoFx(false,true) // plotcandle( // Opn -400, // hgh -400, // lw -400, // cls -400, // "customOHLC", // color = Opn > cls ? color.red : color.green, // wickcolor = color.white, // bordercolor = Opn > cls ? color.red : color.green, // show_last = 120) //#endregion //#region NumAsText // @function Function to return the String Value of Number with decimal precision with the prefix and suffix characters provided // @param float ValueToConvert = Number to Convert // @param int RequiredDecimalPlaces = No of Decimal values Required. supports to a max of 5 decimals else defaults to 2 // @param string BeginingChar = Prefix character which is needed. // @param string EndChar = Suffix character which is needed. // @returns Returns Out put with formated value of Given Number for the specified deicimal values with Prefix and suffix string export NumAsText( float ValueToConvert, int RequiredDecimalPlaces = -1, string ConversionType = format.mintick, string EndChar = "", string BeginingChar = "") => string FormatedVal = switch RequiredDecimalPlaces -1=> str.tostring(ValueToConvert, ConversionType) 0 => str.format("{0,number,integer}", ValueToConvert) 1 => str.format("{0, number,#.#}", ValueToConvert) 3 => str.format("{0,number,#.###}", ValueToConvert) 4 => str.format("{0,number,#.####}", ValueToConvert) 5 => str.format("{0,number,#.####}", ValueToConvert) 2 => str.format("{0,number,#.##}", ValueToConvert) string Output = BeginingChar + FormatedVal + EndChar //#endregion //#region G_Pct_Chng // @function Gets the percentage change between 2 float values over a given lookback period // @param float value1 The first value to reference // @param float value2 The second value to reference // @param int lookback The lookback period to analyze export G_Pct_Chng(float value1, float value2, int lookback) => vChange = value1 - value2 vDiff = vChange - vChange[lookback] (vDiff / vChange) * 100 //#endregion //#region G_Indicator_Val // @function Gets Output of the technical analyis indicator which has length Parameter. RSI, ATR, EMA, SMA, HMA, WMA, VWMA, 'CMO', 'MOM', 'ROC','VWAP', "Highest", "Lowest" // @param string IndicatorName to be specified // @param float SrcVal for the TA indicator default is close // @param simple int Length for the TA indicator // @param int DecimalValue optional to specify if required formatted output with decimal percision else default output comes in tradable value // @returns Value with the given parameters export G_Indicator_Val(string IndicatorName, simple int Length, float SrcVal = close) => ROC_Val = ta.roc(SrcVal, Length) MOM_Val = ta.mom(SrcVal, Length) CMO_Val = ta.cmo(SrcVal, Length) RSI_Val = ta.rsi(SrcVal, Length) ATR_Val = ta.atr(Length) // to Mention Simple Int EMA_Val = ta.ema(SrcVal, Length) SMA_Val = ta.sma(SrcVal, Length) HMA_Val = ta.hma(SrcVal, Length) WMA_Val = ta.wma(SrcVal, Length) VWMA_Val = ta.vwma(SrcVal, Length) Highest_Val = ta.highest(SrcVal == close ? high : SrcVal, Length) Lowest_Val = ta.lowest(SrcVal == close ? low : SrcVal, Length) float IndValue = switch IndicatorName "ROC" => ROC_Val "MOM" => MOM_Val "CMO" => CMO_Val "RSI" => RSI_Val "ATR" => ATR_Val // to Mention Simple Int "EMA" => EMA_Val "SMA" => SMA_Val "HMA" => HMA_Val "WMA" => WMA_Val "VWMA" => VWMA_Val "VWAP" => ta.vwap "Highest" => Highest_Val "Lowest" => Lowest_Val //#endregion //#region G_CandleInfo // @function function to get Candle Informarion such as both wicksize, top wick size , bottom wick size, full candle size and body size in default points // @param string WhatCandleInfo, string input with either of these options "Wick" , "TWick" , "BWick" , "Candle", "Body" , "BearfbVal", "BullfbVal" , "CandleOpen" ,"CandleClose", "CandleHigh" , "CandleLow", "BodyPct","ExtractVal" // @param bool RepaintingVersion, set to true if required data on the realtime bar else default is set to false // @param float FibValueOfCandle, set the fibo value to extract fibvalue of the candle else default is set to 38.2% // @param bool AccountforGaps, set to true if required data on considering the gap between previous and current bar else default is set to false // @param float MidVal, set the % value in order to extract the value for the candle // @returns Returns Respective values for the candles export G_CandleInfo(simple string WhatCandleInfo, simple float FibValueOfCandle = 0.382, bool RepaintingVersion = false, bool AccountforGaps = false, float MidVal = 0.5) => var float fbv = 0.00 var int cndltype = 0 fbv := FibValueOfCandle == 0 ? 0.382 : FibValueOfCandle [Opn, Cls, Hgh, Lw] = CustomCandleInfoFx(RepaintingVersion,AccountforGaps) cndltype := Opn > Cls ? -1 : 1 float Output = switch WhatCandleInfo "Wick" => cndltype == -1 ? (Hgh - Opn) + (Cls - Lw) : (Hgh - Cls) + (Opn - Lw) "TWick" => cndltype == -1 ? (Hgh - Opn) : (Hgh - Cls) "BWick" => cndltype == -1 ? (Cls - Lw) : (Opn - Lw) "Candle" => math.abs(Hgh - Lw) "Body" => math.abs(Opn - Cls) "BearfbVal" => (Hgh - Lw) * fbv "BullfbVal" => (Lw - Hgh) * fbv "CandleOpen" => Opn "ExtractVal" => Lw + ((Hgh - Lw) * MidVal) "CandleLow" => Lw "CandleHigh" => Hgh "CandleClose" => Cls "BodyPct" => math.abs(Opn - Cls) / math.abs(Hgh - Lw) "MCPct" => (math.abs(Opn - Cls) / Cls) * 100 "CandlePct" => (math.abs(Hgh - Lw) / Cls) * 100 //#endregion //#region G_ITM // @function to calculate the ITM stike for the defined strike change // @param string source (default='c') specify either of the source value ['o','h','l','c','s'] Note: Be mindful as it may be repainted and calulation to be called on every bar // @param bool NeedRepainting (default=true) Specify false if you need them to calculate on the completed bars // @param int StrikeDiff (default=100) Specify the strike difference value. eg = Nifty = 50 and BNF = 100 // @param bool ForCE (default=true) Specify false if you need them to calculate for PE option // @param int HowDeep (default=1) Specify the level. // @param float SVal (default=0) Specify the source value. // @param float CalibaratePct (default=0, min = 0 and max = 1) Specify the percentage value. eg if calibarion is set for 50% on the banknifty close price with 30030.5 ITM CE 1 deep will show 29900 how ever if close price is 30070.5 ITM CE with 1 deep will show 30000 export G_ITM(int HowDeep = 1, int StrikeDiff = 100, bool ForCE = true, string source = 'c', float SVal = 0, float CalibaratePct = 0.0, bool NeedRepainting = true, string Delimiter = "|") => CanOpn = G_CandleInfo("CandleOpen",0,NeedRepainting) CanHgh = G_CandleInfo("CandleHigh",0,NeedRepainting) CanLow = G_CandleInfo("CandleLow",0,NeedRepainting) CanCls = G_CandleInfo("CandleClose",0,NeedRepainting) Val = switch str.upper(source) 'O' => CanOpn 'H' => CanHgh 'L' => CanLow 'C' => CanCls => SVal PreOutput = ForCE ? Val - (Val % StrikeDiff) - (StrikeDiff * HowDeep) : Val - (Val % StrikeDiff) + (StrikeDiff * HowDeep) ITMVal = if CalibaratePct == 0.0 PreOutput else if OperatorChk(CalibaratePct, "BE", 0.0 , 1.0) if Val % StrikeDiff >= StrikeDiff * CalibaratePct and ForCE PreOutput + StrikeDiff else if Val % StrikeDiff >= StrikeDiff * CalibaratePct and not ForCE PreOutput + StrikeDiff else PreOutput else PreOutput OutPt = Info_ScriptExpiry.new(ITMVal, NumAsText(ITMVal), str.tostring(ITMVal) + Delimiter + (ForCE ? "CE" : "PE"), str.tostring(ITMVal) + (ForCE ? "CE" : "PE"), (ForCE ? "C" : "P") + str.tostring(ITMVal), NumAsText(ITMVal, 1) + ".0") //#endregion //#region G_OTM // @function to calculate the OTM stike for the defined strike change // @param string source (default='c') specify either of the source value ['o','h','l','c'] Note: Be mindful as it may be repainted and calulation to be called on every bar // @param bool NeedRepainting (default=true) Specify false if you need them to calculate on the completed bars // @param int StrikeDiff (default=100) Specify the strike difference value. eg = Nifty = 50 and BNF = 100 // @param bool ForCE (default=true) Specify false if you need them to calculate for PE option // @param int HowDeep (default=1) Specify the level. // @param float SVal (default=0) Specify the source value. // @param float CalibaratePct (default=0, min = 0 and max = 1) Specify the percentage value. eg if calibarion is set for 50% on the banknifty close price with 30030.5 ITM CE 1 deep will show 29900 how ever if close price is 30070.5 ITM CE with 1 deep will show 30000 // @returns the strike price for the options speficied export G_OTM(int HowDeep = 1, int StrikeDiff = 100, bool ForCE = true, string source = 'c', float SVal = 0, float CalibaratePct = 0.0, bool NeedRepainting = true, string Delimiter = "|") => CanOpn = G_CandleInfo("CandleOpen",0,NeedRepainting) CanHgh = G_CandleInfo("CandleHigh",0,NeedRepainting) CanLow = G_CandleInfo("CandleLow",0,NeedRepainting) CanCls = G_CandleInfo("CandleClose",0,NeedRepainting) Val = switch str.upper(source) 'O' => CanOpn 'H' => CanHgh 'L' => CanLow 'C' => CanCls => SVal PreOutput = ForCE ? Val - (Val % StrikeDiff) + (StrikeDiff * HowDeep) : Val - (Val % StrikeDiff) - (StrikeDiff * HowDeep) OTMVal = if CalibaratePct == 0.0 PreOutput else if OperatorChk(CalibaratePct, "BE", 0.0 , 1.0) if Val % StrikeDiff >= StrikeDiff * CalibaratePct and ForCE PreOutput + StrikeDiff else if Val % StrikeDiff >= StrikeDiff * CalibaratePct and not ForCE PreOutput + StrikeDiff else PreOutput else PreOutput OutPt = Info_ScriptExpiry.new(OTMVal, NumAsText(OTMVal), str.tostring(OTMVal) + Delimiter + (ForCE ? "CE" : "PE"), str.tostring(OTMVal) + (ForCE ? "CE" : "PE"), (ForCE ? "C" : "P") + str.tostring(OTMVal), NumAsText(OTMVal, 1) + ".0") //#endregion //#region G_ATM // @function to calculate the ATM stike for the defined strike change // @param string source (default='c') specify either of the source value ['o','h','l','c'] Note: Be mindful as it may be repainted and calulation to be called on every bar // @param bool NeedRepainting (default=true) Specify false if you need them to calculate on the completed bars // @param int StrikeDiff (default=100) Specify the strike difference value. eg = Nifty = 50 and BNF = 100 // @param float SVal (default=0) Specify the source value. // @param float CalibaratePct (default=0, min = 0 and max = 1) Specify the percentage value. eg if calibarion is set for 50% on the banknifty close price with 30030.5 ITM CE 1 deep will show 29900 how ever if close price is 30070.5 ITM CE with 1 deep will show 30000 // @returns the strike price for the options speficied export G_ATM(int StrikeDiff = 100, bool ForCE = true, string source = 'c', float SVal = 0, float CalibaratePct = 0.0, bool NeedRepainting = true, string Delimiter = "|") => CanOpn = G_CandleInfo("CandleOpen",0,NeedRepainting) CanHgh = G_CandleInfo("CandleHigh",0,NeedRepainting) CanLow = G_CandleInfo("CandleLow",0,NeedRepainting) CanCls = G_CandleInfo("CandleClose",0,NeedRepainting) Val = switch str.upper(source) 'O' => CanOpn 'H' => CanHgh 'L' => CanLow 'C' => CanCls => SVal PreOutput = Val - (Val % StrikeDiff) ATMVal = if CalibaratePct == 0.00 PreOutput else if OperatorChk(CalibaratePct, "BE", 0.0 , 1.0) if Val % StrikeDiff >= StrikeDiff * CalibaratePct and ForCE PreOutput + StrikeDiff else if Val % StrikeDiff >= StrikeDiff * CalibaratePct and not ForCE PreOutput + StrikeDiff else PreOutput else PreOutput OutPt = Info_ScriptExpiry.new(ATMVal, NumAsText(ATMVal), str.tostring(ATMVal) + Delimiter + (ForCE ? "CE" : "PE"), str.tostring(ATMVal) + (ForCE ? "CE" : "PE"), (ForCE ? "C" : "P") + str.tostring(ATMVal), NumAsText(ATMVal, 1) + ".0") //#endregion //#region Chk_TradingTime // @function Determines if the bar's time falls within time filter range // @param string SessionPeriod (default = "GMT+5:30")Opening Market peak time // @returns A boolean - true if the current bar falls within the given time export Chk_TradingTime(string SessionPeriod = '0930-1500') => not(na(time(timeframe.period, SessionPeriod + ':1234567'))) //#endregion //#region DhanHQ_Webhook // @function to retrieve the JSON Format for DhanHQ // @returns to retrieve the JSON Format for DhanHQ export DhanHQ_Webhook(bool Calculation = true, string Dir_, string OrderType_ = "M", string ProductType_ = "", string ScriptName_Expiry, string Qty, string LMTPrice = "0", string Exchange = "NSE", bool IsCall = false, string StrikePrice = "") => string OrderType = str.upper(OrderType_) == "M" ? "MKT" : "LMT" string Dir = str.upper(Dir_) == "BUY" ? "B" : "S" string ProductType = str.upper(ProductType_) == "CNC" or str.upper(ProductType_) == "NRML" ? "M" : "I" string SymbolInfo = str.upper(ScriptName_Expiry) string ExpiryInfo = str.upper(ScriptName_Expiry) string AlertMSg = "" bool ContainsExpiry = str.contains(SymbolInfo, "_") if ContainsExpiry and Calculation ExtractValue = str.split(SymbolInfo,"_") SymbolInfo := ExtractValue.first() ExpiryInfo := ExtractValue.last() AlertMSg := '{"transactionType": "' + Dir +'","orderType": "' + OrderType + '","quantity": "' + Qty + '","exchange": "' + Exchange + '","symbol": "' + SymbolInfo + '","instrument": "OPT","productType": "' + ProductType +'","sort_order": "$","price": "' + LMTPrice +'","option_type": "' + (IsCall ? "CE" : "PE") + '","strike_price": "' + StrikePrice + '","expiry_date": "' + ExpiryInfo + '"}' else if ContainsExpiry and not Calculation ExtractValue = str.split(SymbolInfo,"_") SymbolInfo := ExtractValue.first() ExpiryInfo := ExtractValue.get(1) StrikeInfo = ExtractValue.get(2) CE_Or_PE = ExtractValue.last() AlertMSg := '{"transactionType": "' + Dir +'","orderType": "' + OrderType + '","quantity": "' + Qty + '","exchange": "' + Exchange + '","symbol": "' + SymbolInfo + '","instrument": "OPT","productType": "' + ProductType +'","sort_order": "$","price": "' + LMTPrice +'","option_type": "' + CE_Or_PE + '","strike_price": "' + StrikeInfo + '","expiry_date": "' + ExpiryInfo + '"}' else if not Calculation AlertMSg := '{"transactionType": "' + Dir +'","orderType": "' + OrderType + '","quantity": "' + Qty + '","exchange": "' + Exchange + '","symbol": "' + SymbolInfo + '","instrument": "' + (str.contains(SymbolInfo,"!") ? "FUT" : "EQ") +'","productType": "' + ProductType +'","sort_order": "$","price": "' + LMTPrice +'"}' else AlertMSg := '{Not In Specified Format}' //#endregion //#region ScriptConvertor // @param ExpectedOutput AcceptableValue = "Name", "Type", "Exp" export ScriptConvertor(string ExpectedOutput = "Name", string DefTker = "", string DefType ="")=> Script = DefTker == "" ? syminfo.ticker : DefTker TypeOfScript = if DefType == "" syminfo.type else if DefType == "F" "futures" else if DefType == "E" "stock" else if DefType == "I" "index" else "Others" Output = "" if ExpectedOutput == "Type" Output := switch TypeOfScript "stock" => "E" "futures" => "F" "index" => "I" => "U" else if ExpectedOutput == "Name" PreOutput = switch TypeOfScript "stock" => "E" "futures" => "F" "index" => "I" => "U" if PreOutput == "E" or PreOutput == "I" Output := Script else if PreOutput == "F" and DefTker != "" Output := str.replace(str.replace(Script, "1!", ""),"2", "") else if DefTker == "" Output := Script else Output := "U1" else if ExpectedOutput == "Exp" PreOutput = switch TypeOfScript "stock" => "E" "futures" => "F" "index" => "I" => "U" if PreOutput == "F" CheckExc = str.contains(Script, "1!") or str.contains(Script, "2!") if CheckExc if str.contains(Script, "1!") Output := "C" else if str.contains(Script, "2!") Output := "N" else Output := "C" else Output := "C" else Output := "U2" else Output := "Something" //#endregion //#region AlgoJiIntraMKTAlert // @param string TSym - specify the symbol name for which alert is required defualt is syminfo.tickerid // @param string EnOrEx - specify "EN" for Entry trade or "EX" for Exit trade // @param string LongOrShort - specify "L" for Long and "S" for short // @param int Qty - specify qunatitly for the trade // @param string Instrument - specify instruement type [EQ|FUTIDX|OPTIDX] // @param string Tag - specify Strategy Tag export AlgoJiIntraMKTAlert(string TSym = "", string EnOrEx = "EN", string LongOrShort = "L", int Qty = 1, string Instrument = "OPTIDX", string Tag = "STG1")=> Tker = TSym == "" ? syminfo.ticker(syminfo.tickerid) : TSym Output = "TYPE: " + (LongOrShort == "L" ? "L" : "S") + (EnOrEx == "EN" ? "E" : "X") + " :SYMBOL: " + Tker + " :QTY: " + str.tostring(Qty) + " :PRICE: 0 :OT: MARKET|MIS :INS: " + Instrument + " :STAG: " + Tag //#endregion //#region ChckIndcatorExpiry // @function TODO: to Get Necessary Information with relavnt information for Date & Time Calculation // @param x TODO: Specify the Date String // @returns TODO: Get Necessary Information with relavnt information export ChckIndcatorExpiry(string SupplyInput = "General") => var bool IsHavingA_Valid_L = false var int L_ExpiryDate = 31 var int L_ExpiryMon = 12 var int L_ExpiryYear = 9999 var L_Array = array.from("General|31-01-2023","221812|31-12-2099","HEMA*General|31-01-2023","HEMA*221812|31-12-2099") for [index, value] in L_Array if str.startswith(str.upper(value), str.upper(SupplyInput)) IsHavingA_Valid_L := true ExpiryDateInfo = str.split(str.replace(value, SupplyInput + "|", ""),"-") L_ExpiryDate := int(str.tonumber(array.get(ExpiryDateInfo,0))) L_ExpiryMon := int(str.tonumber(array.get(ExpiryDateInfo,1))) L_ExpiryYear := int(str.tonumber(array.get(ExpiryDateInfo,2))) DateCheck = timestamp(L_ExpiryYear, L_ExpiryMon, L_ExpiryDate, 23, 59, 59) var bool IsValid = if IsHavingA_Valid_L if timenow <= DateCheck true else false else false Output = Info_Account_Expiry.new( IsValid, pcTimeLib.formattedDate(DateCheck, "medium"), DateCheck, math.round(math.abs(DateCheck - timenow) / 86400000, 1)) //#endregion //#region ConvertIndexSLTP2optionsSLTP // @function to calculate Distance between Points of Entry to the points of Either SL or Target In absoulute values // @param Specify the "IAO" Strike type acceptable values are {ITM, OTM, or ATM}, HowDeep (Strike Difference like BNF 100 and Nifty 50) // @returns Returns Calculated points in the string format. export ConvertIndexSLTP2optionsSLTP(string IAO = "ITM", int HowDeep = 0, float MainSL = 0, float MainTGT = 0) => DOW = dayofweek(timenow) Delta = if IAO == "ATM" or HowDeep == 0 DOW > 3 ? 0.2936 : 0.3578 else if IAO == "ITM" switch HowDeep 1 => DOW > 3 and DOW <= 5 ? 0.3578 : 0.4283 2 => DOW > 3 and DOW <= 5 ? 0.4283 : 0.5023 3 => DOW > 3 and DOW <= 5 ? 0.5023 : 0.5775 4 => DOW > 3 and DOW <= 5 ? 0.5775 : 0.651 5 => DOW > 3 and DOW <= 5 ? 0.651 : 0.7195 6 => DOW > 3 and DOW <= 5 ? 0.7195 : 0.7792 7 => DOW > 3 and DOW <= 5 ? 0.7792 : 0.8195 8 => DOW > 3 and DOW <= 5 ? 0.8195 : 0.8478 9 => DOW > 3 and DOW <= 5 ? 0.8478 : 1 => 1 else if IAO == "OTM" switch HowDeep 1 => DOW > 3 and DOW <= 5 ? 0.2369 : 0.3578 2 => DOW > 3 and DOW <= 5 ? 0.1888 : 0.2936 3 => DOW > 3 and DOW <= 5 ? 0.1481 : 0.2369 4 => DOW > 3 and DOW <= 5 ? 0.1163 : 0.1888 5 => DOW > 3 and DOW <= 5 ? 0.0914 : 0.1481 6 => DOW > 3 and DOW <= 5 ? 0.0747 : 0.1163 7 => DOW > 3 and DOW <= 5 ? 0.0606 : 0.0914 8 => DOW > 3 and DOW <= 5 ? 0.0498 : 0.0747 => 0.0426 CalculatedSL = str.tostring(MainSL * Delta, format.mintick) CalculatedTGT = str.tostring(MainTGT * Delta, format.mintick) Output = Info_CalculatedSLTP_Level.new(CalculatedSL, CalculatedTGT, math.round_to_mintick(MainSL * Delta), math.round_to_mintick(MainTGT * Delta)) //#endregion //#region NLB_TradingAlert // @function to Concatenate Leg Strings // @param TradingAccount Specify the string name of Accout you are trading with // @param Dir refers to Diection of the Trade (Buy or Sell), Qty refers to Qty, TradingSymbol refers to Trading Symbol, Exch refers to Exchange (NSE or NFO), Tkn refers to Instrument Token // @param string OrderType - Acceptable strings "M", "L", "SLL", "SLM", "BO", "DBO" // @param float LimitPriceByOrSLBO - whats the price difference form market price can be specified here in this param, can also be used for specifying SL for BO order // @param float TriggerPriceByOrTGTBO - whats the price difference form market price can be specified here in this param, can also be used for specifying TGT for BO order // @returns Returns Alert String which can be used for trigerring Alert export NLB_TradingAlert(string TradingAccount, string Dir = "BUY", string Qty, string T_Exch = "NSE", string TradingSymbol, int Tkn = 0, string ProductType = "INTRADAY", int Delay = 0, string OrderType = "M", string LimitPriceByOrSLBO = "", string TriggerPriceByOrTGTBO = "", string TrailSL = "", int LotSize = 15, float Leverage = 1.0)=> AccountsWithOutSign = array.from('DHANHQ', 'UPSTOXV2', 'ALICEBLUEV2','BINANCE') SameSigns = array.from('MASTERTRUST', 'ZERODHA','SAMCO') AccountName = TradingAccount == "FYERS" ? "FYERSV2" : TradingAccount == "ALICEBLUE" ? "ALICEBLUEV2" : TradingAccount == "IIFL" ? "IIFLV2" : TradingAccount == "UPSTOX" ? "UPSTOXV2" : TradingAccount IsAccWO_Sign = AccountsWithOutSign.includes(AccountName) DelayString = Delay == 0 ? "" : '"DL":"' + str.tostring(Delay) + '",' SameSignAccounts = SameSigns.includes(AccountName) DirectionString = switch AccountName "ANGEL" => OrderType != "BO" ? '{' + DelayString + '"V":"NORMAL","TT":"' + Dir : '{' + DelayString + '"FSL":"' + LimitPriceByOrSLBO + '","FTP":"' + TriggerPriceByOrTGTBO + (TrailSL == "" ? "" : '","FTSL":"' + TrailSL) +'","V":"NORMAL","TT":"' + Dir => OrderType != "BO" ? '{' + DelayString + '"TT":"' + Dir : '","TT":"' + Dir Exch = if AccountName == "FYERSV2" T_Exch == "NSE" or T_Exch == "NFO" ? "NSE" : T_Exch == "BSE" or T_Exch == "BFO" ? "BSE" : T_Exch else T_Exch SymbolIdentity = switch AccountName "FYERSV2" => '","TS":"' + Exch + ':' + TradingSymbol "ANGEL" => Exch == "NSE" ? '","E":"'+ Exch + '","IT":"' + str.tostring(Tkn) + '","TS":"' + TradingSymbol : '","E":"' + Exch + '","TS":"' + TradingSymbol "MASTERTRUST" => Exch == "NSE" ? '","E":"'+ Exch + '","IT":"' + str.tostring(Tkn) : '","E":"' + Exch + '","TS":"' + TradingSymbol "5PAISA" => Exch == "NSE" ? '","E":"'+ Exch + '","IT":"' + str.tostring(Tkn) + '","TS":"' + TradingSymbol + '","ETYPE":"C' : '","E":"' + Exch + '","TS":"' + TradingSymbol + '","ETYPE":"D' => '","E":"' + Exch + '","TS":"' + TradingSymbol QtyIdentity = if not str.contains(Qty,"%") '","Q":"' + Qty else '","Q":"' + Qty + '","FUND":"EQUITY","LEVERAGE":"' + str.tostring(Leverage) + 'X","PER_LOT_SIZE":"' + str.tostring(LotSize) OrderTypeString = switch OrderType "M" => AccountName == "TRADINGVIEW" ? '","PRICE":"0","LIVE":"TRUE' : Exch != "MCX" ? '","OT":"MARKET' : '","OT":"LIMIT","LTP":"' + (IsAccWO_Sign ? "0.05" : Dir != "BUY" ? '+0.05' : '-0.05') "L" => '","OT":"LIMIT","LTP":"' + (IsAccWO_Sign ? "" : Dir != "BUY" ? '+' : '-') + LimitPriceByOrSLBO "SLL" => '","OT":"SLL","LTP":"' + (IsAccWO_Sign ? "" : Dir == "BUY" ? '+' : '-') + LimitPriceByOrSLBO + '","TRP":"' + (IsAccWO_Sign ? "" : SameSignAccounts ? Dir == "BUY" ? '+' : '-' : Dir != "BUY" ? '+' : '-') + TriggerPriceByOrTGTBO "SLM" => '","OT":"SLM","TRP":"' + (IsAccWO_Sign ? "" : Dir == "BUY" ? '+' : '-') + TriggerPriceByOrTGTBO "BO" => '{' + DelayString + '"FSL":"' + LimitPriceByOrSLBO + '","FTP":"' + TriggerPriceByOrTGTBO + (TrailSL == "" ? "" : '","FTSL":"' + TrailSL) "DBO" => '","OT":"LIMIT","LTP":-0","SL":"' + LimitPriceByOrSLBO + '","TP":"' + TriggerPriceByOrTGTBO => '","PRICE":"0","LIVE":"TRUE' EndString = switch AccountName "TRADINGVIEW" => '","AT":"' + AccountName +'"}' => OrderType != "DBO" ? '","P":"' + ProductType + '","VL":"DAY","AT":"' + AccountName +'"}' : '","P":"BO","VL":"DAY","AT":"' + AccountName +'"}' Output = if AccountName == "TRADINGVIEW" DirectionString + SymbolIdentity + OrderTypeString + QtyIdentity + EndString else if OrderType == "BO" (AccountName != "ANGEL" ? OrderTypeString : "") + DirectionString + SymbolIdentity + QtyIdentity + '","OT":"MARKET' + EndString else DirectionString + SymbolIdentity + QtyIdentity + OrderTypeString + EndString OutputCode = str.upper(Output) //#endregion //#region NLB_CancelClose // @function to Contstruct the Alert Syntax for closing and cancelling open positions. // @param TradingAccount Specify the string name of Accout you are trading with // @param SymbolExpiry Specify the string text which can include symbol name and expirt date of symbol // @returns Returns Close & Cancellation Alert String export NLB_CancelClose(string CloseType = "", string TradingAccount = "X", string Exch_ = "NSE", string SymbolNameAndOrExpiry = "X", string CancelType = "", string Product = "", int Delay = 0, bool DhanHQ_As = false)=> AsString = DhanHQ_As ? '"AS":"' : '"CLOSE":"CLOSE","TS":"' DelayString = Delay == 0 ? "" : '"DL":"' + str.tostring(Delay) + '",' AccountName = TradingAccount == "FYERS" ? "FYERSV2" : TradingAccount == "ALICEBLUE" ? "ALICEBLUEV2" : TradingAccount == "IIFL" ? "IIFLV2" : TradingAccount == "UPSTOX" ? "UPSTOXV2" : TradingAccount Exch = if AccountName == "FYERSV2" Exch_ == "NSE" or Exch_ == "NFO" ? "NSE" : Exch_ == "BSE" or Exch_ == "BFO" ? "BSE" : Exch_ else Exch_ SymbolName = TradingAccount == "FYERS" ? Exch + ':' + SymbolNameAndOrExpiry : SymbolNameAndOrExpiry ProductCode = Product == "" ? "" : '","P":"' + Product CancelClode = '{' + DelayString + '"CANCEL":"CANCEL' + ProductCode + '","TS":"' + SymbolName + '","AT":"' + AccountName +'"}' OutputCode = if (CancelType != "" and CloseType == "A" ) and AccountName != "TRADINGVIEW" if AccountName != "FYERSV2" '{' + DelayString + '"CANCEL":"CANCEL' + ProductCode + '","TS":"' + SymbolName + '","AT":"' + AccountName +'"}, {"CLOSE":"CLOSE' + ProductCode + '","AT":"' + AccountName +'"}' else '{' + DelayString + '"CANCEL":"CANCEL' + ProductCode + '","E":"' + Exch + '","TS":"' + SymbolName + '","AT":"' + AccountName +'"}, {"CLOSE":"CLOSE' + ProductCode + '","AT":"' + AccountName +'"}' else if (CancelType != "" and CloseType != "" ) and AccountName == "TRADINGVIEW" '{' + DelayString + '"CANCEL":"CANCEL' + ProductCode + '","TS":"' + SymbolName + '","AT":"' + AccountName +'"}, {"AS":"' + SymbolName + '","E":"' + Exch + '","PRICE":"0","LIVE":"TRUE' + ProductCode + '","AT":"' + AccountName +'"}' else if (CloseType == "" and CancelType != "") CancelClode else if CancelType == "" and CloseType == "A" and AccountName != "TRADINGVIEW" '{' + DelayString + '"CLOSE":"CLOSE' + ProductCode + '","AT":"' + AccountName +'"}' else if CancelType == "" and CloseType == "S" and AccountName != "TRADINGVIEW" Part2CancelCode = switch AccountName "FYERSV2" => '{' + DelayString + '"AS":"' + SymbolName + ProductCode + '","AT":"' + AccountName +'"}' "DHANHQ" => '{' + DelayString + AsString + SymbolName + ProductCode + '","E":"' + Exch + '","AT":"' + AccountName +'"}' => '{' + DelayString + '"AS":"' + SymbolName + ProductCode + '","E":"' + Exch + '","AT":"' + AccountName +'"}' else if CancelType == "S" and CloseType == "S" and AccountName != "TRADINGVIEW" Part2CancelCode = switch AccountName "FYERSV2" => CancelClode + ',' + '{' + DelayString + '"AS":"' + SymbolName + ProductCode + '","AT":"' + AccountName +'"}' "DHANHQ" => CancelClode + ',' + '{' + DelayString + AsString + SymbolName + ProductCode + '","E":"' + Exch + '","AT":"' + AccountName +'"}' => CancelClode + ',' + '{' + DelayString + '"AS":"' + SymbolName + ProductCode + '","E":"' + Exch + '","AT":"' + AccountName +'"}' else if CancelType == "" and CloseType != "" and AccountName == "TRADINGVIEW" '{' + DelayString + '"E":"' + Exch + '","AS":"' + SymbolName + '","PRICE":"0","LIVE":"TRUE","CLOSE":"CLOSE' + ProductCode + '","AT":"TRADINGVIEW"}' //#endregion //#region ArrayCombiner // @function to suffix ", " to the list of string of Array values supplied. export ArrayCombiner(string[] LegsToCombine, string BotType = "", string DhanHQ_Secret = "")=> OP_Array = array.new_string(0) for [index, value] in LegsToCombine if str.length(value) > 2 and not OP_Array.includes(value) OP_Array.push(value) Ouput = if str.startswith(str.upper(BotType), "ALGOJI") or BotType == "" array.join(OP_Array,"\n") else if str.startswith(str.upper(BotType), "N-") or str.startswith(str.upper(BotType), "B-") or str.upper(BotType) == "NLB" or str.upper(BotType) == "BONLB" "[" + array.join(OP_Array,", ") + "]" else if str.startswith(str.upper(BotType), "DHANHQ") or str.startswith(str.upper(BotType), "DHAN") BuyLegs = array.new_string(0) SellLegs = array.new_string(0) for [index, value] in OP_Array if str.contains(value, '"transactionType": "B"') BuyLegs.push(value) else SellLegs.push(value) CombinedLegs = BuyLegs.concat(SellLegs) UpdateSortOrder = array.new_string(0) for [stdIdx, ech] in CombinedLegs UpdateSortOrder.push(str.replace(ech, "$", str.tostring(stdIdx), 0)) '{"secret": "' + DhanHQ_Secret + '","alertType": "multi_leg_order","order_legs": [\n' + array.join(UpdateSortOrder,",\n") + "\n]}" //#endregion //#region NLB_Cal_TradingAlert // @function to create String concatination which can be used for trigerring Alerts. // @param Calculate - true for calculation options strike string // @param IAO - for ITM or OTM or ATM strike Price // @param F_CE - true for for CALL and false for PUT // @param int SDiff (default=100) Specify the strike difference value. eg = Nifty = 50 and BNF = 100 // @param float SVal (default=0) Specify the source value. // @param float C_Pct (default=0, min = 0 and max = 1) Specify the percentage value. eg if calibarion is set for 50% on the banknifty close price with 30030.5 ITM CE 1 deep will show 29900 how ever if close price is 30070.5 ITM CE with 1 deep will show 30000 // @param BotType specify the BOT type, ALGOJI or NEXTLEVEL_BOT // @param C_Symbol specify the Basic Trading Symbol or WithExpiry_Symbol for FUTURES or OPTIONS // @param Exc specify the exchange symbol reference // @param MOrder - if set to true then creates string for Market order for Limit Order String set the param to false // @param MPricePlus - for limit orders setting this param to true will help for creating a string with sell high trade types // @param LMTPriceBy - whats the price difference form market price can be specified here in this param // @returns Returns Intraday Alert String which can be used for trigerring Alert export NLB_Cal_TradingAlert( string BotType = "NLB", bool Calculate = true, string IAO = "ITM", int Deep = 1, int SDiff = 100, bool F_CE = true, string src = 'c', float S_Val = 0, float C_Pct = 0.0, string TAccount = "X", string Exc = "NSE", string C_Symbol = "X", int tkn = 0, string C_Dir, string C_Qty, string MOrder = "M", string LMTPriceBy = "0", string TrgPriceBy = "0", string Product = 'INTRADAY', int Delay = 0, string TrailSL ="", int LotSize = 15, float Leverage = 1.0, string Tg = "STG1", string Instr = "OPTIDX", string EnOEx = "EN", bool CalculateSL_TGT = false)=> string SL_For_BO = "" string TGT_For_BO = "" if not CalculateSL_TGT SL_For_BO := LMTPriceBy TGT_For_BO := TrgPriceBy else GetInputs = ConvertIndexSLTP2optionsSLTP(IAO, Deep, str.tonumber(LMTPriceBy), str.tonumber(TrgPriceBy)) SL_For_BO := GetInputs.SL_Text TGT_For_BO := GetInputs.TP_Text string Algo = "" string Fyers = "" string Finvasia = "" string TradingView = "" string TradingSymbol = "" float IOM_value = 0 string UBotType = str.upper(BotType) if Calculate GetInputsForIAO = switch IAO "ATM" => G_ATM(SDiff, F_CE, src, S_Val, C_Pct) "ITM" => G_ITM(Deep, SDiff, F_CE, src, S_Val, C_Pct) "OTM" => G_OTM(Deep, SDiff, F_CE, src, S_Val, C_Pct) IOM_value := GetInputsForIAO.IAO_Value Algo := GetInputsForIAO.API_Bridge_Format Fyers := GetInputsForIAO.FyersFormat Finvasia := GetInputsForIAO.FinvasiaFormat TradingView := str.replace(Algo,"|","",0) TradingSymbol := if UBotType == "ALGOJI_D" str.upper(C_Symbol) + str.replace(Algo,"|","",0) + "|" + Algo else if UBotType == "ALGOJI" str.upper(C_Symbol) + "|" + Algo else if UBotType == "DHANHQ" str.upper(C_Symbol) + "_" + GetInputsForIAO.DhanStrikeFormat + "_" + (F_CE ? "CE" : "PE") else if str.contains(str.upper(TAccount),"FYERS") str.upper(C_Symbol) + Fyers else if str.contains(str.upper(TAccount),"FINVASIA") str.upper(C_Symbol) + Finvasia else str.upper(C_Symbol) + TradingView else TradingSymbol := str.upper(C_Symbol) Output = if str.startswith(UBotType,"ALGOJI") AlgoJiIntraMKTAlert(TradingSymbol, EnOEx, C_Dir, int(str.tonumber(C_Qty)), (Calculate ? "OPTIDX" : Instr), Tg) else if UBotType == "NLB" or str.startswith(UBotType, "N-") or str.startswith(UBotType, "B-") or UBotType == "BONLB" NLB_TradingAlert(TAccount, C_Dir, C_Qty, Exc, TradingSymbol, tkn, Product, Delay, MOrder, SL_For_BO, TGT_For_BO, TrailSL, LotSize, Leverage) else if UBotType == "DHANHQ" or str.startswith(UBotType, "DHAN") DhanHQ_Webhook(Calculate, C_Dir, MOrder, Product, str.upper(C_Symbol), C_Qty, SL_For_BO, Exc, F_CE, NumAsText(IOM_value, 1) + ".0") [IOM_value, TradingSymbol, Output] //#endregion //#endregion //===================================================================================================== //#region OccationalUsuage //#region GetTicker // @function to extract Symbol Name // @param _str SymbolName with Exchange prefix // @param _of Separator default is ":" export GetTicker(string _str, string _of = ":") => // string _str: string to separate. // string _op : separator character. string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _ofPos = array.indexof(_chars, _of) string[] _substr = array.new_string(0) if _ofPos >= 0 and _ofPos < _len - 1 _substr := array.slice(_chars, _ofPos + 1, _len) string _return = array.join(_substr, "") //#endregion //#region GetTickerPrfx // @function to extract Symbol Prefix // @param _str SymbolName with Exchange prefix // @param _of Separator default is ":" export GetTickerPrfx(string _str, string _of = ":") => // string _str: string to separate. // string _op : separator character. string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _ofPos = array.indexof(_chars, _of) string[] _substr = array.new_string(0) if _ofPos >= 0 and _ofPos < _len - 1 _substr := array.slice(_chars, 0, _ofPos) string _return = array.join(_substr, "") //#endregion //#region TxtSize var SampleInputForText = input.string("Normal","Text Size to Select",["Auto", "Tiny", "Small", "Normal", "Large", "Huge"]) // @function Function to Get size Value for text values used in Lables // @param string SizeValue = auto, tiny, small, normal, large, huge. specify either of these values or default value Normal will be displayed as output // @returns Returns Respective Text size export TxtSize(simple string SizeValue = "Normal") => string Output = switch SizeValue "Auto" => size.auto "Tiny" => size.tiny "Small" => size.small "Large" => size.large "Huge" => size.huge => size.normal //#endregion //#region LnStyle var SampleInputForLineStyle = input.string(title='Line Style', options=['solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)'], defval='dotted (┈)') // @function Function to Get Line Style Value for text values used in Lines // @param string LineType = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output // @returns Returns Respective Line style export LnStyle(simple string LineType = "dotted (┈)") => string Output = switch LineType "solid (─)" => line.style_solid "dashed (╌)" => line.style_dashed "arrow left (←)" => line.style_arrow_left "arrow right (→)" => line.style_arrow_right "arrows both (↔)" => line.style_arrow_both => line.style_dotted //#endregion //#region ShapeType //shape.triangleup, shape.triangledown, shape.flag, shape.circle, shape.arrowup, shape.arrowdown, shape.labelup, shape.labeldown, // @function Function to Get Shape Style Value for text values used in plot shapes // @param string ShapeType = 'XCross', 'Cross', 'Triangle Up', 'Triangle Down', 'Flag', 'Circle','Arrow Up', 'Arrow Down','Lable Up', 'Lable Down' or default shpae style Triangle Up will be the output // @returns Returns Respective Shape style export ShapeType(simple string ShapeType = 'Triangle Up') => string Output = switch ShapeType 'Triangle Down' => shape.triangledown 'Arrow Up' => shape.arrowup 'Arrow Down' => shape.arrowdown 'Lable Up' => shape.labelup 'Lable Down' => shape.labeldown 'Flag' => shape.flag 'Circle' => shape.circle 'Square' => shape.square 'Dimond' => shape.diamond => shape.triangleup //#endregion //#region G_TablePositon var SampleInputForTablePosition = input.string( title = "Table Position", defval = "LeftCenter", options = ["TopLeft", "BottomLeft", "LeftCenter", "RightCenter", "TopRight", "BottomRight","TopCenter","BottomCenter"]) export G_TablePositon(simple string TablePosition) => switch TablePosition "TopLeft" => position.top_left "BottomLeft" => position.bottom_left "LeftCenter" => position.middle_left "RightCenter" => position.middle_right "TopRight" => position.top_right "TopCenter" => position.top_center "BottomCenter" => position.bottom_center => position.bottom_right //#endregion //#region IsPoweredPushBuy // @function To Check if the candle is a powered Push or Not export IsPoweredPushBuy(int LookBackBars, bool RepaintingVersion = true) => MCPct = G_CandleInfo("MCPct",0,RepaintingVersion) HasMoreBodyH = ta.sma(MCPct, LookBackBars) * 2.5 candlesize = G_CandleInfo("Candle",0,RepaintingVersion) wicksize = G_CandleInfo("Wick",0,RepaintingVersion) [Opn, Cls, Hgh, Lw] = CustomCandleInfoFx(RepaintingVersion,false) bool Output = false if Opn < Cls and MCPct > HasMoreBodyH and ((Opn==Lw and Cls==Hgh) or ((Cls >= (Hgh - (candlesize * 0.05))) and (wicksize < math.abs(Opn - Cls))) or (Cls==Hgh and (wicksize < math.abs(Opn - Cls)))) Output := true //#endregion //#region IsPoweredPushSell // @function To Check if the candle is a powered Push or Not export IsPoweredPushSell(int LookBackBars, bool RepaintingVersion = true) => MCPct = G_CandleInfo("MCPct",0,RepaintingVersion) HasMoreBodyH = ta.sma(MCPct, LookBackBars) * 2.5 candlesize = G_CandleInfo("Candle",0,RepaintingVersion) wicksize = G_CandleInfo("Wick",0,RepaintingVersion) [Opn, Cls, Hgh, Lw] = CustomCandleInfoFx(RepaintingVersion,false) bool Output = false if Opn > Cls and MCPct > HasMoreBodyH and ((Opn==Lw and Cls==Hgh) or ((Cls <= (Lw + (candlesize * 0.05))) and (wicksize < math.abs(Opn - Cls))) or (Cls==Lw and (wicksize < math.abs(Opn - Cls)))) Output := true //#endregion //#region G_Delta // @function Gets Delta Output of the technical analyis indicator // @param int ShortLength to be specified default is 3 // @param int LongLength to be specified default is 8 // @param simple string MAType for the TA indicator supported are EMA, SMA, HMA // @param bool RepaintingVersion calculate on realtime bar? default is true. // @returns Value with the given parameters export G_Delta(simple int ShortLength = 3,simple int LongLength = 8,simple string MAType = "EMA", bool RepaintingVersion = true)=> if MAType == "EMA" or MAType == "SMA" or MAType == "HMA" SlowEMA = G_Indicator_Val(MAType,LongLength, G_CandleInfo("CandleClose",0,RepaintingVersion)) FastEMA = G_Indicator_Val(MAType,ShortLength, G_CandleInfo("CandleClose",0,RepaintingVersion)) StTermDelta = ((FastEMA - SlowEMA) / hlc3 ) * 100 //#endregion //#region G_BullBearBarCount // @function Counts how many green & red bars have printed recently (ie. pullback count) // @param int HowManyCandlesToCheck The lookback period to look back over // @param int BullBear The color of the bar to count (1 = Bull, -1 = Bear), Open = close candles are ignored // @param float AboveOrBelow if in case you would need to count only green candles wich are close above 50% of previous candle then use 0.5 // @returns The bar count of how many candles have retraced over the given lookback with specific candles export G_BullBearBarCount(int HowManyCandlesToCheck, int BullBear = 1, float AboveOrBelow = 0) => CandlesCounter = 0 TestTheValue = G_CandleInfo("ExtractVal",0,false,false,AboveOrBelow) for i = 1 to HowManyCandlesToCheck by 1 if BullBear == 1 and close[i] > open[i] and close[i] >= TestTheValue // Count green bars CandlesCounter := CandlesCounter + 1 if BullBear == -1 and close[i] < open[i] and close[i] <= TestTheValue // Count red bars CandlesCounter := CandlesCounter + 1 CandlesCounter //#endregion //#region BarToStartYourCalculation // @function function to get candle co-ordinate in order to use it further for calculating your analysis work . "Heart full Thanks to 3 Pine motivators (LonesomeTheBlue, Myank & Sriki) who helped me cracking this logic" // @param Int SelectedCandleNumber (default=450) How many candles you would need to anlysie in your script from the right. // @returns A boolean - output is returned to say the starting point and continue to diplay true for the future candles export BarToStartYourCalculation(int SelectedCandleNumber = 450) => UTC = 0. // get UTC time int timenow_ = timenow + math.round(UTC * 3600000) int time_ = time + math.round(UTC * 3600000) // calculate D/H/M/S for the bar which we are on and time now int daynow_ = math.floor((timenow_ + 86400000 * 3) / 86400000) % 7 int day_ = math.floor((time_ + 86400000 * 3) / 86400000) % 7 int hournow_ = math.floor(timenow_ / 3600000) % 24 int hour_ = math.floor(time_ / 3600000) % 24 int minutenow_ = math.floor(timenow_ / 60000) % 60 int minute_ = math.floor(time_ / 60000) % 60 int secondnow_ = math.floor(timenow_ / 60000) % 60 int second_ = math.floor(time_ / 60000) % 60 int hmstime_ = hour_ * 3600000 + minute_ * 60000 + second_ * 1000 int hmstimenow_ = hournow_ * 3600000 + minutenow_ * 60000 + secondnow_ * 1000 var int starttime = na if bar_index > SelectedCandleNumber and (na(starttime) or time_ < nz(starttime)) if timeframe.isdaily if day_ == daynow_ // session day diff = time_ - time_[SelectedCandleNumber] starttime := timenow_ - diff if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend diff = time_[1] - time_[SelectedCandleNumber + 1] + (daynow_ - day_[1]) * 86400000 starttime := timenow_ - diff if timeframe.isintraday if day_ == daynow_ and day_[1] == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] <= hmstimenow_ // in session diff = time_[1] - time_[SelectedCandleNumber + 1] + math.round(UTC * 3600000) starttime := timenow_ - diff if day_ != daynow_ and day_[1] == daynow_ and hmstime_ < hmstimenow_ and hmstime_[1] <= hmstimenow_ // in same day and after session diff = time_[1] - time_[SelectedCandleNumber + 1] + hmstimenow_ - hmstime_[1] + math.round(UTC * 3600000) starttime := timenow_ - diff if day_ == daynow_ and day_[1] + 1 == daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // in week (not first day) and before session diff = time_[1] - time_[SelectedCandleNumber + 1] + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff if day_ == daynow_ and day_[1] > daynow_ and hmstime_ > hmstimenow_ and hmstime_[1] >= hmstimenow_ // the day after weekend before session diff = time_[1] - time_[SelectedCandleNumber + 1] + 2 * 86400000 + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff if daynow_ > day_ and daynow_ > day_[1] and day_[1] > day_ // weekend diff = time_[1] - time_[SelectedCandleNumber + 1] + (daynow_ - day_[1] - 1) * 86400000 + 24 * 3600000 - hmstime_[1] + hmstimenow_ + math.round(UTC * 3600000) starttime := timenow_ - diff if timeframe.isweekly starttime := timenow_ - timeframe.multiplier * SelectedCandleNumber * 604800000 // 1 week = 604800000ms if timeframe.ismonthly starttime := timenow_ - timeframe.multiplier * SelectedCandleNumber * 2629743000 // 1 month = 2629743000ms GetBoolOutput = not na(starttime) and time >= starttime //#endregion //#region isHammer // @function Checks if the previous bar is a hammer candle based on the given parameters // @param float fib (default=0.382) The fib to base candle body on // @param bool colorMatch (default=false) Does the candle need to be green? (true/false) // @param bool NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars // @returns A boolean - true if the previous bar matches the requirements of a hammer candle export isHammer(float fib = 0.382, bool colorMatch = false, bool NeedRepainting = false) => o = G_CandleInfo("CandleOpen",0,NeedRepainting) h = G_CandleInfo("CandleHigh",0,NeedRepainting) l = G_CandleInfo("CandleLow",0,NeedRepainting) c = G_CandleInfo("CandleClose",0,NeedRepainting) bullFib = (l - h) * fib + h lowestBody = c < o ? c : o lowestBody >= bullFib and (not colorMatch or c > o) //#endregion //#region isStar // @function Checks if the previous bar is a shooting star candle based on the given parameters // @param float fib (default=0.382) The fib to base candle body on // @param bool colorMatch (default=false) Does the candle need to be red? (true/false) // @param bool NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars // @returns A boolean - true if the previous bar matches the requirements of a shooting star candle export isStar(float fib = 0.382, bool colorMatch = false, bool NeedRepainting = false) => o = G_CandleInfo("CandleOpen",0,NeedRepainting) h = G_CandleInfo("CandleHigh",0,NeedRepainting) l = G_CandleInfo("CandleLow",0,NeedRepainting) c = G_CandleInfo("CandleClose",0,NeedRepainting) bearFib = (h - l) * fib + l highestBody = c > o ? c : o highestBody <= bearFib and (not colorMatch or c < o) //#endregion //#region isDoji // @function Checks if the previous bar is a doji candle based on the given parameters // @param float wickSize (default=1.5 times) The maximum allowed times can be top wick size compared to the bottom (and vice versa) // @param float bodySize (default= 5 percent to be mentioned as 0.05) The maximum body size as a percentage compared to the entire candle size // @param bool NeedRepainting (default=false) Specify true if you need them to calculate on the realtime bars // @returns A boolean - true if the previous bar matches the requirements of a doji candle export isDoji(float wickSize = 1.5, float bodySize = 0.05, bool NeedRepainting = false) => G_CandleInfo("TWick",0,NeedRepainting) <= G_CandleInfo("BWick",0,NeedRepainting) * wickSize and G_CandleInfo("BWick",0,NeedRepainting) <= G_CandleInfo("TWick",0,NeedRepainting) * wickSize and G_CandleInfo("BodyPct",0,NeedRepainting) <= bodySize //#endregion //#region isBullishEC // @function Checks if the previous bar is a bullish engulfing candle // @param float allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps) // @param float rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage // @param bool engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well? // @param bool NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars // @returns A boolean - true if the previous bar matches the requirements of a bullish engulfing candle export isBullishEC(float allowance = 0.0, float rejectionWickSize = 0.0, bool engulfWick = false, bool NeedRepainting = false) => o = G_CandleInfo("CandleOpen",0,NeedRepainting) h = G_CandleInfo("CandleHigh",0,NeedRepainting) l = G_CandleInfo("CandleLow",0,NeedRepainting) c = G_CandleInfo("CandleClose",0,NeedRepainting) (c[1] <= o[1] and c >= o[1] and o <= c[1] + allowance) and (not engulfWick or c >= h[1]) and (rejectionWickSize == 0.0 or G_CandleInfo("TWick",0,NeedRepainting) / G_CandleInfo("Body",0,NeedRepainting) < rejectionWickSize) //#endregion //#region isBearishEC // @function Checks if the previous bar is a bearish engulfing candle // @param float allowance (default=0) How many POINTS to allow the open to be off by (useful for markets with micro gaps) // @param float rejectionWickSize (default=disabled) The maximum rejection wick size compared to the body as a percentage // @param bool engulfWick (default=false) Does the engulfing candle require the wick to be engulfed as well? // @param bool NeedRepainting (default=false) Specify True if you need them to calculate on the realtime bars // @returns A boolean - true if the previous bar matches the requirements of a bearish engulfing candle export isBearishEC(float allowance = 0.0, float rejectionWickSize = 0.0, bool engulfWick = false, bool NeedRepainting = false) => o = G_CandleInfo("CandleOpen",0,NeedRepainting) h = G_CandleInfo("CandleHigh",0,NeedRepainting) l = G_CandleInfo("CandleLow",0,NeedRepainting) c = G_CandleInfo("CandleClose",0,NeedRepainting) (c[1] >= o[1] and c <= o[1] and o >= c[1] - allowance) and (not engulfWick or c <= l[1]) and (rejectionWickSize == 0.0 or G_CandleInfo("BWick",0,NeedRepainting) / G_CandleInfo("Body",0,NeedRepainting) < rejectionWickSize) //#endregion //#region Plot_TrendLineAtDegree // @function helps you to plot the Trendlines based on the specified angle at the defined price to bar ratio // @param float Degree (default=14) angle at which Trendline to be plot // @param float price2bar_ratio (default=1e-10) The maximum rejection wick size compared to the body as a percentage // @param int Bars2Plot (default=6) Does the engulfing candle require the wick to be engulfed as well? // @param string LineStyle = 'solid (─)', 'dotted (┈)', 'dashed (╌)', 'arrow left (←)', 'arrow right (→)', 'arrows both (↔)' or default line style 'dotted (┈)' will be the output // @param bool PlotOnOpen_Close (default=false) Specify True if you need them to calculate on the Open\Close Values // @returns plot the Trendlines based on the specified angle at the defined price to bar ratio export Plot_TrendLineAtDegree(float Degree = 14.0, float price2bar_ratio = 1e-10, int Bars2Plot = 6,simple string LineStyle = "dotted (┈)", bool PlotOnOpen_Close = false) => float valMulti = 1.739e-12 float TimeMulti = 1e-10 float TimeDivider = price2bar_ratio / TimeMulti float Val_Multi = TimeDivider * (Degree * valMulti) wheretoPlot_Top = PlotOnOpen_Close ? math.max(open, close) : high wheretoPlot_Bottom = PlotOnOpen_Close ? math.min(open, close) : low var HighLines = array.new_line(Bars2Plot) var LowLines = array.new_line(Bars2Plot) for ab = 0 to (Bars2Plot - 1) by 1 line.delete(array.get(HighLines, ab)) line.delete(array.get(LowLines, ab)) float HVal2Plot = wheretoPlot_Top[ab] + Val_Multi float LVal2Plot = wheretoPlot_Bottom[ab] - Val_Multi array.set(HighLines, ab, line.new(x1 = bar_index[ab], y1 = wheretoPlot_Top[ab], x2 = bar_index[ab] + 1, y2 = HVal2Plot, color = color.green, extend= extend.right, style = LnStyle(LineStyle))) array.set(LowLines, ab, line.new(x1 = bar_index[ab], y1 = wheretoPlot_Bottom[ab], x2 = bar_index[ab] + 1, y2 = LVal2Plot, color = color.lime, extend= extend.right, style = LnStyle(LineStyle))) //#endregion //#region G_HighFreqValue // @function to retrieve the highest frequency value for the given lookback period // @param int LookBackPeriod - default is 50 // @param float FilterVal1 - default is 0 (include All) // @param float FilterVal2 - default is 0 (will be used only in between scenario) // @param string FilterValOperator - Set to E for ==, NE for !=, G for >, GE for >=, L for <, LE for <= , BE for <= and >= (Between with Equal) and ather string for >< (Between with greater Lesser) // @param minTouch = Minimum Touches to be tested (default is 3) // @param ErrorRateTicks = if in case of exact touch is not happened how much error rate can be included (default is 10 minticks) // @param bool IncludeOpen - default is true // @param bool IncludeHigh - default is true // @param bool IncludeLow - default is true // @param bool IncludeClose - default is true // @returns tuples with MaxTouchValue and HighestRange and LowestRange export G_HighFreqValue(int LookBackPeriod = 50,float FilterVal1 = 0,float FilterVal2 = 0 ,string FilterValOperator = "G",int minTouch = 3, int ErrorRateTicks = 10, bool IncludeOpen = true, bool IncludeHigh = true, bool IncludeLow = true, bool IncludeClose = true) => bool NeedMaxTouch = true FilteredListOfArray = array.new_float(0) int LoadedValues = 0 loadAllValues = false HighestH = ta.highest(LookBackPeriod) LowestL = ta.lowest(LookBackPeriod) if (FilterValOperator == "G" or FilterValOperator == "GE") and (FilterVal1 == 0 or FilterVal1 <= LowestL) loadAllValues := true if (FilterValOperator == "L" or FilterValOperator == "LE") and FilterVal1 >= HighestH loadAllValues := true for filval = 0 to LookBackPeriod by 1 if not loadAllValues if IncludeOpen and OperatorChk(open[filval+ 1],FilterValOperator,FilterVal1, FilterVal2) array.push(FilteredListOfArray,open[filval+ 1]) LoadedValues+=1 if IncludeHigh and OperatorChk(high[filval + 1],FilterValOperator,FilterVal1, FilterVal2) array.push(FilteredListOfArray,high[filval + 1]) LoadedValues+=1 if IncludeLow and OperatorChk(low[filval + 1],FilterValOperator,FilterVal1, FilterVal2) array.push(FilteredListOfArray,low[filval + 1]) LoadedValues+=1 if IncludeClose and OperatorChk(close[filval + 1],FilterValOperator,FilterVal1, FilterVal2) array.push(FilteredListOfArray,close[filval + 1]) LoadedValues+=1 else array.push(FilteredListOfArray,open[filval+ 1]) array.push(FilteredListOfArray,high[filval + 1]) array.push(FilteredListOfArray,low[filval + 1]) array.push(FilteredListOfArray,close[filval + 1]) LoadedValues+=4 UniqueListOfFilter = array.new_float(0) int intialLoop = 0 int ValuesLoaded = 0 HowManyUniqueFound = for ohlc_val in FilteredListOfArray if intialLoop == 0 array.push(UniqueListOfFilter,ohlc_val) ValuesLoaded+=1 else if not array.includes(UniqueListOfFilter,ohlc_val) array.push(UniqueListOfFilter,ohlc_val) ValuesLoaded+=1 intialLoop+=1 ValuesLoaded int MaxRepeatFound = NeedMaxTouch ? minTouch < 3 ? 3 : minTouch : minTouch float LimitTicks = ErrorRateTicks * syminfo.mintick float LimitTicks_ = (ErrorRateTicks * 10) * syminfo.mintick TimesRepeatedArray = array.new_float(0) ListOfOutputValue = array.new_float(0) UpSideTimesRepeatedArray = array.new_float(0) UpSideListOfOutputValue = array.new_float(0) DnSideTimesRepeatedArray = array.new_float(0) DnSideListOfOutputValue = array.new_float(0) for UnqVal in UniqueListOfFilter int TimesRepeated = 0 CalculateRepeats = for ohlc_val in FilteredListOfArray if (ohlc_val >= (UnqVal - LimitTicks) and ohlc_val <= (UnqVal + LimitTicks)) TimesRepeated += 1 TimesRepeated if CalculateRepeats > MaxRepeatFound array.push(ListOfOutputValue,UnqVal) array.push(TimesRepeatedArray,CalculateRepeats) else if CalculateRepeats <= MaxRepeatFound if OperatorChk(UnqVal,"GE",HighestH - LimitTicks_, 0) array.push(UpSideListOfOutputValue,UnqVal) array.push(UpSideTimesRepeatedArray,CalculateRepeats) if OperatorChk(UnqVal,"BE",LowestL, LowestL + LimitTicks_) array.push(DnSideListOfOutputValue,UnqVal) array.push(DnSideTimesRepeatedArray,CalculateRepeats) MaxOfRepeats = array.size(TimesRepeatedArray) > 0 ? array.max(TimesRepeatedArray) : 0 IndexOfMaxRepeat = MaxOfRepeats != 0 ? array.indexof(TimesRepeatedArray,MaxOfRepeats) : -1 ValueTestedMaxNoOfTimes = IndexOfMaxRepeat != -1 ? array.get(ListOfOutputValue,IndexOfMaxRepeat) : 0 H1_MaxOfRepeats = array.size(UpSideTimesRepeatedArray) > 0 ? array.max(UpSideTimesRepeatedArray) : 0 H1_IndexOfMaxRepeat = H1_MaxOfRepeats != 0 ? array.indexof(UpSideTimesRepeatedArray,H1_MaxOfRepeats) : -1 H1_ValueRepeatedMax = H1_IndexOfMaxRepeat != -1 ? array.get(UpSideListOfOutputValue,H1_IndexOfMaxRepeat) : 0 L1_MaxOfRepeats = array.size(DnSideTimesRepeatedArray) > 0 ? array.max(DnSideTimesRepeatedArray) : 0 L1_IndexOfMaxRepeat = L1_MaxOfRepeats != 0 ? array.indexof(DnSideTimesRepeatedArray,L1_MaxOfRepeats) : -1 L1_ValueRepeatedMax = L1_IndexOfMaxRepeat != -1 ? array.get(DnSideListOfOutputValue,L1_IndexOfMaxRepeat) : 0 [ValueTestedMaxNoOfTimes,H1_ValueRepeatedMax,L1_ValueRepeatedMax] //#endregion //#region G_Pivots // @function to retrieve the Pivot High and Low points (Highest Point and the latest PH and similarly Lowest Point and the latest PL) // @param int StartScanFrom default is 150 // @param float Source - default is close, will be used if the source is an external indicator // @param string PlotOnType - default is "HL" (possible use cases can be either "HL", "OC" or any any other string character so that it uses Source param to calculate the Pivot points) // @param int LBC - default is 4 Look Back period for Pivot points // @param int LBF - default is 2 Look forwar period for confirming the Pivot points // @returns tuples with useful information regarding pivot points export G_Pivots(int StartScanFrom = 150,float Source = close, simple string PlotOnType = "HL", int LBC = 4, int LBF = 2)=> Initial_PH = nz(ta.pivothigh(PlotOnType == 'HL' ? G_CandleInfo("CandleHigh",0,true) : PlotOnType == 'OC' ? math.max(G_CandleInfo("CandleOpen",0,true), G_CandleInfo("CandleClose",0,true)) : Source, LBC, LBF),0.0) Initial_PH_Candle = nz(ta.valuewhen(Initial_PH, bar_index[LBF], 0),0) Initial_PL = nz(ta.pivotlow( PlotOnType == 'HL' ? G_CandleInfo("CandleLow",0,true) : PlotOnType == 'OC' ? math.min(G_CandleInfo("CandleOpen",0,true), G_CandleInfo("CandleClose",0,true)): Source, LBC, LBF),0.0) Initial_PL_Candle = nz(ta.valuewhen(Initial_PL, bar_index[LBF], 0),0) float First_PH = na float First_PL = na int FPH_Bar = na int FPL_Bar = na if BarToStartYourCalculation(StartScanFrom) First_PH := Initial_PH First_PL := Initial_PL FPH_Bar := Initial_PH_Candle FPL_Bar := Initial_PL_Candle var SeriesOf_PH = array.new_float(0) var CandleInfoOf_PH = array.new_int(0) var SeriesOf_PL = array.new_float(0) var CandleInfoOf_PL = array.new_int(0) var sizeH = array.size(SeriesOf_PH) var sizeL = array.size(SeriesOf_PL) //========================== PIVOT HIGH CALCULATION =============================== if First_PH != 0.00 if sizeH == 0 array.push(SeriesOf_PH,First_PH) array.push(CandleInfoOf_PH,FPH_Bar) else if FPH_Bar - array.get(CandleInfoOf_PH, sizeH - 1) > 4 and array.get(SeriesOf_PH, sizeH - 1) >= First_PH array.push(SeriesOf_PH,First_PH) array.push(CandleInfoOf_PH,FPH_Bar) else array.pop(SeriesOf_PH) array.pop(CandleInfoOf_PH) array.push(SeriesOf_PH,First_PH) array.push(CandleInfoOf_PH,FPH_Bar) //========================== PIVOT LOW CALCULATION =============================== if First_PL != 0.00 if sizeL == 0 array.push(SeriesOf_PL,First_PL) array.push(CandleInfoOf_PL,FPL_Bar) else if FPL_Bar - array.get(CandleInfoOf_PL, sizeL - 1) > 4 and array.get(SeriesOf_PL, sizeL - 1) <= First_PL array.push(SeriesOf_PL,First_PL) array.push(CandleInfoOf_PL,FPL_Bar) else array.pop(SeriesOf_PL) array.pop(CandleInfoOf_PL) array.push(SeriesOf_PL,First_PL) array.push(CandleInfoOf_PL,FPL_Bar) float LastKnownPL = 0 int LastKnownPLBar = 0 float SecLowestPL = 0 int SecLowestPLBar = 0 int indexOfSecLowestPL = 0 int indexOfLastKnownPLBar = 0 CopyOfPL = array.copy(SeriesOf_PL) if array.size(SeriesOf_PL)> 3 array.pop(CopyOfPL) LastKnownPL := array.pop(CopyOfPL) array.sort(CopyOfPL) array.shift(CopyOfPL) SecLowestPL := array.min(CopyOfPL) indexOfSecLowestPL:= array.indexof(SeriesOf_PL,SecLowestPL) indexOfLastKnownPLBar:= array.indexof(SeriesOf_PL,LastKnownPL) float LastKnownPH = 0 int LastKnownPHBar = 0 float SecHighestPH = 0 int SecHighestPHBar = 0 int indexOfSecHighestPH = 0 int indexOfLastKnownPHBar = 0 CopyOfPH = array.copy(SeriesOf_PH) if array.size(SeriesOf_PH)> 3 array.pop(CopyOfPH) LastKnownPH := array.pop(CopyOfPH) array.sort(CopyOfPH,order.descending) array.shift(CopyOfPH) SecHighestPH := array.max(CopyOfPH) indexOfSecHighestPH:= array.indexof(SeriesOf_PH,SecHighestPH) indexOfLastKnownPHBar:= array.indexof(SeriesOf_PH,LastKnownPH) float LL_Val = 0 int LL_Bar = 0 float HL_Val = 0 int HL_Bar = 0 int indexOfMin = 0 float HH_Val = 0 int HH_Bar = 0 float LH_Val = 0 int LH_Bar = 0 int DindexOfMax = 0 LL_Val := array.min(SeriesOf_PL) HH_Val := array.max(SeriesOf_PH) indexOfMin := array.indexof(SeriesOf_PL,array.min(SeriesOf_PL)) DindexOfMax := array.indexof(SeriesOf_PH,array.max(SeriesOf_PH)) int cntr = 0 for ele in CandleInfoOf_PL if cntr == indexOfMin LL_Bar:= ele else if cntr == indexOfSecLowestPL SecLowestPLBar:= ele else if cntr == indexOfLastKnownPLBar LastKnownPLBar:= ele else HL_Bar:= ele cntr+= 1 int cntr1 = 0 for ele in SeriesOf_PL HL_Val:= ele cntr1+= 1 int Rcntr = 0 for ele in CandleInfoOf_PH if Rcntr == DindexOfMax HH_Bar:= ele else if Rcntr == indexOfSecHighestPH SecHighestPHBar:= ele else if Rcntr == indexOfLastKnownPHBar LastKnownPHBar:= ele else LH_Bar:= ele Rcntr+= 1 int Rcntr1 = 0 for ele in SeriesOf_PH LH_Val:= ele cntr1+= 1 [LL_Bar, SecLowestPLBar, LastKnownPLBar, HL_Bar, LL_Val, SecLowestPL, LastKnownPL, HL_Val, HH_Bar, SecHighestPHBar, LastKnownPHBar, LH_Bar, HH_Val, SecHighestPH, LastKnownPH, LH_Val] //#endregion //#region DiscordGetAccountInfo export DiscordGetAccountInfo(bool OnlyJoin = false, string JoinText = "", int MainOption = 1, int SubOption = 0, string AlternativeSource = "", string AlternativeScriptType = "") => DiscText = switch MainOption 1 => "PNL" 2 => "MTM" 3 => "FUNDS" 4 => "CEXP" 5 => "NEXP" 6 => "ABAL" 7 => "MAR" 8 => "PAYIN" 9 => "PAYOUT" 10 => SubOption == 0 ? "PRICE " : SubOption == 1 ? "PRICE BNF" : "PRICE NIF" 11 => "EXITBCO ALL" 12 => "EXIT_ALL" if not OnlyJoin if ScriptConvertor("Type", AlternativeSource, AlternativeScriptType) == "F" Output = MainOption != 10 or (MainOption == 10 and SubOption != 0) ? '{"content":"' + DiscText +'"}' : MainOption == 10 and SubOption == 0 ? '{"content":"' + DiscText + ScriptConvertor("Name", AlternativeSource, AlternativeScriptType) + " " + ScriptConvertor("Exp", AlternativeSource, AlternativeScriptType) + "F" +'"}' : '{"content":"' + DiscText +'"}' else Output = MainOption != 10 or (MainOption == 10 and SubOption != 0) ? '{"content":"' + DiscText +'"}' : MainOption == 10 and SubOption == 0 ? '{"content":"' + DiscText + ScriptConvertor("Name", AlternativeSource, AlternativeScriptType) + '"}' : '{"content":"' + DiscText +'"}' else Output = '{"content":"' + JoinText +'"}' //#endregion //#region DiscordTradingJSON // @param TradeType acceptable Inputs are I (for MIS / Intraday), CO (for Cover Order), BO (for Bracket Order) // @param BuyOrSell acceptable Inputs are B or S // @param EqOrFutOrOp acceptable Inputs are E (for Equity), F (for Futures), O (for Options) // @param TradeQty string format (default = 25 Qty) // @param ScriptName string format // @param OrderType acceptable Inputs are "" (for Market), "XXX.XX" (143.05 to place Limit Orders at 143.05), Continued Below 2 other acceptable inputs... // @param OrderType "X.X%" (1.25% to place Limit orders at specified percentage Below Market price for BUY, and Above Market price for SELL) // @param OrderType "A X.X%" or "B X.X%" or "A 154.0" or "B 125.0" (A 0.75% to place BUY SL-Limit orders at specified percentage Above Market price for BUY, B 1.05% to place SELL SL-Limit orders at specified percentage Below Market price for SELL) // @param HowDeep acceptable Inputs are "0" (for ATM option), "1" (Positive Numbers for ITM), "-1" (Negative Numbers for OTM) or "" (for Non Expiry Orders) // @param CEorPE acceptable Inputs are CE, PE or "" (for Non Option Orders) // @param Expiry acceptable Inputs are C (for Current Expiry), N (for Next Expiry) or "" (for Non Expiry Orders) // @param BO_Tgt acceptable Inputs are "X" (5 for Rs.5 Target Point), "X.X%" (1.2% for capturing specified percentage rise in price as Target Points for BUY) or "" (for Non BO Orders) // @param BO_SL acceptable Inputs are "X" (3 for Rs.3 SL Point), "X.X%" (0.75% for specified percentage fall in price as SL Points for BUY) or "" (for Non BO Orders) // @param CO_SL acceptable Inputs are "+X" (+3 for Rs.3 above current price for Sell Trade), "-X" (-5 for Rs.5 below current price for Buy Trade), "XXX.X" (125.5 will be applied as SL Value for CO Order) or "" (for Non Expiry Orders) export DiscordTradingJSON(string TradeType = "I", string BuyOrSell = "B", string EqOrFutOrOp = "O", string TradeQty = "25", string ScriptName, string OrderType = "", string HowDeep = "", string CEorPE = "", string Expiry = "", string BO_Tgt = "", string BO_SL = "", string CO_SL = "")=> TT = switch TradeType "CO" => "CO" "BO" => "BO" => "" BS = switch BuyOrSell "B" => "B" => "S" EFO = switch EqOrFutOrOp "O" => "O" "F" => "F" => "E" Ex = switch Expiry "N" => "N" => "" IsCO = CO_SL != "" and TT == "CO" and (EFO == "E" or EFO == "F") and OrderType == "" IsBO = BO_SL != "" and BO_Tgt != "" and TT == "BO" and (EFO == "E" or EFO == "F") and OrderType == "" IsOptions = EFO == "O" and HowDeep != "" and TT == "" and CEorPE != "" and Expiry != "" Construct = if TT == "" if EFO == "E" or EFO == "F" if OrderType == "" BS + EFO + " " + TradeQty + " " + ScriptName else BS + EFO + " " + TradeQty + " " + ScriptName + " " + OrderType else if EFO == "O" and IsOptions and not IsBO and not IsCO if OrderType == "" BS + EFO + " " + TradeQty + " " + ScriptName + "?" + HowDeep + CEorPE + "?" + Ex else BS + EFO + " " + TradeQty + " " + ScriptName + "?" + HowDeep + CEorPE + "?" + Ex + " " + OrderType else "Something Wrong" else if IsCO TT + BS + EFO + " " + TradeQty + " " + ScriptName + " " + CO_SL else if IsBO TT + BS + EFO + " " + TradeQty + " " + ScriptName + " " + BO_Tgt + " " + BO_SL else "Something Wrong" //#endregion //#region TriggerAlertAfter // @param _cond acceptable Inputs are seconds to wait and then trigger the output as NA // @param _resetCond acceptable Inputs are true or false export TriggerAlertAfter(int cond = 15, bool _resetCond = barstate.isnew) => // bool _cond : condition to test. // bool _resetCond: when `true`, the duration resets. _cond = timenow <= (time + (cond * 1000)) varip float _timeBegin = na varip bool _lastCond = false if _resetCond // Reset time if required. _timeBegin := _cond ? timenow : na else if _cond if not _lastCond // First occurrence of true `_cond`; save beginnning time. _timeBegin := timenow else // Condition is not true; reset beginning time. _timeBegin := na // Remember the last state of the `_cond` so we can detect transitions. _lastCond := _cond // Return seconds since beginning of condition, or `na`. float _return = (timenow - _timeBegin) / 1000 //#endregion //#region DiscordStrategyAdd // @param bool Deploy acceptable Inputs are true for Deploy based Strategy Alert or false for Adding Strategy Alert type // @param string StrategyShortName specify the shortname for either deploying based or Adding based // @param string StrategyFullName specify the fullname for strategy Addition // @param ArrayString LegValues specify the array containing list of Leg Values else use array.new_string(0) export DiscordStrategyAdd(bool Deploy = true, string StrategyShortName = "", string OnScript = "", int TradingQty = 0, string[] LegValues, string StrategyFullName = "") => Output = "" if Deploy and StrategyShortName != "" and TradingQty == 0 Output := '{"content":"STRGY DEP ' + str.upper(StrategyShortName) +'"}' else if Deploy and StrategyShortName != "" and TradingQty > 0 and OnScript != "" Output := '{"content":"STRGY DEP ' + str.upper(StrategyShortName) + ' ' + str.upper(OnScript) + ' ' + str.tostring(TradingQty) +'"}' else if not Deploy and array.size(LegValues) > 0 and StrategyShortName != "" and StrategyFullName != "" InitialText = '{"content":"STRGY ADD ' NameText = '{"Strategy Name": "' + StrategyFullName + '", ' ShortNameText = '"Short Name": "' + StrategyShortName + '", "LegValues": [' EndText = ']}"' LegJoinText = "" for [cntr, Lv] in LegValues if cntr != array.size(LegValues) - 1 LegJoinText := LegJoinText + '{"LEG": "' + str.upper(Lv) + '"}, ' else LegJoinText := LegJoinText + '{"LEG": "' + str.upper(Lv) + '"}' Output := InitialText + str.upper(NameText) + str.upper(ShortNameText) + str.upper(LegJoinText) + EndText //#endregion //#endregion
Strategy Table Library
https://www.tradingview.com/script/1jL2WC73/
only_fibonacci
https://www.tradingview.com/u/only_fibonacci/
133
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © only_fibonacci //@version=5 // @description TODO: With this library, you can add tables to your strategies. library("table_library", overlay=true) // @returns Strategy Profit Table // Adds a table to the graph of the strategy for which you are calling the function. You can see data such as net profit in this table. export strategy_table() => //-----------TABLE // COLUMNS var table tablo = table.new(position.top_right,2,6,border_width=4,border_color=color.gray, frame_color=color.gray, frame_width=4) table.cell(tablo,0,0,bgcolor=color.black,text_color=color.white, text="NET PROFIT") table.cell(tablo,0,1,bgcolor=color.black,text_color=color.white, text="TOTAL PROFIT") table.cell(tablo,0,2,bgcolor=color.black,text_color=color.white, text="TOTAL LOSS") table.cell(tablo,0,3,bgcolor=color.black,text_color=color.white, text="PROFIT FACTOR") table.cell(tablo,0,4,bgcolor=color.black,text_color=color.white, text="WIN TRADES") table.cell(tablo,0,5,bgcolor=color.black,text_color=color.white, text="LOSS TRADES") // ROWS table.cell(tablo,1,0,bgcolor=strategy.netprofit>0 ? color.green : color.red,text_color=color.white, text=str.tostring(strategy.netprofit)) table.cell(tablo,1,1,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.grossprofit)) table.cell(tablo,1,2,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.grossloss)) table.cell(tablo,1,3,bgcolor=strategy.grossprofit / strategy.grossloss >1 ? color.green : color.red,text_color=color.white, text=str.tostring(strategy.grossprofit / strategy.grossloss)) table.cell(tablo,1,4,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.wintrades)) table.cell(tablo,1,5,bgcolor=color.black,text_color=color.white, text=str.tostring(strategy.losstrades)) tablo
bullratio
https://www.tradingview.com/script/os9Pk0Hd-bullratio/
slopip
https://www.tradingview.com/u/slopip/
11
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © slopip //@version=5 // @description Calculate the profit/loss ratio of a permabull for configurable time range library("bullratio") // @function calculates the profit/loss ratio for a permabull of age len // @param len the number of candles to include in the running bull ratio - 0 for all time // @returns series float of profit/loss percentage export bullratio(int len) => var bullspend = 0.0 var allbuys = 0.0 if(len == 0) bullspend := ta.cum(close*volume) allbuys := ta.cum(volume) else bullspend := math.sum(close*volume, len) allbuys := math.sum(volume, len) bullratio = ((close*allbuys)/bullspend)-1 bullratio := bullratio > 0? 1-(bullspend/(close*allbuys)): bullratio
Time Functions
https://www.tradingview.com/script/2Urtmxjz-Time-Functions/
standingtiger
https://www.tradingview.com/u/standingtiger/
1
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © standingtiger //@version=5 // @description TODO: add library description here library("TimeFunctions") // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns //export fun(float x) => //TODO : add function body and return value here // x export TimeframetoInt(string tf) => int i = switch tf "1" => 1 "5" => 5 "10" => 10 "15" => 15 "30" => 30 "60" => 60 "H1" => 60 "H4" => 240 "1D" => 1440 export BarsSinceOpen(int t, string timeframe) => t1 = (((t%8.64e7)/1000)-48600)/60 tf = TimeframetoInt(timeframe) t2 = t1/tf t2
FunctionPatternFrequency
https://www.tradingview.com/script/LmDW3o1o-FunctionPatternFrequency/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
16
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Counts the word or integer number pattern frequency on a array. // reference: // http://rosettacode.org/wiki/Word_frequency library(title='FunctionPatternFrequency') import RicardoSantos/DebugConsole/10 as console // @function counts the number a pattern is repeated. // @param pattern : array<string> : array with patterns to be counted. // @returns // array<string> : list of unique patterns. // array<int> : list of counters per pattern. // usage: // count(array.from('a','b','c','a','b','a')) export count (array<string> patterns) => //{ array<string> _patterns = array.copy(patterns) array<string> _freq_patterns = array.new<string>(0) array<int> _freq_counters = array.new<int>(0) while array.size(_patterns) > 0 string _pattern = array.shift(_patterns) int _pattern_idx = array.indexof(_freq_patterns, _pattern) if _pattern_idx >= 0 array.set(_freq_counters, _pattern_idx, array.get(_freq_counters, _pattern_idx) + 1) else array.push(_freq_patterns, _pattern) array.push(_freq_counters, 1) [_freq_patterns, _freq_counters] // example: { //string str1 = str.lower('Cras pharetra lorem non tempus mollis orci ipsum consequat sem non finibus odio augue vitae arcu Lorem ipsum dolor sit amet consectetur adipiscing elit Integer condimentum semper semper. Ut arcu purus, condimentum a lorem ac, pretium semper risus. Aliquam sit amet magna non lorem varius pellentesque. Maecenas in enim sed purus sodales lacinia in a turpis. In hac habitasse platea dictumst. Nullam placerat, ante non imperdiet dignissim, lectus arcu bibendum nisi, eu bibendum est libero ut urna. Etiam eget neque suscipit, semper ligula id, laoreet magna. Vivamus id erat id lacus elementum pretium. Donec felis justo, dapibus at condimentum sit amet, ultricies ut enim. Nulla facilisi. Ut porttitor vel enim sed interdum. Donec sed quam viverra laoreet nisl sed interdum dui Nam suscipit eros eu velit posuere et elementum nisl consequat') //string str2 = 'the red fox jumped the fence of the farmer and ate the chicken of the farmer' //array<string> txt = str.split(str1, ' ') //[fp, fc] = count(txt) //if barstate.islast // console.log( // str.tostring(array.slice(fp, 0, math.min(10, array.size(fp)))) + // '\n' + // str.tostring(array.slice(fc, 0, math.min(10, array.size(fc))))) //} //} // @function counts the number a pattern is repeated. // @param pattern : array<int> : array with patterns to be counted. // @returns // array<int> : list of unique patterns. // array<int> : list of counters per pattern. // usage: // count(array.from(1,2,3,1,2,1)) export count (array<int> patterns) => //{ array<int> _patterns = array.copy(patterns) array<int> _freq_patterns = array.new<int>(0) array<int> _freq_counters = array.new<int>(0) while array.size(_patterns) > 0 int _pattern = array.shift(_patterns) int _pattern_idx = array.indexof(_freq_patterns, _pattern) if _pattern_idx >= 0 array.set(_freq_counters, _pattern_idx, array.get(_freq_counters, _pattern_idx) + 1) else array.push(_freq_patterns, _pattern) array.push(_freq_counters, 1) [_freq_patterns, _freq_counters] // example: { array<int> int1 = array.from(1, 2, 3, 44, 1, 2, 3, 1, 2, 1) [fp1, fc1] = count(int1) if barstate.islast console.log( str.tostring(array.slice(fp1, 0, math.min(10, array.size(fp1)))) + '\n' + str.tostring(array.slice(fc1, 0, math.min(10, array.size(fc1))))) //} //}
RecursiveAlerts
https://www.tradingview.com/script/DWO4FzuI-RecursiveAlerts/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
70
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description The library provides options to run alert() calls in loop without worrying about limitations of frequency options. // When an alert statement is called within a loop, // it will fire just once per bar irrespective of how many iterations allowed when fequency is set to alert.freq_once_per_bar or alert.freq_once_per_bar_close // it will fire continuously till it breaks when frequency is set to alert.freq_all // The function helps overcome this issue by using varip key array which resets on every bar library("RecursiveAlerts", overlay=true) // @function Enhanced alert which can be used in loops // @param message Alert message to be fired // @param key Key to be checked to avoid repetitive alerts // @returns array containing id of already fired alerts export rAlert(string message, string key) => varip fired = array.new<string>() if(barstate.isrealtime) if(barstate.isnew) array.clear(fired) if not array.includes(fired, key) alert(message, alert.freq_all) array.push(fired, key) fired // @function Updates alert template with given keys and values // @param template Alert message template // @param keys array containing placeholders to be replaced // @param values array containing values which will replace placeholder keys // @returns updated alert message export updateAlertTemplate(string template, string[] keys, string[] values)=> updatedAlert = template for [i, key] in keys updatedAlert := str.replace_all(updatedAlert, key, array.get(values, i)) updatedAlert
LibBacktestingDayRange
https://www.tradingview.com/script/Vz4QzcG7-LibBacktestingDayRange/
Nut_Satit
https://www.tradingview.com/u/Nut_Satit/
2
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Nut_Satit //@version=5 // @description TODO: add library description here library("LibBacktestingDayRange", overlay=true) // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns export rangdate(int startDate, int finishDate) => //TODO : add function body and return value here // Backtesting day range // Your insert undercode [$time_cond]to Buy Sell Condition // ($time_cond and [Condition]) time_cond = time >= startDate and time <= finishDate
Moving_Averages
https://www.tradingview.com/script/PfHvOTgk-Moving-Averages/
MightyZinger
https://www.tradingview.com/u/MightyZinger/
40
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © MightyZinger //@version=5 // @description This library contains all majority important moving averages' funtions with int series support. library("Moving_Averages") // @function Exponential Moving Average (EMA) // @param src Source // @param len Period // @returns Exponential Moving Average with Series Int Support (EMA) export ema(float src, int len) => // ─── Arnaud Legoux Moving Average (ALMA) float result = 0.0 result := (src - nz(result[1])) * (2.0 / (len + 1)) + nz(result[1]) result // @function Arnaud Legoux Moving Average (ALMA) // @param src Source // @param len Period // @param a_offset Arnaud Legoux offset // @param a_sigma Arnaud Legoux sigma // @returns Arnaud Legoux Moving Average (ALMA) export alma(float src, int len, float a_offset, float a_sigma) => // ─── Arnaud Legoux Moving Average (ALMA) var float result = 0.0 result := ta.alma(src, len, a_offset, a_sigma) result // @function Coefficient of Variation Weighted Exponential Moving Average (COVWEMA) // @param src Source // @param len Period // @returns Coefficient of Variation Weighted Exponential Moving Average (COVWEMA) export covwema(float src, int len) => // ─── Coefficient of Variation Weighted Exponential Moving Average (COVWEMA) var float result = 0.0 _dev = ta.stdev(src, len) _ema = ema(src, len) _cov = _dev / _ema _cWg = src * _cov result := math.sum(_cWg, len) / math.sum(_cov, len) result // @function Coefficient of Variation Weighted Moving Average (COVWMA) // @param src Source // @param len Period // @returns Coefficient of Variation Weighted Moving Average (COVWMA) export covwma(float src, int len) => // Coefficient of Variation Weighted Moving Average (COVWMA) var float result = 0.0 _dev = ta.stdev(src, len) _sma = ta.sma(src, len) _cov = _dev / _sma _cWg = src * _cov result := math.sum(_cWg, len) / math.sum(_cov, len) result // @function DEMA - Double Exponential Moving Average // @param src Source // @param len Period // @returns DEMA - Double Exponential Moving Average export dema(float src, int len) => // DEMA - Double Exponential Moving Average var float result = 0.0 e = ema(src, len) result := 2 * e - ema(e, len) result // EDSMA Pre-requisits functions get2PoleSSF(src, length) => PI = 2 * math.asin(1) arg = math.sqrt(2) * PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(arg) c2 = b1 c3 = -math.pow(a1, 2) c1 = 1 - c2 - c3 ssf = 0.0 ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2]) ssf get3PoleSSF(src, length) => PI = 2 * math.asin(1) arg = PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(1.738 * arg) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -(c1 + b1 * c1) coef4 = math.pow(c1, 2) coef1 = 1 - coef2 - coef3 - coef4 ssf = 0.0 ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3]) ssf // @function EDSMA - Ehlers Deviation Scaled Moving Average // @param src Source // @param len Period // @param ssfLength EDSMA - Super Smoother Filter Length // @param ssfPoles EDSMA - Super Smoother Filter Poles // @returns Ehlers Deviation Scaled Moving Average (EDSMA) export edsma(float src, int len, int ssfLength, int ssfPoles) => // EDSMA - Ehlers Deviation Scaled Moving Average var float result = 0.0 zeros = src - nz(src[2]) avgZeros = (zeros + zeros[1]) / 2 poles2 = get2PoleSSF(avgZeros, ssfLength) poles3 = get3PoleSSF(avgZeros, ssfLength) // Ehlers Super Smoother Filter ssf = ssfPoles == 2 ? poles2 : poles3 // Rescale filter in terms of Standard Deviations stdev = ta.stdev(ssf, len) scaledFilter = stdev != 0 ? ssf / stdev : 0 alpha = 5 * math.abs(scaledFilter) / len edsma = 0.0 edsma := alpha * src + (1 - alpha) * nz(edsma[1]) result := edsma result // @function Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA) // @param src Source // @param len Period // @param FC Lower Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average // @param SC Upper Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average // @returns Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA) export eframa(float src, int len, int FC, int SC) => // Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA) var float result = 0.0 len1 = len / 2 e = 2.7182818284590452353602874713527 w = math.log(2 / (SC + 1)) / math.log(e) // Natural logarithm (ln(2/(SC+1))) workaround H1 = ta.highest(high, len1) L1 = ta.lowest(low, len1) N1 = (H1 - L1) / len1 H2 = ta.highest(high, len1)[len1] L2 = ta.lowest(low, len1)[len1] N2 = (H2 - L2) / len1 H3 = ta.highest(high, len) L3 = ta.lowest(low, len) N3 = (H3 - L3) / len dimen1 = (math.log(N1 + N2) - math.log(N3)) / math.log(2) dimen = N1 > 0 and N2 > 0 and N3 > 0 ? dimen1 : nz(dimen1[1]) alpha1 = math.exp(w * (dimen - 1)) oldalpha = alpha1 > 1 ? 1 : alpha1 < 0.01 ? 0.01 : alpha1 oldN = (2 - oldalpha) / oldalpha N = (SC - FC) * (oldN - 1) / (SC - 1) + FC alpha_ = 2 / (N + 1) alpha = alpha_ < 2 / (SC + 1) ? 2 / (SC + 1) : alpha_ > 1 ? 1 : alpha_ result := (1 - alpha) * nz(result[1]) + alpha * src result // @function EHMA - Exponential Hull Moving Average // @param src Source // @param len Period // @returns Exponential Hull Moving Average (EHMA) export ehma(float src, int len) => // EHMA - Exponential Hull Moving Average var float result = 0.0 result := ema(2 * ema(src, len / 2) - ema(src, len), math.round(math.sqrt(len))) result // @function Exponential Triangular Moving Average (ETMA) // @param src Source // @param len Period // @returns Exponential Triangular Moving Average (ETMA) export etma(float src, int len) => // ─── Exponential Triangular Moving Average (ETMA) var float result = 0.0 result := ema(ema(src, len), len) result // @function Fractal Adaptive Moving Average (FRAMA) // @param src Source // @param len Period // @returns Fractal Adaptive Moving Average (FRAMA) export frama(float src, int len) => // ─── Fractal Adaptive Moving Average (FRAMA) var float result = 0.0 _coef = -4.6 _len0 = len _len2 = len / 2 _hl0 = (ta.highest(high, _len0) - ta.lowest(low, _len0)) / _len0 _hl1 = (ta.highest(high, _len2) - ta.lowest(low, _len2)) / _len2 _hl2 = (ta.highest(high, _len2)[_len2] - ta.lowest(low, _len2)[_len2]) / _len2 _dim = _hl0 > 0 and _hl1 > 0 and _hl2 > 0 ? (math.log(_hl2 + _hl1) - math.log(_hl0)) / math.log(2) : 0 _alpha = math.exp(_coef * (_dim - 1)) _sc = _alpha < 0.01 ? 0.01 : _alpha > 1 ? 1 : _alpha var _frama = src _frama := bar_index <= _len0 + 1 ? src : src * _sc + nz(_frama[1]) * (1 - _sc) result := _frama result // @function HMA - Hull Moving Average // @param src Source // @param len Period // @returns Hull Moving Average (HMA) export hma(float src, int len) => // HMA - Hull Moving Average var float result = 0.0 result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result // @function Jurik Moving Average - JMA // @param src Source // @param len Period // @param jurik_phase Jurik (JMA) Only - Phase // @param jurik_power Jurik (JMA) Only - Power // @returns Jurik Moving Average (JMA) export jma(float src, int len, int jurik_phase, int jurik_power) => // Jurik Moving Average - JMA /// Copyright © 2018 Alex Orekhov (everget) /// Copyright © 2017 Jurik Research and Consulting. var float result = 0.0 phaseRatio = jurik_phase < -100 ? 0.5 : jurik_phase > 100 ? 2.5 : jurik_phase / 100 + 1.5 _beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2) _alpha = math.pow(_beta, jurik_power) jma = 0.0 e0 = 0.0 e0 := (1 - _alpha) * src + _alpha * nz(e0[1]) e1 = 0.0 e1 := (src - e0) * (1 - _beta) + _beta * nz(e1[1]) e2 = 0.0 e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - _alpha, 2) + math.pow(_alpha, 2) * nz(e2[1]) jma := e2 + nz(jma[1]) result := jma result // @function Kaufman's Adaptive Moving Average (KAMA) // @param src Source // @param len Period // @param k_fastLength Number of periods for the fastest exponential moving average // @param k_slowLength Number of periods for the slowest exponential moving average // @returns Kaufman's Adaptive Moving Average (KAMA) export kama(float src, int len, float k_fastLength, float k_slowLength) => // ─── Kaufman's Adaptive Moving Average (KAMA) var float result = 0.0 var float _constant1 = 2 / (k_fastLength + 1) - 2 / (k_slowLength + 1) var float _constant2 = 2 / (k_slowLength + 1) _efficiencyRatio = nz(math.abs(ta.change(src, len)) / math.sum(math.abs(ta.change(src)), len)) _smoothingConstant = math.pow(math.abs(_efficiencyRatio * _constant1 + _constant2), 2) result := nz(result[1]) + _smoothingConstant * (src - nz(result[1])) result // @function Kijun v2 // @param _high High value of bar // @param _low Low value of bar // @param len Period // @param kidiv Kijun MOD Divider // @returns Kijun v2 export kijun(float _high, float _low, int len, int kidiv) => // Kijun v2 var float result = 0.0 kijun = math.avg(ta.lowest(_high, len), ta.highest(_low, len)) //, (open + close)/2) conversionLine = math.avg(ta.lowest(_low, len / kidiv), ta.highest(_high, len / kidiv)) delta = (kijun + conversionLine) / 2 result := delta result // @function LSMA/LRC - Least Squares Moving Average / Linear Regression Curve // @param src Source // @param len Period // @param offset Offset // @returns Least Squares Moving Average (LSMA)/ Linear Regression Curve (LRC) export lsma(float src, int len, int offset) => // LSMA/LRC - Least Squares Moving Average / Linear Regression Curve var float result = 0.0 result := ta.linreg(src, len, offset) result // @function MF - Modular Filter // @param src Source // @param len Period // @param beta Modular Filter, General Filter Only - Beta // @param feedback Modular Filter Only - Feedback // @param z Modular Filter Only - Feedback Weighting // @returns Modular Filter (MF) export mf(float src, int len, float beta, bool feedback, float z) => // MF - Modular Filter var float result = 0.0 ts = 0. b = 0. c = 0. os = 0. //---- alpha = 2 / (len + 1) a = feedback ? z * src + (1 - z) * nz(ts[1], src) : src //---- b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a) c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a) os := a == b ? 1 : a == c ? 0 : os[1] //---- upper = beta * b + (1 - beta) * c lower = beta * c + (1 - beta) * b ts := os * upper + (1 - os) * lower result := ts result // @function RMA - RSI Moving average // @param src Source // @param len Period // @returns RSI Moving average (RMA) export rma(float src, int len) => // RMA - RSI Moving average var float result = 0.0 alpha = 1 / len result := alpha * src + (1 - alpha) * nz(result[1]) result // @function SMA - Simple Moving Average // @param src Source // @param len Period // @returns Simple Moving Average (SMA) export sma(float src, int len) => // SMA - Simple Moving Average var float result = 0.0 result := ta.sma(src, len) result // @function Smoothed Moving Average (SMMA) // @param src Source // @param len Period // @returns Smoothed Moving Average (SMMA) export smma(float src, int len) => // Smoothed Moving Average (SMMA) var float result = 0.0 _sma = ta.sma(src, len) result := na(result[1]) ? _sma : (result[1] * (len - 1) + src) / len result // @function Simple Triangular Moving Average (STMA) // @param src Source // @param len Period // @returns Simple Triangular Moving Average (STMA) export stma(float src, int len) => // Simple Triangular Moving Average (STMA) var float result = 0.0 result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result // @function TEMA - Triple Exponential Moving Average // @param src Source // @param len Period // @returns Triple Exponential Moving Average (TEMA) export tema(float src, int len) => // TEMA - Triple Exponential Moving Average var float result = 0.0 e = ema(src, len) result := 3 * (e - ema(e, len)) + ema(ema(e, len), len) result // @function THMA - Triple Hull Moving Average // @param src Source // @param len Period // @returns Triple Hull Moving Average (THMA) export thma(float src, int len) => // THMA - Triple Hull Moving Average var float result = 0.0 result := ta.wma(ta.wma(src, len / 3) * 3 - ta.wma(src, len / 2) - ta.wma(src, len), len) result // @function VAMA - Volatility Adjusted Moving Average // @param src Source // @param len Period // @param volatility_lookback Volatility lookback length // @returns Volatility Adjusted Moving Average (VAMA) export vama(float src, int len, int volatility_lookback) => // VAMA - Volatility Adjusted Moving Average var float result = 0.0 mid = ema(src, len) dev = src - mid vol_up = ta.highest(dev, volatility_lookback) vol_down = ta.lowest(dev, volatility_lookback) result := mid + math.avg(vol_up, vol_down) result // @function Variable Index Dynamic Average (VIDYA) // @param src Source // @param len Period // @returns Variable Index Dynamic Average (VIDYA) export vidya(float src, int len) => // ─── Variable Index Dynamic Average (VIDYA) var float result = 0.0 _cmo = ta.cmo(src, len) / 100 //Chande Momentum Oscillator var _factor = 2 / (len + 1) result := src * _factor * math.abs(_cmo) + nz(result[1]) * (1 - _factor * math.abs(_cmo)) result // @function Volume-Weighted Moving Average (VWMA) // @param src Source // @param len Period // @returns Volume-Weighted Moving Average (VWMA) export vwma(float src, int len) => // Volume-Weighted Moving Average (VWMA) var float result = 0.0 result := ta.vwma(src, len) result // @function WMA - Weighted Moving Average // @param src Source // @param len Period // @returns Weighted Moving Average (WMA) export wma(float src, int len) => // WMA - Weighted Moving Average var float result = 0.0 result := ta.wma(src, len) result // @function Zero-Lag Exponential Moving Average (ZEMA) // @param src Source // @param len Period // @returns Zero-Lag Exponential Moving Average (ZEMA) export zema(float src, int len) => // ─── Zero-Lag Exponential Moving Average (ZEMA) var float result = 0.0 var _l = (len + 1) / 2 _srcL = src + nz(ta.mom(src, _l)) result := ema(_srcL, len) result // @function Zero-Lag Simple Moving Average (ZSMA) // @param src Source // @param len Period // @returns Zero-Lag Simple Moving Average (ZSMA) export zsma(float src, int len) => // ─── Zero-Lag Simple Moving Average (ZSMA) var float result = 0.0 var _l = (len + 1) / 2 _srcL = src + nz(ta.mom(src, _l)) result := ta.sma(_srcL, len) result // @function EVWMA - Elastic Volume Weighted Moving Average // @param src Source // @param len Period // @returns Elastic Volume Weighted Moving Average (EVWMA) export evwma(float src, int len) => // EVWMA - Elastic Volume Weighted Moving Average // Copyright © LazyBear var float result = 0.0 nbfs = math.sum(volume, len) result := nz(result[1]) * (nbfs - volume) / nbfs + volume * src / nbfs result // @function Tillson T3 // @param src Source // @param len Period // @param a1_t3 Tillson T3 Volume Factor // @returns Tillson T3 export tt3(float src, int len, float a1_t3) => // Tillson T3 var float result = 0.0 result := -a1_t3 * a1_t3 * a1_t3 * ema(ema(ema(ema(ema(ema(src, len), len), len), len), len), len) + (3 * a1_t3 * a1_t3 + 3 * a1_t3 * a1_t3 * a1_t3) * ema(ema(ema(ema(ema(src, len), len), len), len), len) + (-6 * a1_t3 * a1_t3 - 3 * a1_t3 - 3 * a1_t3 * a1_t3 * a1_t3) * ema(ema(ema(ema(src, len), len), len), len) + (1 + 3 * a1_t3 + a1_t3 * a1_t3 * a1_t3 + 3 * a1_t3 * a1_t3) * ema(ema(ema(src, len), len), len) result // @function GMA - Geometric Moving Average // @param src Source // @param len Period // @returns Geometric Moving Average (GMA) export gma(float src, int len) => // GMA - Geometric Moving Average var float result = 0.0 sum = src for i = 1 to len - 1 by 1 sum *= src[i] sum result := math.pow(sum, 1 / len) result // @function WWMA - Welles Wilder Moving Average // @param src Source // @param len Period // @returns Welles Wilder Moving Average (WWMA) export wwma(float src, int len) => // WWMA - Welles Wilder Moving Average var float result = 0.0 result := (nz(result[1]) * (len - 1) + src) / len result // @function AMA - Adjusted Moving Average // @param src Source // @param _high High value of bar // @param _low Low value of bar // @param len Period // @param ama_f_length Fast EMA Length // @param ama_s_length Slow EMA Length // @returns Adjusted Moving Average (AMA) export ama(float src, float _high, float _low, int len, int ama_f_length, int ama_s_length) => // AMA - Adjusted Moving Average var float result = 0.0 fastAlpha = 2 / (ama_f_length + 1) slowAlpha = 2 / (ama_s_length + 1) hh = ta.highest(_high, len + 1) ll = ta.lowest(_low, len + 1) mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0 ssc_ = mltp * (fastAlpha - slowAlpha) + slowAlpha result := nz(result[1]) + math.pow(ssc_, 2) * (src - nz(result[1])) result // @function Corrective Moving average (CMA) // @param src Source // @param len Period // @returns Corrective Moving average (CMA) export cma(float src, int len) => // Corrective Moving average (CMA) var float result = 0.0 sma_ = ta.sma(src, len) _cma = sma_ v1 = ta.variance(src, len) v2 = math.pow(nz(_cma[1], _cma) - sma_, 2) v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2) var tolerance = math.pow(10, -5) float err = 1 // Gain Factor float kPrev = 1 float k = 1 for i = 0 to 5000 by 1 if err > tolerance k := v3 * kPrev * (2 - kPrev) err := kPrev - k kPrev := k kPrev _cma := nz(_cma[1], src) + k * (sma_ - nz(_cma[1], src)) result := _cma result // @function Geometric Mean Moving Average (GMMA) // @param src Source // @param len Period // @returns Geometric Mean Moving Average (GMMA) export gmma(float src, int len) => // Geometric Mean Moving Average (GMMA) var float result = 0.0 lmean = math.log(src) smean = math.sum(lmean, len) geoMA = math.exp(smean / len) result := geoMA result // @function Ehler's Adaptive Laguerre filter (EALF) // @param src Source // @param len Period // @param LAPercLen_ Median Length // @param FPerc_ Median Percentage // @returns Ehler's Adaptive Laguerre filter (EALF) export ealf(float src, int len, int LAPercLen_, simple float FPerc_) => // Ehler's Adaptive Laguerre filter var float result = 0.0 y = float(na) alpha = float(na) error = math.abs(src - nz(y[1])) le_ = ta.lowest(error, len) he_ = ta.highest(error, len) range_2 = he_ - le_ perc = range_2 != 0 ? (error - le_) / range_2 : nz(alpha[1]) alpha := ta.percentile_nearest_rank(perc, LAPercLen_, FPerc_) L0 = 0.0 L0 := alpha * src + (1 - alpha) * nz(L0[1]) L1 = 0.0 L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1]) L2 = 0.0 L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1]) L3 = 0.0 L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1]) y := (L0 + 2 * L1 + 2 * L2 + L3) / 6 result := y result // @function ELF - Ehler's Laguerre filter // @param src Source // @param len Period // @param LAPercLen_ Median Length // @param FPerc_ Median Percentage // @returns Ehler's Laguerre Filter (ELF) export elf(float src, int len) => // ELF - Ehler's Laguerre filter var float result = 0.0 y = float(na) alpha = math.exp((1 - len) / 20) // map length to alpha L0 = 0.0 L0 := alpha * src + (1 - alpha) * nz(L0[1]) L1 = 0.0 L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1]) L2 = 0.0 L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1]) L3 = 0.0 L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1]) y := (L0 + 2 * L1 + 2 * L2 + L3) / 6 result := y result // @function Exponentially Deviating Moving Average (MZ EDMA) // @param src Source // @param len Period // @returns Exponentially Deviating Moving Average (MZ EDMA) export edma(float src, int len) => // Exponentially Deviating Moving Average (MZ EDMA) var hexp = float(na) var lexp = float(na) var _hma = float(na) var _edma = float(na) float smoothness = 1.0 // Increasing smoothness will result in MA same as EMA h_len = int(len/1.5) // Length to be used in final calculation of Hull Moving Average // Defining Exponentially Expanding Moving Line hexp := na(hexp[1]) ? src : src >= hexp[1] ? src : hexp[1] + (src - hexp[1]) * (smoothness / (len + 1)) // Defining Exponentially Contracting Moving Line lexp := na(lexp[1]) ? hexp : src <= lexp[1] ? hexp : lexp[1] + (src - lexp[1]) * (smoothness / (len + 1)) // Calculating Hull Moving Average of resulted Exponential Moving Line with 3/2 of total length _hma := ta.wma(2 * ta.wma(lexp, h_len / 2) - ta.wma(lexp, h_len), math.round(math.sqrt(h_len))) _edma := _hma // EDMA will be equal to resulted smoothened Hull Moving Average _edma // @function PNR - percentile nearest rank // @param src Source // @param len Period // @param rank_inter_Perc_ Rank and Interpolation Percentage // @returns Percentile Nearest Rank (PNR) export pnr(float src, int len, simple float rank_inter_Perc_) => // PNR - percentile nearest rank. Calculates percentile using method of Nearest Rank. var float result = 0.0 result := ta.percentile_nearest_rank(src, len, rank_inter_Perc_) result // @function PLI - Percentile Linear Interpolation // @param src Source // @param len Period // @param rank_inter_Perc_ Rank and Interpolation Percentage // @returns Percentile Linear Interpolation (PLI) export pli(float src, int len, simple float rank_inter_Perc_) => // PLI - Percentile Linear Interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks. var float result = 0.0 result := ta.percentile_linear_interpolation(src, len, rank_inter_Perc_) result // @function Range EMA (REMA) // @param src Source // @param len Period // @returns Range EMA (REMA) export rema(float src, int len) => // Range EMA (REMA) var float result = 0.0 alpha = 2 / (1 + len) weight = high - low weight := weight == 0 ? syminfo.pointvalue : weight num = 0.0 den = 0.0 num := na(num[1]) ? weight * src : num[1] + alpha * (weight * src - num[1]) den := na(den[1]) ? weight : den[1] + alpha * (weight - den[1]) result := num / den result // @function Sine-Weighted Moving Average (SW-MA) // @param src Source // @param len Period // @returns Sine-Weighted Moving Average (SW-MA) export sw_ma(float src, int len) => // Sine-Weighted Moving Average (SW-MA) var float result = 0.0 PI_ = 2 * math.asin(1) sum = 0.0 weightSum = 0.0 for i = 0 to len - 1 by 1 weight = math.sin((i + 1) * PI_ / (len + 1)) sum += nz(src[i]) * weight weightSum += weight weightSum result := sum / weightSum result // @function Volume Weighted Average Price (VWAP) // @param src Source // @param len Period // @returns Volume Weighted Average Price (VWAP) export vwap(float src) => // Volume Weighted Average Price (VWAP) var float result = 0.0 var float sumSrcVol = na var float sumVol = na var float sumSrcSrcVol = na isNewPeriod = ta.change(time('D')) sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1] sumVol := isNewPeriod ? volume : volume + sumVol[1] result := sumSrcVol / sumVol result //{ MAMA & FAMA & HKAMA Pre-requisits // Original Hilbert by everget : https://www.tradingview.com/script/aaWzn9bK-Ehlers-MESA-Adaptive-Moving-Averages-MAMA-FAMA/ PI = 2 * math.asin(1) hilbertTransform(src) => 0.0962 * src + 0.5769 * nz(src[2]) - 0.5769 * nz(src[4]) - 0.0962 * nz(src[6]) computeComponent(src, mesaPeriodMult) => hilbertTransform(src) * mesaPeriodMult computeAlpha(src, fastLimit, slowLimit) => mesaPeriod = 0.0 mesaPeriodMult = 0.075 * nz(mesaPeriod[1]) + 0.54 smooth = 0.0 smooth := (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10 detrender = 0.0 detrender := computeComponent(smooth, mesaPeriodMult) // Compute InPhase and Quadrature components I1 = nz(detrender[3]) Q1 = computeComponent(detrender, mesaPeriodMult) // Advance the phase of I1 and Q1 by 90 degrees jI = computeComponent(I1, mesaPeriodMult) jQ = computeComponent(Q1, mesaPeriodMult) I2 = 0.0 Q2 = 0.0 // Phasor addition for 3 bar averaging I2 := I1 - jQ Q2 := Q1 + jI // Smooth the I and Q components before applying the discriminator I2 := 0.2 * I2 + 0.8 * nz(I2[1]) Q2 := 0.2 * Q2 + 0.8 * nz(Q2[1]) // Homodyne Discriminator Re = I2 * nz(I2[1]) + Q2 * nz(Q2[1]) Im = I2 * nz(Q2[1]) - Q2 * nz(I2[1]) Re := 0.2 * Re + 0.8 * nz(Re[1]) Im := 0.2 * Im + 0.8 * nz(Im[1]) if Re != 0 and Im != 0 mesaPeriod := 2 * PI / math.atan(Im / Re) mesaPeriod if mesaPeriod > 1.5 * nz(mesaPeriod[1]) mesaPeriod := 1.5 * nz(mesaPeriod[1]) mesaPeriod if mesaPeriod < 0.67 * nz(mesaPeriod[1]) mesaPeriod := 0.67 * nz(mesaPeriod[1]) mesaPeriod if mesaPeriod < 6 mesaPeriod := 6 mesaPeriod if mesaPeriod > 50 mesaPeriod := 50 mesaPeriod mesaPeriod := 0.2 * mesaPeriod + 0.8 * nz(mesaPeriod[1]) phase = 0.0 if I1 != 0 phase := 180 / PI * math.atan(Q1 / I1) phase deltaPhase = nz(phase[1]) - phase if deltaPhase < 1 deltaPhase := 1 deltaPhase alpha = fastLimit / deltaPhase if alpha < slowLimit alpha := slowLimit alpha [alpha, alpha / 2.0] // } // @function MAMA - MESA Adaptive Moving Average // @param src Source // @param len Period // @returns MESA Adaptive Moving Average (MAMA) export mama(float src, int len) => // MAMA - MESA Adaptive Moving Average var float result = 0.0 er = math.abs(ta.change(src, len)) / math.sum(math.abs(ta.change(src)), len) [a, b] = computeAlpha(src, er, er * 0.1) result := a * src + (1 - a) * nz(result[1]) result // @function FAMA - Following Adaptive Moving Average // @param src Source // @param len Period // @returns Following Adaptive Moving Average (FAMA) export fama(float src, int len) => // FAMA - Following Adaptive Moving Average var float result = 0.0 var float mama = 0.0 var float fama = 0.0 er = math.abs(ta.change(src, len)) / math.sum(math.abs(ta.change(src)), len) [a, b] = computeAlpha(src, er, er * 0.1) mama := a * src + (1 - a) * nz(mama[1]) fama := b * mama + (1 - b) * nz(fama[1]) result := fama result // @function HKAMA - Hilbert based Kaufman's Adaptive Moving Average // @param src Source // @param len Period // @returns Hilbert based Kaufman's Adaptive Moving Average (HKAMA) export hkama(float src, int len) => // HKAMA - Hilbert based Kaufman's Adaptive Moving Average var float result = 0.0 er = math.abs(ta.change(src, len)) / math.sum(math.abs(ta.change(src)), len) [a, b] = computeAlpha(src, er, er * 0.1) alpha = math.pow(er * (b - a) + a, 2) result := alpha * src + (1 - alpha) * nz(result[1]) result ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///// Plotting ////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// string MA01 = 'ALMA - Arnaud Legoux Moving Average' string MA02 = 'COVWEMA - Coefficient of Variation Weighted\tExponential Moving Average' string MA03 = 'COVWMA - Coefficient of Variation Weighted\tMoving Average' string MA04 = 'DEMA - Double Exponential Moving Average' string MA05 = 'EDSMA - Ehlers Deviation Scaled Moving Average' string MA06 = 'EFRAMA - Ehlrs Modified Fractal Adaptive Moving Average' string MA07 = 'EHMA - Exponential Hull Moving Average' string MA08 = 'EMA - Exponential Moving Average' string MA09 = 'ETMA - Exponential Triangular Moving Average' string MA10 = 'FRAMA - Fractal Adaptive Moving Average' string MA11 = 'HMA - Hull Moving Average' string MA12 = 'JMA - Jurik Moving Average' string MA13 = 'KAMA - Kaufman\'s Adaptive Moving Average' string MA14 = 'Kijun v2' string MA15 = 'LSMA/LRC - Least Squares Moving Average' string MA16 = 'MF - Modular Filter' string MA17 = 'RMA - RSI Moving average' string MA18 = 'SMA - Simple Moving Average' string MA19 = 'SMMA - Smoothed Moving Average' string MA20 = 'STMA - Simple Triangular Moving Average' string MA21 = 'TEMA - Triple Exponential Moving Average' string MA22 = 'THMA - Triple Hull Moving Average' string MA23 = 'VAMA - Volatility Adjusted Moving Average' string MA24 = 'VIDYA - Variable Index Dynamic Average' string MA25 = 'VWMA - Volume Weighted Moving Average' string MA26 = 'WMA - Weighted Moving Average' string MA27 = 'ZEMA - Zero-Lag Exponential Moving Average' string MA28 = 'ZSMA - Zero-Lag Simple Moving Average' string MA29 = 'EVWMA - Elastic Volume Weighted Moving Average' string MA30 = 'Tillson T3' string MA31 = 'GMA - Geometric Moving Average' string MA32 = 'WWMA - Welles Wilder Moving Average' string MA33 = 'AMA - Adjusted Moving Average' string MA34 = 'CMA - Corrective Moving Average' string MA35 = 'GMMA - Geometric Mean Moving Average' string MA36 = 'EALF - Ehler\'s Adaptive Laguerre filter' string MA37 = 'ELF - Ehler\'s Laguerre Filter' string MA38 = 'PNR - Percentile Nearest Rank' string MA39 = 'PLI - Percentile Linear Interpolation' string MA40 = 'REMA - Range EMA' string MA41 = 'SWMA - Sine-Weighted Moving Average' string MA42 = 'VWAP - Volume Weighted Average Price' string MA43 = 'MAMA - MESA Adaptive Moving Average' string MA44 = 'FAMA - Following Adaptive Moving Average' string MA45 = 'HKAMA - Hilbert based Kaufman\'s Adaptive Moving Average' string MA46 = 'EDMA - MZ Exponentially Deviating Moving Average' ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Slow MA Parameters src = input.source(hlc3, 'Source') grp1 = 'Slow MA Parameters' grp2 = 'Fast MA Parameters' slowMAtype = input.string(title='Slow MA Type', group=grp1, defval=MA05, options=['Source', MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08, MA09, MA10, MA11, MA12, MA13, MA14, MA15, MA16, MA17, MA18, MA19, MA20, MA21, MA22, MA23, MA24, MA25, MA26, MA27, MA28, MA29, MA30, MA31, MA32, MA33, MA34, MA35, MA36, MA37, MA38, MA39, MA40, MA41, MA42, MA43, MA44, MA45, MA46]) slowMAlen = input.int(100, title='Slow MA Length:', group=grp1) fastMAtype = input.string(title='Fast MA Type', group=grp2, defval=MA11, options=['Source', MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08, MA09, MA10, MA11, MA12, MA13, MA14, MA15, MA16, MA17, MA18, MA19, MA20, MA21, MA22, MA23, MA24, MA25, MA26, MA27, MA28, MA29, MA30, MA31, MA32, MA33, MA34, MA35, MA36, MA37, MA38, MA39, MA40, MA41, MA42, MA43, MA44, MA45, MA46]) fastMAlen = input.int(50, title='Fast MA Length:', group=grp2) ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///// MA Functions' Additional Inputs ////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Pre-reqs // // Kijun V2 kidiv = input.int(defval=1, maxval=4, title='Kijun MOD Divider') // JMA jurik_phase = input(title='* Jurik (JMA) Only - Phase', defval=3) jurik_power = input(title='* Jurik (JMA) Only - Power', defval=1) // VAMA volatility_lookback = input(10, title='* Volatility Adjusted (VAMA) Only - Volatility lookback length') // MF beta = input.float(0.8, minval=0, maxval=1, step=0.1, title='Modular Filter, General Filter Only - Beta') feedback = input(false, title='Modular Filter Only - Feedback') z = input.float(0.5, title='Modular Filter Only - Feedback Weighting', step=0.1, minval=0, maxval=1) // EDSMA ssfLength = input.int(title='EDSMA - Super Smoother Filter Length', minval=1, defval=20) ssfPoles = input.int(title='EDSMA - Super Smoother Filter Poles', defval=2, options=[2, 3]) // KAMA k_fastLength = input.float(2.0, 'Number of periods for the fastest exponential moving average', minval=1) k_slowLength = input.float(30.0, 'Number of periods for the slowest exponential moving average', minval=1) // ─── Ehlrs Modified Fractal Adaptive Moving Average (EFRAMA) FC = input.int(defval=1, title='Lower Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average', minval=1) SC = input.int(defval=200, title='Upper Shift Limit for Ehlrs Modified Fractal Adaptive Moving Average', minval=1) // ─── Arnaud Legoux Moving Average (ALMA) a_offset = input.float(0.85, 'Arnaud Legoux offset', minval=0.01, step=0.05) a_sigma = input.float(6.0, 'Arnaud Legoux sigma', minval=1, step=0.1) // Tillson T3 a1_t3 = input.float(title='Tillson T3 Volume Factor', defval=0.7, inline='5', step=0.001) // AMA ama_f_length = input(title='Fast Length (Adjusted Moving Average)', defval=14) ama_s_length = input(title='Slow Length (Adjusted Moving Average)', defval=100) // EALF Ehler's Adaptive Laguerre filter LAPercLen_ = input(title='Median Length (Ehler\'s Adaptive Laguerre filter)', defval=5) FPerc_ = input(title='Median Percentage (Ehler\'s Adaptive Laguerre filter)', defval=50) // PNR & PLI rank_inter_Perc_ = input(title='Rank and Interpolation Percentage (PNR & PLI)', defval=50) ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///// Selections & Calculations ////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // MA Selection and Output function ma(type, src, len) => var float result = 0.0 // initiating if type == MA01 result := alma(src, len, a_offset, a_sigma) if type == MA02 result := covwema(src, len) if type == MA03 result := covwma(src, len) if type == MA04 result := dema(src, len) if type == MA05 result := edsma(src, len, ssfLength, ssfPoles) if type == MA06 result := eframa(src, len, FC, SC) if type == MA07 result := ehma(src, len) if type == MA08 result := ema(src, len) if type == MA09 result := etma(src, len) if type == MA10 result := frama(src, len) if type == MA11 result := hma(src, len) if type == MA12 result := jma(src, len, jurik_phase, jurik_power) if type == MA13 result := kama(src, len, k_fastLength, k_slowLength) if type == MA14 result := kijun(high, low, len, kidiv) if type == MA15 result := lsma(src, len, 0) if type == MA16 result := mf(src, len, beta, feedback, z) if type == MA17 result := rma(src, len) if type == MA18 result := sma(src, len) if type == MA19 result := smma(src, len) if type == MA20 result := stma(src, len) if type == MA21 result := tema(src, len) if type == MA22 result := thma(src, len) if type == MA23 result := vama(src, len, volatility_lookback) if type == MA24 result := vidya(src, len) if type == MA25 result := vwma(src, len) if type == MA26 result := wma(src, len) if type == MA27 result := zema(src, len) if type == MA28 result := zsma(src, len) if type == MA29 result := evwma(src, len) if type == MA30 result := tt3(src, len, a1_t3) if type == MA31 result := gma(src, len) if type == MA32 result := wwma(src, len) if type == MA33 result := ama(src, high, low, len, ama_f_length, ama_s_length) if type == MA34 result := cma(src, len) if type == MA35 result := gmma(src, len) if type == MA36 result := ealf(src, len, LAPercLen_, FPerc_) if type == MA37 result := elf(src, len) if type == MA38 result := pnr(src, len, rank_inter_Perc_) if type == MA39 result := pli(src, len, rank_inter_Perc_) if type == MA40 result := rema(src, len) if type == MA41 result := sw_ma(src, len) if type == MA42 result := vwap(src) if type == MA43 result := mama(src, len) if type == MA44 result := fama(src, len) if type == MA45 result := hkama(src, len) if type == MA46 result := edma(src, len) result ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// slowMA = ma(slowMAtype, src, slowMAlen) fastMA = ma(fastMAtype, src, fastMAlen) //Plot plot(slowMA, 'Slow MA', color.blue, 4) plot(fastMA, 'Fast MA', color.green, 2)
"Swap" - Bool/Position/Value : Array / Matrix / Var Autoswap
https://www.tradingview.com/script/k7STBLpA-Swap-Bool-Position-Value-Array-Matrix-Var-Autoswap/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
13
library
5
MPL-2.0
//This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //©kaigouthro //@version=5 // @description # Side / Boundary Based All Types Swapper // - three automagic types for Arrays, Matrixes, and Variables // - no signal : Long/ Short positon autoswap // - true / false : Boolean based side choice // - Src / Thresh : if source is above or below the threshhold // - two operatng modes for variables, Holding mode only for arrays/matrixes // - with two items, will automatically change btween the two caveat is it does not delete table/box/line(fill VAR items automatically) // - with three items, a neutral is available for NA input or neutral // - one function name for all of them. One import name that's easy to type/remember // - make life easy for your conditionala. library("swap",true) // @function src helper function for side // @param source value input // @param thresh boundary line to cross // @param _a value 1 // @param _b value 2 // @param _c value 3 _side (src, thresh,_a,_b,_c) => var value = src var border = thresh value := src border := thresh switch value > thresh => _a value < thresh => _b => _c // @function src helper function for side boolean // @param _isTrue value input // @param _a value 1 // @param _b value 2 // @param _c value 3 _sidebool (_isTrue,_a,_b,_c) => switch _isTrue true => _a false => _b => _c // @function src helper function for overloads // @param _a if Long position Item // @param _b if Short position Item // @param _c if neutral position Item _positionSwapper (_a,_b,_c) => _side (strategy.position_size,0,_a,_b,_c) // @function side Change outputs based on position or a crrossing level // // - three automagic types for Arrays, Matrixes, and Variables // - no signal : Long/ Short positon autoswap // - true / false : Boolean based side choice // - Src / Thresh : if source is above or below the threshhold // - two operatng modes for variables, Holding mode only for arrays/matrixes // - with two items, will automatically change btween the two caveat is it does not delete table/box/line(fill VAR items automatically) // - with three items, a neutral is available for NA input or neutral // - one function name for all of them. One import name that's easy to type/remember // - make life easy for your conditionala. // // # simple local methods to add: // import kaigouthro/swap/1 // > this will allow local use easy // ``` // method swwap(float s, float t, a,b,c) => swap.side(s,t,a,b,c) // // // var _held = "your value" // // example_held = _src.swap(_threshold, item1,item2,_held) // method swwap(bool t, a,b,c p) => swap.side(t,a,b,c) // // // var _held = "your value" // // example_held = _bool_var.swap(item1,item2,_held) // // ``` // @param source (float) OPTIONAL value input // @param thresh (float) OPTIONAL boundary line to cross // @param _a (any) if Long/True/Above // @param _b (any) if Short/False/Below // @param _c (any) OPTIONAL Neutral Item, if var/varip on a/b it will leave behind, ie, a table or box or line will not erase , if it's a varip you're sending in. // @returns first, second, or third items based on input conditions export side ( bool _a , bool _b, bool _c = na) => _d = bool (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == bool (na) ? out : _d) export side ( box _a , box _b, box _c = na) => _d = box (_c), out = _positionSwapper ( _a, _b, _d ) export side ( color _a , color _b, color _c = na) => _d = color (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == color (na) ? out : _d) export side ( float _a , float _b, float _c = na) => _d = float (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == float (na) ? out : _d) export side ( int _a , int _b, int _c = na) => _d = int (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == int (na) ? out : _d) export side ( label _a , label _b, label _c = na) => _d = label (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == label (na) ? out : _d) export side ( line _a , line _b, line _c = na) => _d = line (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == line (na) ? out : _d) export side ( linefill _a , linefill _b, linefill _c = na) => _d = linefill (_c), out = _positionSwapper ( _a, _b, _d ) export side ( string _a , string _b, string _c = na) => _d = string (_c), var out = _d, out := _positionSwapper ( _a, _b, _d == string (na) ? out : _d) export side ( table _a , table _b, table _c = na) => _d = table (_c), out = _positionSwapper ( _a, _b, _d ) export side ( float src, float thresh, bool _a , bool _b, bool _c = na) => _d = bool (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == bool (na) ? out : _d) export side ( float src, float thresh, box _a , box _b, box _c = na) => _d = box (_c), out = _side (src , thresh , _a, _b, _d ) export side ( float src, float thresh, color _a , color _b, color _c = na) => _d = color (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == color (na) ? out : _d) export side ( float src, float thresh, float _a , float _b, float _c = na) => _d = float (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == float (na) ? out : _d) export side ( float src, float thresh, int _a , int _b, int _c = na) => _d = int (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == int (na) ? out : _d) export side ( float src, float thresh, label _a , label _b, label _c = na) => _d = label (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == label (na) ? out : _d) export side ( float src, float thresh, line _a , line _b, line _c = na) => _d = line (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == line (na) ? out : _d) export side ( float src, float thresh, linefill _a , linefill _b, linefill _c = na) => _d = linefill (_c), out = _side (src , thresh , _a, _b, _d ) export side ( float src, float thresh, string _a , string _b, string _c = na) => _d = string (_c), var out = _d, out := _side (src , thresh , _a, _b, _d == string (na) ? out : _d) export side ( float src, float thresh, table _a , table _b, table _c = na) => _d = table (_c), out = _side (src , thresh , _a, _b, _d ) export side ( bool _istrue , bool _a , bool _b, bool _c = na) => _d = bool (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == bool (na) ? out : _d) export side ( bool _istrue , box _a , box _b, box _c = na) => _d = box (_c), out = _sidebool (_istrue , _a, _b, _d ) export side ( bool _istrue , color _a , color _b, color _c = na) => _d = color (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == color (na) ? out : _d) export side ( bool _istrue , float _a , float _b, float _c = na) => _d = float (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == float (na) ? out : _d) export side ( bool _istrue , int _a , int _b, int _c = na) => _d = int (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == int (na) ? out : _d) export side ( bool _istrue , label _a , label _b, label _c = na) => _d = label (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == label (na) ? out : _d) export side ( bool _istrue , line _a , line _b, line _c = na) => _d = line (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == line (na) ? out : _d) export side ( bool _istrue , linefill _a , linefill _b, linefill _c = na) => _d = linefill (_c), out = _sidebool (_istrue , _a, _b, _d ) export side ( bool _istrue , string _a , string _b, string _c = na) => _d = string (_c), var out = _d, out := _sidebool (_istrue , _a, _b, _d == string (na) ? out : _d) export side ( bool _istrue , table _a , table _b, table _c = na) => _d = table (_c), out = _sidebool (_istrue , _a, _b, _d ) export side ( bool[] _a , bool[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( box[] _a , box[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( color[] _a , color[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( float[] _a , float[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( int[] _a , int[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( label[] _a , label[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( line[] _a , line[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( linefill[] _a , linefill[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( string[] _a , string[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( table[] _a , table[] _b ) => var out = _b, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( float src, float thresh, bool[] _a , bool[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, box[] _a , box[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, color[] _a , color[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, float[] _a , float[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, int[] _a , int[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, label[] _a , label[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, line[] _a , line[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, linefill[] _a , linefill[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, string[] _a , string[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, table[] _a , table[] _b ) => var out = _b, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( bool _istrue , bool[] _a , bool[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , box[] _a , box[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , color[] _a , color[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , float[] _a , float[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , int[] _a , int[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , label[] _a , label[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , line[] _a , line[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , linefill[] _a , linefill[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , string[] _a , string[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , table[] _a , table[] _b ) => var out = _b, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( matrix<bool> _a , matrix<bool> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<box> _a , matrix<box> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<color> _a , matrix<color> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<float> _a , matrix<float> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<int> _a , matrix<int> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<label> _a , matrix<label> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<line> _a , matrix<line> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<linefill> _a , matrix<linefill> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<string> _a , matrix<string> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( matrix<table> _a , matrix<table> _b ) => var out = _a, _c = out[1], out := _positionSwapper ( _a, _b, _c) export side ( bool _istrue , matrix<bool> _a , matrix<bool> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<box> _a , matrix<box> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<color> _a , matrix<color> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<float> _a , matrix<float> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<int> _a , matrix<int> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<label> _a , matrix<label> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<line> _a , matrix<line> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<linefill> _a , matrix<linefill> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<string> _a , matrix<string> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( bool _istrue , matrix<table> _a , matrix<table> _b ) => var out = _a, _c = out[1], out := _sidebool (_istrue , _a, _b, _c) export side ( float src, float thresh, matrix<bool> _a , matrix<bool> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<box> _a , matrix<box> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<color> _a , matrix<color> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<float> _a , matrix<float> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<int> _a , matrix<int> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<label> _a , matrix<label> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<line> _a , matrix<line> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<linefill> _a , matrix<linefill> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<string> _a , matrix<string> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) export side ( float src, float thresh, matrix<table> _a , matrix<table> _b ) => var out = _a, _c = out[1], out := _side (src , thresh , _a, _b, _c) // demo testtbl (table _tb, int _num, _string, _value , _col) => // { _cellvalue = str.tostring(_value) table.cell(_tb, 0, _num, _string , 0, 0, color.new(_col, 30),'left' , 'bottom' , size.normal ) table.cell(_tb, 1, _num, _cellvalue , 0, 0, color.new(_col, 30),'right', 'bottom' , size.normal ) testln (int dist = 20, string xloc=xloc.bar_index, string extend=extend.none, color color=#33aaff, string style=line.style_solid, int width=1) => //{ ln = line(na) line.delete(ln[1]) ln := line.new(last_bar_index, close, last_bar_index - dist, close[dist], xloc=xloc, extend=extend, color=color, style=style, width=width) testlnf (line l1,line l2) => //{ var ln = linefill(na) linefill.delete(ln) ln := linefill.new(l1,l2,color.new(color.orange,80)) testlbl (float _y=high, string _text="Your text here", int _x=bar_index, color _color=color.white) => var ln = label(na) label.delete(ln[1]) ln := label.new(_x,_y,_text,xloc.bar_index, yloc.price, _color, label.style_label_down, color.black, size.large) dist = input(3) var color _demo_colora = na var color _demo_colorb = na var color _demo_colorc = na var color _demo_colord = na var color _demo_colore = na varip bool _demo_bool = na varip int _demo_int = na varip float _demo_float = na varip string _demo_string = na varip string _desca = 'Is This Below ? ' varip string _descb = 'Lower value Bar Index ' varip string _descc = 'Lower item Value ' varip string _descd = 'further item is ' varip string _desce = 'Linefill is on ' _stringsa = array.from('Array 1 - a' ,'Array 1 - b' ,'Array 1 - c' ,'Array 1 - d' ,'Array 1 - e' ) _stringsb = array.from('Array 2 - e' ,'Array 2 - d' ,'Array 2 - c' ,'Array 2 - b' ,'Array 2 - a' ) stringarr = side(dayofmonth>15,_stringsa,_stringsb) _demo_colora := side (close[2*dist] , close , color.green , color.orange , color.gray ) _demo_colorb := side (close[3*dist] , close , color.green , color.orange , color.gray ) _demo_colorc := side (close[4*dist] , close , color.green , color.orange , color.gray ) _demo_colord := side (close[5*dist] , close , color.green , color.orange , color.gray ) _demo_colore := side (close[ dist] , close , color.yellow , color.fuchsia , color.gray ) _demo_bool := side (close , close [2*dist] , true , false , na ) _demo_int := side (close , close [3*dist] , bar_index[3*dist] , last_bar_index , 0 ) _demo_float := side (close , close [4*dist] , close [4*dist] , close , _demo_float[1] ) _demo_string := side (close , close [5*dist] , 'Below Close' , 'Above Close ' , 'Equal' ) ln1 = testln(2*dist) ln2 = testln(3*dist) ln3 = testln(4*dist) ln4 = testln(5*dist) line1 = side(_demo_bool,ln1,ln3) line2 = side(_demo_bool,ln2,ln4) testlnf(line1,line2) _stringlinechoise = side(_demo_bool, 'ln1,ln3', 'ln2,ln4') testlbl(close[2*dist] , _desca + str.tostring(_demo_bool ), bar_index - 2*dist , _demo_colora) testlbl(close[3*dist] , _descb + str.tostring(_demo_int ), bar_index - 3*dist , _demo_colorb) testlbl(close[4*dist] , _descc + str.tostring(_demo_float ), bar_index - 4*dist , _demo_colorc) testlbl(close[5*dist] , _descd + str.tostring(_demo_string ), bar_index - 5*dist , _demo_colord) testlbl(close , _desce + str.tostring(_stringlinechoise ), bar_index , _demo_colore) table _tba = table.new('bottom_left' , 20, 20, color.new(#333333, 80), na, 1, na) table _tbb = table.new('bottom_right' , 20, 20, color.new(#333333, 80), na, 1, na) table _tbc = table.new('bottom_center', 20, 20, color.new(#333333, 80), na, 1, na) _tabis = table(na) _tabis := side(close>open and input(true,'table swap'), _tba,_tbb, na) _htest = side(barstate.isfirst?open:close,close,'| Two options, holding first', '| ERROR if this showed', input(true,'Test holding last value')? na : '| Three options, Showing Third') testtbl(_tbc , 0, close>open ? " <<<<< Table should be" : "Table should be >>>>>>" , _htest , color.white) testtbl(_tabis, 1, _desca , _demo_bool , _demo_colora) testtbl(_tabis, 2, _descb , _demo_int , _demo_colorb) testtbl(_tabis, 3, _descc , _demo_float , _demo_colorc) testtbl(_tabis, 4, _descd , _demo_string , _demo_colord) testtbl(_tabis, 5, _desce , _stringlinechoise , _demo_colore) for i = 0 to array.size(stringarr)-1 testtbl(_tabis, i + 6, array.get(stringarr,i) , 'upside down or right side up for swap' , color.yellow)
CalculatePercentageSlTp
https://www.tradingview.com/script/AlbHS5w7-CalculatePercentageSlTp/
massiveMoth88776
https://www.tradingview.com/u/massiveMoth88776/
1
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © massiveMoth88776 //@version=5 // @description This Library calculate the sl and tp amount in percentage library("CalculatePercentageSlTp", true) // @function this function calculates the sl value in percentage // @param entry_price indicates the entry level // @param sl_price indicates the stop loss level // @returns stop loss in percentage export sl_percentage(float entry_price, float sl_price) => sl_percentage = math.abs((entry_price / sl_price) - 1)*100 sl_percentage // @function this function calculates the tp value in percentage // @param entry_price indicates the entry level // @param tp_price indicates the take profit level // @returns take profit in percentage export tp_percentage(float entry_price, float tp_price) => tp_percentage = math.abs((entry_price / tp_price) - 1)*100 tp_percentage // @function this function calculates the sl level price // @param entry_price indicates the entry level // @param sl_percentage indicates the stop loss percentage // @returns stop loss price in $ export sl_level(float entry_price, float sl_percentage) => sl_value = entry_price * (1 - (sl_percentage/100)) sl_value // @function this function calculates the tp level price // @param entry_price indicates the entry level // @param tp_percentage indicates the take profit percentage // @returns take profit price in $ export tp_level(float entry_price, float tp_percentage) => tp_value = entry_price * (1 + (tp_percentage/100)) tp_value
RouterOrdersIron
https://www.tradingview.com/script/bgkkOUfX-RouterOrdersIron/
HPotter
https://www.tradingview.com/u/HPotter/
36
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HPotter //@version=5 doAlert(uid, sym, side, bal, price, type, take_percent, stop_percent)=> id = timenow alert("{\"userid\": \""+uid+"\", \"symbol\": \""+sym+"\",\"price\": "+str.tostring(price)+",\"take\": "+str.tostring(take_percent)+",\"stop\": "+str.tostring(stop_percent)+", \"side\": \""+side+"\",\"balance\":"+str.tostring(bal)+",\"order_type\": \""+type+"\", \"id\": "+str.tostring(id)+"}") doMessage(uid, sym, side, bal, price, type, take_percent, stop_percent)=> id = timenow m = "{\"userid\": \""+uid+"\", \"symbol\": \""+sym+"\",\"price\": "+str.tostring(price)+",\"take\": "+str.tostring(take_percent)+",\"stop\": "+str.tostring(stop_percent)+", \"side\": \""+side+"\",\"balance\":"+str.tostring(bal)+",\"order_type\": \""+type+"\", \"id\": "+str.tostring(id)+"}" m // @description Library for routing orders to the Binance exchange. Routing is carried out by the Iron program that you can run on your VPS server. More: t.me/hpottersoft library("RouterOrdersIron") // @function Returns json for Iron to buy a symbol for the amount of the balance with market order. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @param balance The amount for which to carry out the transaction. // @returns json string export MsgDoLongMKT(string id, string symbol, float balance, float take_percent, float stop_percent) => doMessage(id, symbol, "long", balance, 1000, "market", take_percent, stop_percent) // @function Returns json for Iron to sell a symbol for the amount of the balance with market order. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns json string export MsgDoShortMKT(string id,string symbol, float balance, float take_percent, float stop_percent) => doMessage(id, symbol, "short", balance, 1000, "market", take_percent, stop_percent) // @function Returns json for Iron to buy a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns json string export MsgDoLongLR(string id, string symbol,float price, float balance, float take_percent, float stop_percent) => doMessage(id, symbol, "long",balance, price, "limit_refresh", take_percent, stop_percent) // @function Returns json for Iron to sell a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns json string export MsgDoShortLR(string id,string symbol,float price, float balance, float take_percent, float stop_percent) => doMessage(id, symbol, "short", balance, price, "limit_refresh", take_percent, stop_percent) // @function Buy a symbol for the amount of the balance. It is send market order to Iron. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns true export DoLongMKT(string id,string symbol, float balance, float take_percent, float stop_percent) => doAlert(id,symbol, "long", balance, 1000, "market", take_percent, stop_percent) true // @function Sell a symbol for the amount of the balance. It is send market order to Iron. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns true export DoShortMKT(string id,string symbol, float balance, float take_percent, float stop_percent) => doAlert(id, symbol, "short", balance, 1000, "market", take_percent, stop_percent) true // @function Buy a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns true export DoLongLR(string id,string symbol,float price, float balance, float take_percent, float stop_percent) => doAlert(id, symbol, "long", balance, price, "limit_refresh", take_percent, stop_percent) true // @function Sell a symbol for the amount of the balance. It is set at the best price and is re-set each time if a new price has risen before the application. // @param id ID of your Iron router. // @param symbol Symbol for a trade, BTC example // @param balance The amount for which to carry out the transaction. // @param take The percent take profit value from entry price. // @param stop The percent stop loss value from entry price. // @returns true export DoShortLR(string id,string symbol,float price, float balance, float take_percent, float stop_percent) => doAlert(id,symbol, "short", balance, price, "limit_refresh", take_percent, stop_percent) true // @function Get Qty for strategy on balance // @param price Order price // @param balance The amount for which to carry out the transaction. // @returns Qty for strategy order TV export GetQty(float price, float balance) => balance / price
getSeries
https://www.tradingview.com/script/Bn7QkdZR-getSeries/
PineCoders
https://www.tradingview.com/u/PineCoders/
95
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © PineCoders //@version=5 // @description This library is a Pine programmer’s tool containing functions that build an array of values meeting specific conditions. library("getSeries", true) // getSeries Library // v1, 2022.06.23 // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html // Import the library containing the `allTimeHigh()` function we use in example #8. import TradingView/ta/2 as TVta // Import the library containing the `formattedDay()` function we use in example #5. import PineCoders/Time/3 as PCtime // ———————————————————— Library functions { // @function Creates an array containing the `length` last `src` values where `whenCond` is true, since the last occurence of `sinceCond`. // @param src (series int/float) The source of the values to be included. // @param whenCond (series bool) The condition determining which values are included. Optional. The default is `true`. // @param sinceCond (series bool) The condition determining when the accumulated series resets. Optional. The default is false, which will not reset. // @param length (simple int) The number of last values to return. Optional. The default is all values. // @returns (float[]) The array ID of the accumulated `src` values. export whenSince(series float src, series bool whenCond = true, series bool sinceCond = false, simple int length = na) => var float[] values = array.new_float(0) int cappedLen = math.max(1, length) if sinceCond array.clear(values) if whenCond array.push(values, src) if not na(cappedLen) and array.size(values) > cappedLen array.shift(values) float[] result = values // @function Creates an array of `src` values where `cond` is true, over a moving window of length `timeWindow` milliseconds. // @param src (series int/float) The source of the values to be included. // @param timeWindow (simple int) The time duration in milliseconds defining the size of the moving window. // @param cond (series bool) The condition determining which values are included. Optional. The default is `true`. // @param minBars (simple int) The minimum number of values to maintain in the moving window. Optional. The default is 1. // @returns (float[]) The array ID of the accumulated `src` values. export rollOnTimeWhen(series float src, simple int timeWindow, series bool cond = true, simple int minBars = 1) => var float[] sources = array.new_float(0) var int[] times = array.new_int(0) if cond array.push(sources, src) array.push(times, time) if array.size(sources) > 0 while time - array.get(times, 0) >= timeWindow and array.size(sources) > minBars array.shift(sources) array.shift(times) float[] result = sources // } // ———————————————————— Example Code { int MS_IN_1M = 1000 * 60 * 60 * 24 * 30 // ————— 1. Get the sum of pre-market volume for the day. float volPreMarket = nz(array.sum(whenSince(volume, session.ispremarket, timeframe.change("D")))) plotchar(volPreMarket, "1. Total Pre-market Vol.", "", location.top, color.orange, size = size.tiny) // ————— 2. Find the two highest volumes values in the last 30 days. // Create an array from the volume values for the 30-day rolling window. float[] volumes30days = rollOnTimeWhen(volume, MS_IN_1M) // Get the highest. float highestVol = array.max(volumes30days) plotchar(highestVol, "2. 30 Day Highest Vol.", "", location.top, color.aqua, size = size.tiny) // When the array has at least two values, use the `nth` optional parameter of `array.max()` to get the second highest value. float secondHighestVol = array.size(volumes30days) > 1 ? array.max(volumes30days, 1) : na plotchar(secondHighestVol, "2. 30 Day 2nd Highest Vol.", "", location.top, color.aqua, size = size.tiny) // ————— 3. Get the average of the pivot highs of the last 30-day rolling window. int PIVOT_LEGS = 5 // Calculate pivot highs. float pivHi = ta.pivothigh(high, PIVOT_LEGS, PIVOT_LEGS) // Create an array from the volume values for the 30-day rolling window. float[] hiPivotsInLastMonth = rollOnTimeWhen(pivHi, MS_IN_1M, not na(pivHi)) // Calculate its average value. float avgHiPivots = array.avg(hiPivotsInLastMonth) plot(avgHiPivots, "3. avgHiPivots") plotchar(pivHi, "3. pivHi", "•", location.absolute, size = size.tiny) // ————— 4. Average volume of low pivots for the whole chart. float avgVolOfLowPivots = array.avg(whenSince(volume[PIVOT_LEGS], ta.pivotlow(low, PIVOT_LEGS, PIVOT_LEGS))) plotchar(avgVolOfLowPivots, "4. Avg. Vol. of Pivot Lows", "", location.top, color.maroon, size = size.tiny) // ————— 5. Find the time of the last 4 golden crosses. // Calculate MA's and create cross condition. float ma50 = ta.sma(close, 50) float ma200 = ta.sma(close, 200) bool goldenCross = ta.cross(ma50, ma200) // Plot the MA's. Create unique color at the cross point. plot(ma50, "5. 50 MA", goldenCross or goldenCross[1] ? #f3ff00 : color.new(color.gray, 50)) plot(ma200, "5. 200 MA", goldenCross or goldenCross[1] ? #f3ff00 : color.new(color.gray, 50)) // Highlight cross area. if goldenCross label.new(time, (ma50 + ma200) / 2, xloc = xloc.bar_time, color = color.new(#ff0000, 65), style = label.style_circle, size = size.tiny) // Get an array containing the last 4 golden cross times. float[] goldenCrossesTimes = whenSince(time_close, goldenCross, length = 4) // Display the date and time of the last crosses (executes only once on the last historical bar). if barstate.islastconfirmedhistory // Declare empty table var table t = table.new(position.top_right, 2, 6, color.new(color.black, 100), color.gray, 1, color.gray, 1) // Create title for table and merge cells. table.cell(t, 0, 0, "5. Golden Cross Times", text_color = color.black, bgcolor = #FFD700) table.merge_cells(t, 0, 0, 1, 0) // Loop array writing cells containing the cross time for each element. Number each element in the left row. for [i, timeValue] in goldenCrossesTimes table.cell(t, 0, i + 1, str.tostring(i + 1), text_color = #FFD700) table.cell(t, 1, i + 1, PCtime.formattedDay(timeValue, "yyyy.MM.dd 'at' HH:mm:ss z"), text_color = color.gray) // ————— 6. Get average closes in a specific session. string sessionInput = input.session("0900-1000") bool inSession = not na(time("D", sessionInput)) float sessionAvgClose = array.avg(whenSince(close, inSession, timeframe.change("D"))) plot(sessionAvgClose, "6. Avg. Close Within Session", color.olive, 2, style = plot.style_linebr) // ————— 7. Create a Session VWAP anchored to market open. float vwap = array.sum(whenSince(close * volume, session.ismarket, session.isfirstbar_regular)) / array.sum(whenSince(volume, session.ismarket, session.isfirstbar_regular)) plot(session.ismarket ? vwap : na, "7. Session VWAP", color.purple, style = plot.style_linebr) // ————— 8. Get the bar indices where RSI makes a new all-time high. float myRsi = ta.rsi(close, 20) float[] barIndicesOfHiRSIs = whenSince(bar_index, myRsi == TVta.allTimeHigh(myRsi)) if barstate.islastconfirmedhistory var table t = table.new(position.bottom_left, 1, 1, color.new(color.black, 100), color.gray, 1, color.gray, 1) table.cell(t, 0, 0, "8. Bar indices of RSI ATHs\n" + str.tostring(barIndicesOfHiRSIs)) // }
[LIB] Array / Matrix Display
https://www.tradingview.com/script/L94FmzSI-LIB-Array-Matrix-Display/
kurtsmock
https://www.tradingview.com/u/kurtsmock/
26
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © kurtsmock //@version=5 // @description Show Array or Matrix Elements In Table library("ArrayMatrixHUD") // [-- PINESCRIPT DEBUGGER --] { // -- Example Define Matrix rows = 30 cols = 9 varip console = matrix.new<string>(rows,cols,'') // @function Debug Variables in Matrix // @param _col (int) Assign Column // @param _row (int) Assign Row // @param _name (simple matrix) Matrix Name // @param _value (string) Assign variable as a string (str.tostring()) // @param _lb (string) Constant label (optional) // @param _ip (int) (default 1) 1 for continuous updates. 2 for barstate.isnew updates. 3 for barstate.isconfirmed updates. -1 to only add once // @returns Returns Variable _value output and _msg formatted as '_msg: variableOutput' in designated column and row export debug(int _col, int _row, simple matrix<string> _name, string _value, string _msg='', int _ip=1) => ipOn = _ip == 1 ? true : false bsnOn = _ip == 2 ? true : false bscOn = _ip == 3 ? true : false if matrix.get(_name, _row, _col) == '' matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value)) if ipOn matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value)) if bsnOn if barstate.isnew matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value)) if bscOn if barstate.isconfirmed matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value)) // @function Debug Scope in Matrix - Identify When Scope Is Accessed // @param _col (int) Column Number // @param _row (int) Row Number // @param _name (simple matrix) Matrix Name // @param _msg (string) Message // @returns Message appears in debug panel using _col/_row as the identifier export debugs(int _col, int _row, simple matrix<string> _name, string _msg='') => matrix.set(_name, _row, _col, "debugs(" + str.tostring(_col) + "," + str.tostring(_row) + "): Fired" + _msg) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DEBUG NOTE: // Anywhere you want to test the value of a variable, add a debug() function. Debug functions can be stacked together at the end of the script // However, if you want to clearly see how variables are updated during intrabar calculations, you will need to place the debug function immediately // below the variable you want to display and see real time updates // debug(0,0,rows,"Total Rows") // DebugScope is used to show when a scope is accessed. Thus debugs() must be placed inside the scope being analyzed. // if close>open // debugs(0,1,"Close>Open") // CAUTION: Value's will be overwritten if two debug/debugs functions share the same column and row. This can be a desired effect or undesired. // Keep that in mind. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //} // [-- showArray FUNCTIONS --] { // @function Array Element Display (Supports float[], int[], string[], and bool[]) // @param _arrayName ID of Array to be Displayed // @param _pos Position for Table // @param _txtSize Size of Table Cell Text // @param _fillCond (Optional) Conditional statement. Function displays array only when true. For instances where indices are na. Default = true, indicating array size is set at bar_index 0. // @param _offset (Optional) Use to view historical array states. Default = 0, displaying realtime bar. // @param _tRows Number of Rows to Display Data In (columns will be calculated accordingly) // @returns A Display of Array Values in a Table export viewArray(float[] _arrayName, string _pos, string _txtSize, int _tRows, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getSize = array.size(_arrayName[_offset]) getCols = math.ceil(getSize / _tRows) viewArray = table.new(_pos, getCols, _tRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = _tRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewArray, column, row, array.size(_arrayName[_offset]) > index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : "-", text_halign=text.align_left, text_size=_txtSize) if index <= array.size(_arrayName[_offset]) - 1 index += 1 if _j < endRow row += 1 row := 0 if _i < endCol column += 1 export viewArray(int[] _arrayName, string _pos, string _txtSize, int _tRows, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getSize = array.size(_arrayName[_offset]) getCols = math.ceil(getSize / _tRows) viewArray = table.new(_pos, getCols, _tRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = _tRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewArray, column, row, array.size(_arrayName[_offset]) > index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : "-", text_halign=text.align_left, text_size=_txtSize) if index <= array.size(_arrayName[_offset]) - 1 index += 1 if _j < endRow row += 1 row := 0 if _i < endCol column += 1 export viewArray(string[] _arrayName, string _pos, string _txtSize, int _tRows, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getSize = array.size(_arrayName[_offset]) getCols = math.ceil(getSize / _tRows) viewArray = table.new(_pos, getCols, _tRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = _tRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewArray, column, row, array.size(_arrayName[_offset]) > index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : "-", text_halign=text.align_left, text_size=_txtSize) if index <= array.size(_arrayName[_offset]) - 1 index += 1 if _j < endRow row += 1 row := 0 if _i < endCol column += 1 export viewArray(bool[] _arrayName, string _pos, string _txtSize, int _tRows, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getSize = array.size(_arrayName[_offset]) getCols = math.ceil(getSize / _tRows) viewArray = table.new(_pos, getCols, _tRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = _tRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewArray, column, row, array.size(_arrayName[_offset]) > index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : "-", text_halign=text.align_left, text_size=_txtSize) if index <= array.size(_arrayName[_offset]) - 1 index += 1 if _j < endRow row += 1 row := 0 if _i < endCol column += 1 // Examples { arraySize = 28 a = array.new_float(arraySize, math.round(hlc3,2)) for l = 0 to arraySize - 1 array.set(a, l, math.round(hlc3[l],2)) viewArray(a, position.top_left, size.normal, 5, _offset = 5) b = array.new_int(arraySize, 0) inc = 0 for l = 0 to arraySize - 1 array.set(b, l, inc) inc += 1 viewArray(b, position.top_right, size.normal, 5, open > close, 5) c = array.new_string(arraySize, "") str = 'a' for l = 0 to arraySize - 1 array.set(c, l, str) str := str + 'a' viewArray(c, position.bottom_left, size.normal, 5, true, 0) //} [/endExample] //} // [-- showMatrix FUNCTIONS --] { // @function Matrix Element Display (Supports <float>, <int>, <string>, and <bool>) // @param _matrixName ID of Matrix to be Displayed // @param _pos Position for Table // @param _txtSize Size of Table Cell Text // @param _fillCond (Optional) Conditional statement. Function displays matrix only when true. For instances where indices are na. Default = true, indicating matrix size is set at bar_index 0. // @param _offset (Optional) Use to view historical matrix states. Default = 0, displaying realtime bar. // @returns A Display of Matrix Values in a Table export viewMatrix(simple matrix<float> _matrixName, string _pos, string _txtSize, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getRows = matrix.rows(_matrixName[_offset]) getCols = matrix.columns(_matrixName[_offset]) viewMatrix = table.new(_pos, getCols, getRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = getRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewMatrix, column, row, str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row, column)), text_halign=text.align_left, text_size=_txtSize) if _j < endRow row += 1 index += 1 row := 0 if _i < endCol column += 1 export viewMatrix(simple matrix<int> _matrixName, string _pos, string _txtSize, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getRows = matrix.rows(_matrixName[_offset]) getCols = matrix.columns(_matrixName[_offset]) viewMatrix = table.new(_pos, getCols, getRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = getRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewMatrix, column, row, str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row, column)), text_halign=text.align_left, text_size=_txtSize) if _j < endRow row += 1 index += 1 row := 0 if _i < endCol column += 1 export viewMatrix(simple matrix<string> _matrixName, string _pos, string _txtSize, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getRows = matrix.rows(_matrixName[_offset]) getCols = matrix.columns(_matrixName[_offset]) viewMatrix = table.new(_pos, getCols, getRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = getRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewMatrix, column, row, str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row, column)), text_halign=text.align_left, text_size=_txtSize) if _j < endRow row += 1 index += 1 row := 0 if _i < endCol column += 1 export viewMatrix(simple matrix<bool> _matrixName, string _pos, string _txtSize, bool _fillCond = true, int _offset = 0) => if _fillCond and bar_index > _offset getRows = matrix.rows(_matrixName[_offset]) getCols = matrix.columns(_matrixName[_offset]) viewMatrix = table.new(_pos, getCols, getRows) row = 0, column = 0, index = 0 endCol = getCols - 1 endRow = getRows - 1 for _i = 0 to endCol for _j = 0 to endRow table.cell(viewMatrix, column, row, str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row, column)), text_halign=text.align_left, text_size=_txtSize) if _j < endRow row += 1 index += 1 row := 0 if _i < endCol column += 1 // -- Examples { d = matrix.new<float>(5, 5, close[1]) viewMatrix(d, position.top_center, size.small) //} //}
ccIndidatorCandles
https://www.tradingview.com/script/n2ldg4jn/
ccTradingCourse
https://www.tradingview.com/u/ccTradingCourse/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © ccTradingCourse //@version=5 library("ccIndidatorCandles") export isCandleBetween(float _price, float _high=high, float _low=low) => _price < _high and _price > _low
pta_plot
https://www.tradingview.com/script/Bcm0mGop-pta-plot/
protradingart
https://www.tradingview.com/u/protradingart/
40
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © protradingart //@version=5 // @description pta_plot: This library will help you to plot different value. I will keep updating with your requirement library("pta_plot", overlay = true) // @function Display array element as a table. // @param array_id Id of your array. // @param border_color Color for border (`color.black` is used if no argument is supplied). // @param position: Position of Table // @returns Display array element in bottom of the pane. export print_array_float(float[] array_id, int position = 22, color border_color=color.black) => tablePosition = switch position 00 => position.top_left 01 => position.top_center 02 => position.top_right 10 => position.middle_left 11 => position.middle_center 12 => position.middle_right 20 => position.bottom_left 21 => position.bottom_center 22 => position.bottom_right size = array.size(array_id) if size > 0 var testTable = table.new(position = tablePosition, columns = size + 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Index") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "Value") for i = 0 to size - 1 table.cell(table_id = testTable, column = i + 2, row = 0, text = str.tostring(i)) table.cell(table_id = testTable, column = i + 2, row = 1, text = str.tostring(array.get(array_id, i))) else var testTable = table.new(position = tablePosition, columns = 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Message") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "No element in your array", text_color=color.red) // @function Display array element as a table. // @param array_id Id of your array. // @param border_color Color for border (`color.black` is used if no argument is supplied). // @param position Position of Table // @returns Display array element in bottom of the pane. export print_array_int(int[] array_id, int position = 22, color border_color=color.black) => tablePosition = switch position 00 => position.top_left 01 => position.top_center 02 => position.top_right 10 => position.middle_left 11 => position.middle_center 12 => position.middle_right 20 => position.bottom_left 21 => position.bottom_center 22 => position.bottom_right size = array.size(array_id) if size > 0 var testTable = table.new(position = tablePosition, columns = size + 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Index") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "Value") for i = 0 to size - 1 table.cell(table_id = testTable, column = i + 2, row = 0, text = str.tostring(i)) table.cell(table_id = testTable, column = i + 2, row = 1, text = str.tostring(array.get(array_id, i))) else var testTable = table.new(position = tablePosition, columns = 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Message") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "No element in your array", text_color=color.red) // @function Display array element as a table. // @param array_id Id of your array. // @param border_color Color for border (`color.black` is used if no argument is supplied). // @param position Position of Table // @returns Display array element in bottom of the pane. export print_array_string(string[] array_id, int position = 22, color border_color=color.black) => tablePosition = switch position 00 => position.top_left 01 => position.top_center 02 => position.top_right 10 => position.middle_left 11 => position.middle_center 12 => position.middle_right 20 => position.bottom_left 21 => position.bottom_center 22 => position.bottom_right size = array.size(array_id) if size > 0 var testTable = table.new(position = tablePosition, columns = size + 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Index") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "Value") for i = 0 to size - 1 table.cell(table_id = testTable, column = i + 2, row = 0, text = str.tostring(i)) table.cell(table_id = testTable, column = i + 2, row = 1, text = str.tostring(array.get(array_id, i))) else var testTable = table.new(position = tablePosition, columns = 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Message") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "No element in your array", text_color=color.red) // @function Display array element as a table. // @param array_id Id of your array. // @param border_color Color for border (`color.black` is used if no argument is supplied). // @param position Position of Table // @returns Display array element in bottom of the pane. export print_array_bool(bool[] array_id, int position = 22, color border_color=color.black) => tablePosition = switch position 00 => position.top_left 01 => position.top_center 02 => position.top_right 10 => position.middle_left 11 => position.middle_center 12 => position.middle_right 20 => position.bottom_left 21 => position.bottom_center 22 => position.bottom_right size = array.size(array_id) if size > 0 var testTable = table.new(position = tablePosition, columns = size + 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Index") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "Value") for i = 0 to size - 1 table.cell(table_id = testTable, column = i + 2, row = 0, text = str.tostring(i)) table.cell(table_id = testTable, column = i + 2, row = 1, text = str.tostring(array.get(array_id, i))) else var testTable = table.new(position = tablePosition, columns = 2, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=border_color) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Size") table.cell(table_id = testTable, column = 1, row = 0, text = "Message") table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(size)) table.cell(table_id = testTable, column = 1, row = 1, text = "No element in your array", text_color=color.red) ///////////////////////// Calculate CPR /////////// // @function Return CPR. // @param High: High Price for any timeframe. // @param Low: Low Price for any timeframe. // @param Close: Close Price for any timeframe. // @returns CPR Value as Tuple [pp, tc, bc, r1, r2, r3, r4, s1, s2, s3, s4]. export calcCPR(float High, float Low, float Close) => pp = (High + Low + Close) / 3 tc = (High + Low) / 2 bc = pp + (pp - tc) r1 = 2 * pp - Low r2 = pp + (High - Low) r3 = High + 2 * (pp - Low) r4 = High + 3 * (pp - Low) s1 = 2 * pp - High s2 = pp - (High - Low) s3 = Low - 2 * (High - pp) s4 = Low - 3 * (High - pp) [pp, tc, bc, r1, r2, r3, r4, s1, s2, s3, s4] ///////////////////////// Plot Line and Label Function /////////// // @description Plots a horizontal line and label at a specified price level on the chart. // @param Price: The Y value for the line and label. // @param Text: The text to display alongside the label. // @param barCount: Number of candle in a session. // @param Color: The color for the line and label text. // @param Width: The width of the line (default is 1). // @param LineStyle: The style of the line (default is solid). // @param Historical: If set to true, the line and label will appear on historical chart data (default is false). // @returns Nothing. Displays a horizontal line and label on the chart. export dll(float Price, string Text, int barCount, color Color, int Width=1, string LineStyle=line.style_solid, bool Historical=false) => // Create a label with specified text at the given price level LABEL = label.new(x=bar_index + barCount, y=Price, text=Text + " : " + str.tostring(Price, format.mintick), color=color.new(Color, 100), style=label.style_label_left, size=size.normal, textcolor=Color) // Draw a horizontal line at the specified price level LINE = line.new(x1=bar_index, y1=Price, x2=bar_index + barCount, y2=Price, color=Color, width=Width, style=LineStyle) // Remove the line and label from historical data if Historical is false if not Historical label.delete(LABEL[1]) line.delete(LINE[1])
utils
https://www.tradingview.com/script/H99gJok7-utils/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
37
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 // @description Few essentials captured together (subset of arrayutils) library("utils") // @function finds difference between two timestamps // @param timeStart start timestamp // @param endTime end timestamp // @returns [days, hours, minutes, seconds, milliseconds] export timer(int timeStart, int timeEnd=timenow)=> timeDiff = math.abs(timeEnd - timeStart) mseconds = timeDiff seconds = mseconds/1000 minutes = seconds/60 hours = minutes/60 days = hours/24 tmSeconds = mseconds%1000 tSeconds = seconds%60 tMinutes = minutes%60 tHours = hours%24 [days, tHours, tMinutes, tSeconds, tmSeconds] // @function finds difference between two timestamps // @param pivots pivots array // @param barArray pivot bar array // @param dir direction for which overflow need to be checked // @returns bool overflow export check_overflow(float[] pivots, float[] barArray, int dir)=> cBar = int(array.get(barArray, 0)) aBar = int(array.get(barArray, array.size(barArray)-1)) c = array.get(pivots, 0) a = array.get(pivots, array.size(pivots)-1) ln = line.new(aBar, a, cBar, c) overflow = false for [i, currentBar] in barArray peak = array.get(pivots, i) linePrice = line.get_price(ln, int(currentBar)) if(dir*peak > dir*linePrice) overflow := true break line.delete(ln) overflow // @function finds series of pivots in particular trend // @param pivots pivots array // @param length length for which trend series need to be checked // @param highLow filter pivot high or low // @param trend Uptrend or Downtrend // @returns int[] trendIndexes export get_trend_series(float[] pivots, int length, int highLow, int trend)=> startLength = 1 endLength = math.min(array.size(pivots), length) trendIndexes = array.new_int() if(startLength < endLength) first = array.get(pivots, 0) sec = array.get(pivots, 1) dir = first > sec? 1 : -1 while(startLength+(dir==highLow?1:0) < endLength) oTrend = trend*highLow min = array.slice(pivots, startLength, endLength) peak = highLow == 1? array.max(min) : array.min(min) peakIndex = oTrend == 1? array.indexof(min, peak) : array.lastindexof(min, peak) if oTrend == 1 array.insert(trendIndexes, 0, startLength+peakIndex) else array.push(trendIndexes, startLength+peakIndex) if(oTrend == 1? startLength+peakIndex == endLength : peakIndex == 0) break if oTrend == 1 startLength := startLength+peakIndex+1+(dir>0?1:0) else endLength := peakIndex trendIndexes // @function finds series of pivots in particular trend // @param pivots pivots array // @param firstIndex First index of the series // @param lastIndex Last index of the series // @returns int[] trendIndexes export get_trend_series(float[] pivots, int firstIndex, int lastIndex)=> startIndex = firstIndex endIndex = math.min(array.size(pivots), lastIndex) trendIndexes = array.new_int() if(startIndex+1 < endIndex) first = array.get(pivots, startIndex) sec = array.get(pivots, startIndex+1) dir = first > sec? 1 : -1 min = array.slice(pivots, startIndex, endIndex) while(array.size(min) > 1) peak = (dir == 1? array.min(min) : array.max(min)) peakIndex = array.lastindexof(min, peak) min := array.slice(pivots, startIndex, startIndex+peakIndex) reversePeak = (dir == 1? array.max(min) : array.min(min)) if(reversePeak == first) array.push(trendIndexes, startIndex+peakIndex) trendIndexes // @function Consolidates labels into single string by concatenating it with given separator // @param include array of conditions to include label or not // @param labels string array of labels // @param separator Separator for concatenating labels // @returns string labelText export getConsolidatedLabel(simple bool[] include, simple string[] labels, simple string separator = '\n')=> labelText = '' for i=0 to array.size(include)-1 labelText := labelText + (array.get(include, i) ? (labelText == '' ? '' : separator) + array.get(labels, i) : '') labelText // @function gets array of colors based on theme // @param theme dark or light theme // @returns color[] themeColors export getColors(simple string theme="dark")=> str.lower(theme)=="dark"? array.from( color.rgb(251, 244, 109), color.rgb(141, 186, 81), color.rgb(74, 159, 245), color.rgb(255, 153, 140), color.rgb(255, 149, 0), color.rgb(0, 234, 211), color.rgb(167, 153, 183), color.rgb(255, 210, 113), color.rgb(119, 217, 112), color.rgb(95, 129, 228), color.rgb(235, 146, 190), color.rgb(198, 139, 89), color.rgb(200, 149, 149), color.rgb(196, 182, 182), color.rgb(255, 190, 15), color.rgb(192, 226, 24), color.rgb(153, 140, 235), color.rgb(206, 31, 107), color.rgb(251, 54, 64), color.rgb(194, 255, 217), color.rgb(255, 219, 197), color.rgb(121, 180, 183) ) : array.from( color.rgb(61, 86, 178), color.rgb(57, 163, 136), color.rgb(250, 30, 14), color.rgb(169, 51, 58), color.rgb(225, 87, 138), color.rgb(62, 124, 23), color.rgb(244, 164, 66), color.rgb(134, 72, 121), color.rgb(113, 159, 176), color.rgb(170, 46, 230), color.rgb(161, 37, 104), color.rgb(189, 32, 0), color.rgb(16, 86, 82), color.rgb(200, 92, 92), color.rgb(63, 51, 81), color.rgb(114, 106, 149), color.rgb(171, 109, 35), color.rgb(247, 136, 18), color.rgb(51, 71, 86), color.rgb(12, 123, 147), color.rgb(195, 43, 173) )
DatasetWeatherTokyoMeanAirTemperature
https://www.tradingview.com/script/kAqYDCMN-DatasetWeatherTokyoMeanAirTemperature/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
44
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RicardoSantos //@version=5 // @description Provides a data set of the monthly mean air temperature (°C) for the city of Tokyo in Japan. // this was just for fun, no financial implications in this. // reference: // https://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s3_en.php?block_no=47662 // TOKYO WMO Station ID:47662 Lat 35o41.5'N Lon 139o45.0'E library(title='DatasetWeatherTokyoMeanAirTemperature') // @function the years of the data set. // @returns // array<int> : year values. export year_ () => var array<int> year_ = array.from( 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 ) // @function the january values of the dataset // @returns // array\<float> : data values for january. export january () => var array<float> january = array.from( float(na), 1.6, 3.2, 2.3, 3.2, 2.6, 2.1, 4.6, 3.1, 2.6, 0.6, 2.4, 2.7, 3.3, 2.1, 3.4, 2.4, 3.7, 2.6, 3.0, 2.1, 3.3, 3.7, 3.6, 3.2, 1.6, 4.1, 2.4, 4.6, 1.9, 4.3, 2.2, 4.0, 3.2, 2.1, 4.2, 2.5, 3.0, 1.9, 4.3, 3.3, 5.1, 2.3, 1.6, 2.8, 4.1, 4.0, 0.6, 1.7, 2.7, 2.9, 3.1, 2.7, 3.6, 2.6, 3.8, 2.9, 5.9, 3.2, 2.5, 3.7, 2.0, 4.6, 2.7, 2.4, 2.7, 4.8, 2.9, 2.4, 3.0, 1.1, 3.5, 3.4, 4.0, 5.4, 5.0, 3.3, 4.3, 3.3, 4.3, 3.8, 4.2, 5.7, 5.0, 3.7, 5.0, 3.6, 4.5, 3.2, 5.4, 4.4, 4.6, 4.4, 5.7, 5.7, 4.5, 5.1, 6.6, 6.3, 4.4, 4.7, 5.4, 3.4, 5.6, 6.6, 5.6, 4.4, 5.8, 6.2, 3.7, 4.1, 4.5, 5.8, 7.7, 8.1, 5.0, 6.3, 6.8, 6.2, 5.5, 6.3, 6.6, 6.8, 5.3, 6.6, 7.6, 4.9, 7.4, 5.5, 6.3, 6.1, 5.1, 7.6, 5.9, 6.8, 7.0, 5.1, 4.8, 5.5, 6.3, 5.8, 6.1, 5.8, 4.7, 5.6, 7.1, 5.4, 4.9 ) // @function the february values of the dataset // @returns // array\<float> : data values for february. export february () => var array<float> february = array.from( float(na), 3.4, 3.6, 2.5, 5.4, 5.8, 3.7, 5.2, 1.9, 2.7, 2.2, 2.0, 4.3, 2.2, 3.1, 6.1, 3.8, 4.1, 2.2, 3.7, 4.0, 3.5, 3.5, 4.4, 4.2, 3.1, 3.7, 3.8, 4.1, 4.3, 2.7, 2.6, 2.9, 3.4, 3.1, 2.9, 5.2, 6.2, 4.5, 3.5, 4.1, 4.1, 4.5, 3.6, 3.7, 2.6, 3.5, 7.0, 3.0, 4.5, 2.4, 4.6, 2.1, 3.3, 2.9, 5.4, 2.5, 4.3, 3.6, 4.0, 4.8, 2.5, 5.7, 3.4, 4.1, 3.7, 5.0, 2.6, 4.0, 3.2, 1.6, 4.2, 2.7, 5.1, 6.5, 4.7, 4.5, 2.6, 4.2, 5.6, 6.2, 4.3, 4.3, 6.0, 7.3, 6.6, 4.5, 5.9, 4.8, 4.2, 4.7, 7.2, 4.9, 4.3, 5.7, 6.0, 5.9, 5.1, 6.9, 5.1, 5.1, 6.8, 4.9, 4.2, 8.4, 5.2, 5.3, 5.5, 6.1, 3.0, 6.5, 4.3, 6.8, 4.9, 7.5, 7.8, 6.5, 6.9, 7.7, 6.6, 6.5, 5.4, 7.0, 7.0, 6.7, 6.0, 6.6, 7.9, 6.4, 8.5, 6.2, 6.7, 8.6, 5.5, 7.8, 6.5, 7.0, 5.4, 6.2, 5.9, 5.7, 7.2, 6.9, 5.4, 7.2, 8.3, 8.5, 5.2 ) // @function the march values of the dataset // @returns // array\<float> : data values for march. export march () => var array<float> march = array.from( float(na), 8.1, 6.2, 7.2, 8.0, 8.4, 5.3, 6.9, 5.3, 6.1, 4.9, 6.9, 6.9, 7.2, 6.9, 9.2, 8.9, 5.1, 6.2, 8.4, 6.9, 6.0, 5.7, 5.5, 8.5, 5.7, 7.3, 8.4, 7.7, 6.1, 5.6, 7.3, 5.6, 6.2, 6.3, 6.1, 8.2, 8.1, 6.2, 8.8, 6.6, 5.8, 6.5, 6.7, 8.3, 6.6, 6.2, 6.6, 7.9, 5.0, 6.2, 6.3, 6.3, 6.9, 7.1, 8.8, 7.9, 6.9, 5.8, 6.1, 7.1, 6.1, 8.1, 8.8, 7.4, 8.2, 8.2, 10.3, 6.8, 5.6, 6.6, 6.2, 6.8, 6.5, 6.7, 7.7, 8.8, 7.4, 9.4, 8.4, 8.7, 8.6, 6.8, 8.4, 8.9, 9.5, 8.2, 8.2, 7.6, 7.6, 6.9, 9.6, 9.5, 10.0, 7.9, 5.5, 8.3, 9.7, 7.8, 7.3, 7.9, 9.0, 9.3, 8.7, 9.9, 8.2, 9.0, 9.9, 8.6, 5.9, 7.8, 7.8, 9.3, 8.4, 9.6, 10.6, 9.5, 9.7, 8.7, 8.1, 8.9, 9.2, 10.5, 10.1, 10.1, 9.4, 9.8, 12.2, 8.7, 9.8, 9.0, 9.8, 10.8, 10.7, 10.0, 9.1, 8.1, 8.8, 12.1, 10.4, 10.3, 10.1, 8.5, 11.5, 10.6, 10.7, 12.8, 10.9 ) // @function the april values of the dataset // @returns // array\<float> : data values for april. export april () => var array<float> april = array.from( float(na), 12.2, 13.6, 11.5, 12.6, 12.3, 11.6, 13.7, 12.0, 11.6, 10.7, 12.3, 12.2, 12.4, 12.0, 14.2, 12.0, 13.1, 13.3, 13.8, 12.9, 13.7, 11.3, 11.2, 12.8, 11.4, 13.4, 11.6, 12.7, 13.2, 10.9, 12.9, 12.4, 12.3, 13.6, 12.3, 13.8, 13.0, 13.6, 11.8, 11.6, 12.7, 12.7, 11.7, 13.4, 12.6, 13.8, 13.3, 12.0, 14.7, 11.9, 11.1, 13.5, 12.5, 12.6, 14.0, 12.4, 12.3, 12.3, 11.5, 12.5, 12.0, 12.8, 13.2, 12.8, 13.1, 12.7, 13.6, 11.8, 10.6, 13.5, 14.3, 13.1, 14.2, 12.1, 13.9, 13.3, 13.3, 12.7, 14.9, 13.6, 13.1, 14.3, 13.9, 15.3, 12.8, 14.9, 14.1, 13.9, 15.3, 11.1, 13.6, 14.5, 14.1, 14.6, 13.0, 13.5, 13.4, 15.3, 14.8, 14.3, 13.0, 15.1, 13.9, 13.9, 13.6, 13.9, 14.0, 15.9, 11.6, 14.2, 13.9, 14.4, 14.3, 15.6, 14.7, 15.4, 15.1, 13.4, 15.8, 15.0, 12.7, 15.2, 16.3, 15.0, 14.5, 15.7, 16.1, 15.1, 16.4, 15.1, 13.6, 13.7, 14.7, 15.7, 12.4, 14.5, 14.5, 15.2, 15.0, 14.5, 15.4, 14.7, 17.0, 13.6, 12.8, 15.1, 15.3 ) // @function the may values of the dataset // @returns // array\<float> : data values for may. export may () => var array<float> may = array.from( float(na), 17.0, 16.5, 18.3, 18.0, 17.7, 17.2, 16.8, 15.5, 15.5, 15.2, 16.4, 15.2, 16.0, 15.7, 16.1, 18.2, 16.6, 15.8, 16.3, 17.5, 16.6, 17.3, 16.7, 17.9, 17.3, 16.1, 16.3, 15.9, 15.7, 16.9, 16.3, 17.1, 16.1, 16.9, 16.8, 16.2, 16.7, 16.1, 17.8, 15.9, 16.9, 15.8, 16.7, 16.2, 16.8, 16.4, 16.8, 16.8, 16.9, 16.1, 16.3, 17.1, 17.8, 15.9, 17.7, 16.3, 18.0, 18.1, 17.8, 16.7, 16.4, 17.6, 18.7, 17.0, 17.7, 17.6, 17.3, 17.8, 17.7, 15.6, 16.9, 16.9, 18.1, 18.4, 19.2, 18.0, 18.1, 17.8, 17.6, 18.2, 17.6, 17.1, 18.0, 18.5, 17.8, 19.8, 18.4, 18.4, 18.9, 17.2, 17.9, 20.0, 17.5, 19.6, 19.6, 17.4, 18.6, 17.9, 19.3, 18.6, 17.7, 18.7, 19.0, 18.6, 19.2, 17.5, 20.7, 19.7, 17.2, 19.1, 17.9, 19.3, 18.2, 17.7, 19.2, 18.8, 17.3, 18.1, 19.5, 19.1, 18.1, 19.2, 20.5, 19.9, 19.8, 19.5, 18.4, 18.8, 19.6, 17.7, 19.0, 19.8, 18.5, 20.1, 19.0, 18.5, 19.6, 19.8, 20.3, 21.1, 20.2, 20.0, 19.8, 20.0, 19.5, 19.6, 18.8 ) // @function the june values of the dataset // @returns // array\<float> : data values for june. export june () => var array<float> june = array.from( 22.3, 18.5, 22.0, 20.0, 21.4, 19.8, 21.3, 20.4, 19.8, 19.8, 20.3, 20.9, 20.3, 18.6, 20.9, 22.0, 20.3, 21.1, 20.5, 23.6, 20.4, 21.6, 18.8, 19.2, 21.5, 19.3, 20.6, 19.8, 19.7, 21.8, 20.8, 18.4, 19.2, 20.9, 20.2, 20.7, 20.8, 20.1, 20.3, 21.5, 21.9, 22.7, 19.6, 20.1, 19.8, 20.3, 18.8, 21.7, 20.4, 19.4, 20.1, 19.0, 20.5, 20.3, 20.6, 21.4, 20.4, 19.8, 21.9, 22.0, 21.5, 21.4, 19.6, 20.8, 20.7, 22.1, 20.8, 22.2, 21.5, 22.3, 20.4, 23.3, 19.2, 21.6, 19.4, 21.8, 21.2, 21.3, 20.6, 18.3, 22.7, 22.3, 19.8, 22.0, 20.4, 21.5, 22.6, 20.9, 21.8, 21.5, 21.6, 20.1, 23.0, 22.0, 21.8, 20.7, 21.3, 21.4, 19.8, 21.9, 21.6, 21.5, 20.9, 23.8, 24.4, 23.6, 20.2, 21.4, 20.5, 21.8, 20.2, 21.1, 22.1, 22.3, 20.7, 23.5, 23.6, 20.6, 21.7, 22.4, 20.4, 22.6, 22.7, 21.5, 22.8, 22.5, 23.1, 21.6, 23.2, 23.7, 23.2, 22.5, 23.2, 21.3, 22.5, 23.6, 22.8, 21.4, 22.9, 23.4, 22.1, 22.4, 22.0, 22.4, 21.8, 23.2, 22.7, 23.0 ) // @function the july values of the dataset // @returns // array\<float> : data values for july. export july () => var array<float> july = array.from( 26.0, 24.3, 26.5, 26.0, 26.1, 24.2, 24.0, 24.2, 23.7, 23.4, 23.1, 25.0, 23.6, 24.5, 23.4, 23.5, 24.9, 25.7, 25.3, 26.8, 22.1, 24.1, 22.9, 25.9, 23.2, 22.8, 22.1, 21.8, 23.2, 24.8, 23.3, 23.5, 22.7, 22.1, 24.3, 23.0, 24.5, 24.3, 23.3, 25.5, 24.2, 23.9, 25.7, 26.0, 23.6, 26.1, 24.3, 25.0, 24.0, 26.1, 23.2, 24.6, 26.0, 23.4, 25.9, 26.3, 21.8, 25.7, 26.6, 23.9, 24.3, 24.9, 26.3, 25.0, 26.5, 26.9, 23.7, 27.5, 25.1, 25.6, 22.0, 26.2, 25.7, 26.0, 25.3, 26.5, 24.3, 24.3, 24.7, 22.3, 27.6, 24.2, 24.4, 24.9, 26.1, 25.8, 27.4, 25.1, 25.7, 25.5, 24.2, 24.4, 26.3, 24.7, 25.0, 25.4, 25.8, 25.2, 26.1, 23.4, 25.6, 23.9, 25.8, 27.8, 25.2, 23.8, 26.3, 23.1, 23.8, 26.2, 26.3, 23.9, 27.0, 22.4, 24.1, 25.7, 26.7, 25.5, 22.5, 28.3, 26.4, 26.2, 26.6, 25.3, 25.9, 27.7, 28.5, 28.0, 22.8, 28.5, 25.6, 25.6, 24.4, 27.0, 26.3, 28.0, 27.3, 26.4, 27.3, 26.8, 26.2, 25.4, 27.3, 28.3, 24.1, 24.3, 25.9, 27.4 ) // @function the august values of the dataset // @returns // array\<float> : data values for august. export august () => var array<float> august = array.from( 24.9, 26.6, 25.9, 24.6, 26.6, 25.5, 26.7, 24.7, 25.1, 24.1, 25.4, 26.5, 25.3, 25.6, 25.8, 25.4, 25.5, 26.4, 26.2, 27.0, 25.5, 25.9, 25.0, 26.1, 26.1, 26.1, 25.1, 22.9, 25.7, 25.1, 22.2, 24.5, 25.8, 25.4, 25.2, 24.1, 25.6, 25.2, 23.8, 26.4, 25.7, 25.0, 25.0, 26.1, 25.0, 25.7, 25.3, 27.3, 27.2, 26.2, 25.7, 26.3, 26.6, 24.1, 27.1, 26.8, 26.4, 26.7, 27.5, 26.1, 24.8, 26.5, 28.2, 26.0, 25.8, 24.9, 25.4, 27.0, 27.4, 27.5, 26.7, 26.7, 28.0, 25.4, 26.6, 26.2, 26.7, 26.8, 25.0, 27.0, 26.3, 25.4, 27.3, 25.8, 26.7, 26.4, 26.8, 28.1, 26.6, 27.8, 26.7, 26.9, 28.0, 26.6, 27.2, 27.4, 26.7, 26.6, 28.5, 27.1, 27.3, 25.1, 25.0, 28.9, 27.4, 23.4, 26.2, 27.1, 27.5, 28.6, 27.9, 26.8, 27.3, 27.0, 27.1, 28.6, 25.5, 27.0, 24.8, 28.9, 29.4, 26.0, 27.0, 27.2, 28.5, 28.3, 26.4, 28.0, 26.0, 27.2, 28.1, 27.5, 29.0, 26.8, 26.6, 29.6, 27.5, 29.1, 29.2, 27.7, 26.7, 27.1, 26.4, 28.1, 28.4, 29.1, 27.4, 29.6 ) // @function the september values of the dataset // @returns // array\<float> : data values for september. export september () => var array<float> september = array.from( 21.5, 22.6, 21.3, 22.8, 21.3, 22.5, 22.7, 21.1, 21.8, 22.3, 22.1, 23.2, 21.0, 20.9, 20.3, 24.2, 24.3, 23.0, 22.5, 21.9, 22.9, 22.3, 20.9, 21.6, 19.8, 22.6, 22.3, 22.6, 22.3, 21.2, 21.9, 19.7, 21.3, 19.4, 21.8, 20.9, 22.6, 20.2, 20.0, 22.5, 22.7, 23.7, 22.0, 22.6, 22.7, 21.4, 21.3, 23.4, 23.4, 21.8, 22.9, 23.2, 21.2, 23.9, 20.5, 21.5, 22.5, 21.8, 23.1, 21.6, 20.8, 24.2, 22.7, 22.4, 23.7, 21.7, 20.6, 24.9, 24.4, 23.2, 22.4, 23.1, 22.9, 23.8, 22.4, 23.8, 20.7, 22.7, 22.2, 24.6, 22.3, 22.7, 20.8, 23.2, 24.1, 23.6, 25.3, 24.5, 21.4, 22.3, 22.2, 23.2, 22.6, 21.9, 22.8, 24.0, 21.1, 23.1, 23.2, 22.8, 25.2, 22.0, 24.3, 22.2, 24.1, 23.0, 21.8, 22.3, 23.1, 23.5, 23.1, 23.7, 23.3, 22.8, 25.2, 24.8, 23.9, 23.3, 22.9, 24.8, 23.7, 22.4, 22.9, 24.4, 26.2, 25.6, 23.2, 23.1, 24.2, 25.1, 24.7, 23.5, 25.2, 24.4, 23.0, 25.1, 25.1, 26.2, 25.2, 23.2, 22.6, 24.4, 22.8, 22.9, 25.1, 24.2, 22.3, float(na) ) // @function the october values of the dataset // @returns // array\<float> : data values for october. export october () => var array<float> october = array.from( 15.3, 14.8, 15.9, 15.8, 15.0, 16.6, 15.7, 15.4, 16.7, 15.8, 16.1, 16.6, 16.6, 15.0, 14.6, 16.0, 16.5, 16.5, 15.9, 15.4, 16.5, 15.8, 15.2, 16.0, 14.3, 16.5, 16.8, 16.6, 15.2, 16.4, 16.2, 15.1, 15.2, 16.1, 14.8, 16.1, 15.8, 15.9, 15.6, 16.1, 17.6, 15.8, 16.8, 16.0, 16.4, 16.4, 15.4, 16.8, 16.8, 15.4, 16.3, 15.0, 16.7, 16.7, 16.5, 16.7, 16.3, 16.5, 16.8, 14.6, 17.1, 16.0, 16.3, 16.7, 17.9, 17.8, 17.3, 16.4, 17.2, 16.3, 16.8, 17.3, 15.6, 17.4, 16.1, 15.8, 17.3, 17.3, 17.2, 15.5, 17.6, 17.3, 17.2, 16.0, 17.6, 16.8, 18.3, 16.7, 16.3, 15.9, 16.9, 18.9, 16.9, 16.3, 17.3, 17.2, 15.5, 18.5, 17.4, 17.8, 17.3, 17.5, 18.7, 17.3, 19.6, 18.2, 17.6, 18.0, 17.7, 17.7, 17.9, 17.1, 18.9, 17.5, 17.5, 19.2, 18.1, 17.3, 17.5, 20.2, 19.5, 18.0, 18.7, 20.1, 19.5, 18.8, 18.7, 19.0, 17.8, 17.5, 19.2, 19.5, 19.0, 19.4, 19.0, 18.9, 19.5, 19.4, 19.8, 19.1, 18.4, 18.7, 16.8, 19.1, 19.4, 17.5, 18.2, float(na) ) // @function the november values of the dataset // @returns // array\<float> : data values for november. export november () => var array<float> november = array.from( 9.7, 9.1, 9.6, 9.7, 9.7, 10.2, 11.0, 9.6, 10.0, 7.6, 10.7, 10.2, 11.6, 11.4, 9.7, 10.8, 10.4, 9.9, 10.1, 11.6, 9.9, 10.7, 10.1, 10.9, 8.9, 11.0, 10.2, 11.5, 9.1, 9.1, 10.3, 9.3, 11.2, 9.1, 10.0, 10.4, 12.8, 9.4, 10.0, 11.9, 11.1, 11.3, 8.7, 10.4, 11.4, 12.0, 9.3, 10.8, 12.0, 9.9, 11.4, 9.8, 11.2, 11.7, 11.0, 10.3, 11.5, 10.9, 11.2, 10.8, 10.7, 11.2, 11.2, 10.8, 12.3, 12.3, 11.7, 10.1, 10.8, 10.9, 11.3, 12.4, 10.3, 11.9, 10.0, 11.1, 11.4, 12.0, 10.4, 11.7, 11.0, 11.8, 12.9, 11.1, 12.3, 12.3, 12.7, 11.3, 12.1, 11.1, 12.7, 12.9, 12.1, 14.1, 12.8, 12.3, 11.9, 12.3, 12.1, 11.7, 12.7, 11.2, 14.8, 12.9, 14.3, 13.0, 10.4, 14.3, 12.3, 12.2, 13.3, 12.3, 12.8, 11.4, 14.2, 15.1, 13.0, 13.0, 14.1, 13.4, 12.7, 13.2, 14.3, 13.9, 14.2, 13.3, 13.1, 11.6, 14.4, 15.6, 13.3, 14.4, 13.3, 13.1, 13.5, 13.5, 14.9, 12.7, 13.5, 14.2, 13.9, 11.4, 11.9, 14.0, 13.1, 14.0, 13.7, float(na) ) // @function the december values of the dataset // @returns // array\<float> : data values for december. export december () => var array<float> december = array.from( 4.6, 4.8, 5.8, 5.1, 8.0, 3.9, 4.3, 5.0, 5.0, 3.4, 5.7, 4.7, 5.7, 5.2, 4.9, 9.3, 5.6, 3.3, 4.7, 5.8, 5.4, 4.8, 3.7, 6.4, 5.5, 5.5, 4.5, 7.1, 4.1, 5.3, 6.8, 5.9, 4.5, 4.6, 4.6, 4.3, 5.0, 4.7, 5.2, 5.8, 5.6, 6.8, 4.0, 3.9, 5.3, 5.2, 5.0, 4.0, 5.6, 5.2, 6.8, 4.1, 5.5, 5.4, 8.6, 5.2, 6.9, 6.0, 6.2, 5.9, 5.5, 6.2, 5.2, 5.9, 5.4, 6.2, 6.9, 5.4, 5.7, 4.3, 4.8, 4.7, 4.1, 7.9, 6.0, 5.4, 7.3, 5.3, 7.6, 7.1, 7.9, 5.0, 8.0, 7.9, 7.0, 6.7, 7.2, 7.0, 8.1, 7.5, 7.0, 6.6, 6.7, 10.2, 7.2, 6.8, 7.9, 8.1, 6.6, 6.7, 6.7, 7.3, 8.9, 8.5, 10.1, 7.7, 7.6, 9.5, 7.1, 7.7, 7.4, 8.5, 8.1, 8.4, 9.2, 10.0, 9.2, 9.4, 8.5, 9.0, 7.7, 9.3, 9.2, 9.0, 9.0, 8.8, 8.4, 7.2, 9.2, 9.9, 6.4, 9.5, 9.0, 9.8, 9.0, 9.9, 7.5, 7.3, 8.3, 6.7, 9.3, 8.9, 6.6, 8.3, 8.5, 7.7, 7.9, float(na) ) // @function the annual values of the dataset // @returns // array\<float> : data values for annual. export annual () => var array<float> annual = array.from( 17.0, 13.6, 14.2, 13.8, 14.6, 14.1, 13.8, 14.0, 13.3, 12.9, 13.1, 13.9, 13.8, 13.5, 13.3, 15.0, 14.4, 14.0, 13.8, 14.8, 13.8, 14.0, 13.2, 14.0, 13.8, 13.6, 13.9, 13.7, 13.7, 13.7, 13.5, 13.1, 13.5, 13.2, 13.6, 13.5, 14.4, 13.9, 13.4, 14.7, 14.2, 14.5, 13.6, 13.8, 14.1, 14.2, 13.6, 14.4, 14.2, 14.0, 13.8, 13.6, 14.1, 14.1, 14.3, 14.8, 14.0, 14.6, 14.7, 13.9, 14.1, 14.1, 14.9, 14.5, 14.7, 14.8, 14.6, 15.0, 14.6, 14.2, 13.6, 14.9, 14.1, 15.2, 14.6, 15.1, 14.7, 14.6, 14.6, 14.8, 15.5, 14.7, 14.9, 15.2, 15.7, 15.4, 15.9, 15.4, 15.0, 15.3, 14.6, 15.5, 15.7, 15.6, 15.6, 15.2, 15.0, 15.7, 15.7, 15.2, 15.6, 15.0, 15.8, 16.1, 16.9, 15.4, 15.0, 16.0, 15.7, 14.9, 15.7, 15.2, 16.3, 15.4, 16.4, 17.0, 16.4, 16.0, 15.5, 16.9, 16.3, 15.8, 16.7, 16.7, 17.0, 16.9, 16.5, 16.7, 16.0, 17.3, 16.2, 16.4, 17.0, 16.4, 16.7, 16.9, 16.5, 16.3, 17.1, 16.6, 16.4, 16.4, 15.8, 16.8, 16.5, 16.5, 16.6, 15.1 ) // @function get the temperature values for a specific month. // @param idx int, month index (1 -> 12 | any other value returns annual average values). // @returns // array\<float> : data values for selected month. export select_month (int idx) => switch idx 01 => january() 02 => february() 03 => march() 04 => april() 05 => may() 06 => june() 07 => july() 08 => august() 09 => september() 10 => october() 11 => november() 12 => december() => annual() // @function get the temperature value of a specified year and month. // @param year_ int, year value. // @param month_ int, month index (1 -> 12 | any other value returns annual average values). // @returns // float : value of specified year and month. export select_value (int year_, int month_) => int _idx = array.indexof(year_(), year_) array.get(select_month(month_), _idx) //float sum = 0.0 //for _i = 1875 to 2022 // sum += nz(select_value(_i, 01)) //plot(sum) //plot(array.sum(january)) // @function the difference of the month air temperature (ºC) to the median of the sample. // @param month_ int, month index (1 -> 12 | any other value returns annual average values). // @returns // float : difference of current month to median in (Cº) export diff_to_median (int month_) => var array<float> _month_data = select_month(month_) int _idx = bar_index % array.size(_month_data) float _diff = array.get(_month_data, _idx) - array.median(_month_data) plot(diff_to_median(00), color=color.rgb(255, 255, 255, 0), style=plot.style_circles) plot(diff_to_median(01), color=color.rgb(000, 150, 255, 0), style=plot.style_circles) plot(diff_to_median(02), color=color.rgb(000, 200, 255, 0), style=plot.style_circles) plot(diff_to_median(03), color=color.rgb(000, 255, 255, 0), style=plot.style_circles) plot(diff_to_median(04), color=color.rgb(100, 200, 255, 0), style=plot.style_circles) plot(diff_to_median(05), color=color.rgb(200, 150, 255, 0), style=plot.style_circles) plot(diff_to_median(06), color=color.rgb(255, 100, 255, 0), style=plot.style_circles) plot(diff_to_median(07), color=color.rgb(255, 000, 255, 0), style=plot.style_circles) plot(diff_to_median(08), color=color.rgb(255, 100, 255, 0), style=plot.style_circles) plot(diff_to_median(09), color=color.rgb(255, 150, 255, 0), style=plot.style_circles) plot(diff_to_median(10), color=color.rgb(200, 200, 255, 0), style=plot.style_circles) plot(diff_to_median(11), color=color.rgb(100, 255, 255, 0), style=plot.style_circles) plot(diff_to_median(12), color=color.rgb(000, 150, 255, 0), style=plot.style_circles) plot(bar_index % array.size(annual()) == 0?0:na, color=color.white, style=plot.style_circles, linewidth=4)